diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48912cf..12615a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -182,6 +182,12 @@ jobs: "$test" done + # The SDK ships this file and runs it; it must be exactly what was published. + - name: Check the bundled SDK Core against its recorded sha256 + run: | + scripts/sdk-core/update-bundled-sdk-core.sh --check + scripts/sdk-core/test/update-bundled-sdk-core.test.sh + - name: Upload coverage for Sonar uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 23f0f9d..53d34ea 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -11,6 +11,8 @@ name: E2E # Cloudflare quick tunnel (e2e/tunnel) and the two jobs, side by side (neither needs the other), swap run # artifacts: the tunnel URL one way, the journey result the other. A job's outputs only publish # when it ends, which is why the hand-off uses artifacts. +# - Both platforms also run e2e/react-native/run-sdk-core.sh: SDK Core's conformance script in the +# SDK's real hidden WebView, against a test server the spec starts itself (no Formbricks server). on: workflow_call: inputs: @@ -136,7 +138,10 @@ jobs: force-avd-creation: true emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none -accel on -no-snapshot disable-animations: true - script: e2e/react-native/run-journey.sh android test + # Then SDK Core's conformance script in the SDK's real hidden WebView. + script: | + e2e/react-native/run-journey.sh android test + e2e/react-native/run-sdk-core.sh android - name: Assert the response through the V1 API run: e2e/server/assert-response.sh @@ -318,6 +323,10 @@ jobs: - name: Build the playground and the Detox framework run: e2e/react-native/run-journey.sh ios build + # Needs no server, so it runs while the server job boots. + - name: Run SDK Core's conformance script in the SDK's hidden WebView + run: e2e/react-native/run-sdk-core.sh ios + - name: Wait for the server's tunnel URL id: server env: diff --git a/AGENTS.md b/AGENTS.md index 6c2359a..d16cab3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ ## Project Structure & Module Organization This repository is a `pnpm` workspace with two main packages: -- `packages/react-native`: the published SDK (`@formbricks/react-native`). Source lives in `src/`, grouped by domain under `src/lib/`, with React components in `src/components/` and shared types in `src/types/`. +- `packages/react-native`: the published SDK (`@formbricks/react-native`). It is a shell around SDK Core (see `GLOSSARY.md`): the shell is `src/sdk-core/`, React components are in `src/components/`, the rest of `src/lib/` is local state (appearance, Embedded Data, logging), and the bundled SDK Core is `assets/sdk-core/`. Targeting rules belong in SDK Core, in the formbricks monorepo, not here. - `apps/playground`: an Expo app for manual testing and integration checks. App code is in `src/`, with static assets in `assets/`. GitHub Actions run every check from `.github/workflows/ci.yml`; its `PR Check Summary` job is the only required check. `release.yml` publishes. @@ -24,6 +24,8 @@ Run commands from the repository root unless package-scoped work is needed. - `pnpm api:update`: regenerate `packages/react-native/etc/react-native.api.md`. Commit it whenever the public API changes. - `pnpm package-check`: after a build, run publint, attw, and install the `npm pack` tarball into a scratch consumer. - `pnpm --filter playground ios` / `pnpm --filter playground android`: launch the Expo playground on a device target. +- `e2e/react-native/run-sdk-core.sh android|ios`: run SDK Core's conformance script in the SDK's real hidden WebView, on the playground `e2e/react-native/run-journey.sh build` built. +- `scripts/sdk-core/update-bundled-sdk-core.sh --commit [manifest-url]` / `--check`: update the bundled SDK Core from a server's manifest, checked against the formbricks/formbricks commit that records it; or check it against its recorded sha256 and commit. ## Coding Style & Naming Conventions Use TypeScript with strict compiler settings. Biome is the formatter and linter; run `pnpm format` before large refactors. The repo uses spaces for indentation, double quotes, and semicolons. diff --git a/GLOSSARY.md b/GLOSSARY.md index f7bc400..f7a7d39 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -6,7 +6,7 @@ Terms the React Native SDK (`packages/react-native`) uses, grouped by area. Use - **Workspace**: the Formbricks space the app's surveys, action classes and styling belong to, identified by `workspaceId` (`TWorkspace`, `src/lib/workspace/`). Replaces the older term _environment_: `environmentId` is a deprecated alias that still works, and stored configs that use it are migrated. - **App URL**: the Formbricks instance the SDK talks to (`appUrl`), passed to `setup()` with the workspace ID. -- **Config**: the SDK's persisted state (`TConfig`, `RNConfig`): workspace ID, app URL, workspace state, user state and filtered surveys, stored in AsyncStorage. +- **Saved data**: the one JSON string SDK Core saves (workspace ID, app URL, workspace state, user state and filtered surveys), stored in AsyncStorage under `formbricks-react-native`. The shell only stores it. Formerly _config_. - **Workspace state**: the workspace's surveys, action classes and settings as fetched from the server, cached with an expiry (30 minutes) and refetched when it lapses. ## Users @@ -15,7 +15,7 @@ Terms the React Native SDK (`packages/react-native`) uses, grouped by area. Use - **Attributes**: key/value facts about the user (`setAttribute()`, `setAttributes()`, `setLanguage()`), sent to the server and used for targeting. - **User state**: what the server knows about the user (`TUserState`): user ID, segments, displays, responses, last display time and language. - **Segment**: a server-defined group of users; the SDK only receives the IDs of the segments a user belongs to and never evaluates segment filters itself. -- **Interaction refresh**: refetching a user's segments after a survey display, response or finish, gated per survey by `interactionRefresh` (`src/lib/user/interaction-refresh.ts`). +- **Interaction refresh**: refetching a user's segments after a survey display, response or finish, gated per survey by `interactionRefresh` (done by SDK Core). ## Surveys @@ -23,14 +23,22 @@ Terms the React Native SDK (`packages/react-native`) uses, grouped by area. Use - **Action class**: the workspace's definition of an action (`TActionClass`), either `code` (tracked from the app) or `noCode`. - **Trigger**: an action class a survey listens for (`survey.triggers`). - **Display option**: how often a survey may show to one user (`displayOnce`, `displayMultiple`, `displaySome`, `respondMultiple`). -- **Filtered surveys**: the surveys this user is eligible for after display options, recontact days and segments are applied (`filterSurveys`). +- **Filtered surveys**: the surveys this user is eligible for after display options, recontact days and segments are applied (by SDK Core). - **Display**: one time a survey was shown to a user. - **Response**: a user's answers to a survey. - **Embedded Data**: app context attached to responses with `setEmbeddedData()` / `clearEmbeddedData()`. Held in memory, synchronous and never queued. A survey takes a snapshot of it when it opens, so later changes reach only surveys opened afterwards; values land only on fields the survey declares as ingested. -- **Survey web view**: the WebView that renders a survey with the Formbricks renderer (`src/components/survey-web-view.tsx`), mounted by the `` component. +- **Survey web view**: the WebView that renders a survey SDK Core asked to show, with the Formbricks renderer (`src/components/survey-web-view.tsx`), mounted by the `` component. - **Appearance**: how surveys render, `light`, `dark` or `system` (`setAppearance()`); kept in memory only, never sent to the server. -## Internals - -- **Command queue**: runs the public async methods (`track`, `setUserId`, `setAttributes`, `logout`, …) one at a time, in order (`CommandQueue`). -- **Update queue**: debounces user ID and attribute updates into one request to the server (`UpdateQueue`). +## SDK Core + +- **SDK Core**: the one TypeScript package (in the formbricks monorepo) with all the targeting rules every Formbricks SDK shares: setup and sync, users and the update queue, which survey shows and when. This SDK runs its mobile build. _Avoid_: brain, mobile core. +- **Shell**: this SDK's own part (`src/sdk-core/`): it runs SDK Core and does only what SDK Core asks: store a string, make an HTTP call to the app URL's origin, show a survey, write a log line. +- **Engine**: where SDK Core runs: a hidden 0×0 WebView inside ``, on a blank page with the CSP `default-src 'none'`. Each mount starts SDK Core afresh from the saved data. +- **Bridge contract**: the JSON messages SDK Core and the shell send each other (`start`, `command`, `http.request`, `survey.show`, …). +- **Bundled copy**: the SDK Core file shipped inside this SDK (`packages/react-native/assets/sdk-core/mobile.umd.cjs`), with the `{version, sha256}` it was published with and the formbricks/formbricks `commit` that records the same copy. `scripts/sdk-core/update-bundled-sdk-core.sh` updates it and CI checks it. +- **Manifest**: the server's list of SDK Core copies, with version and SHA-256 (`/js/sdk/mobile.json`). A server from before 6.3 has none. +- **Stored copy**: the last downloaded SDK Core file that passed the hash check, kept in AsyncStorage per app URL. +- **Loader**: the part of the shell that picks, downloads and checks SDK Core copies (`src/sdk-core/loader.ts`). Anything it can't use falls back to the bundled copy. +- **Protocol**: SDK Core's major version; the shell runs only copies of its own. +- **Conformance script**: a fake SDK Core every shell runs in its real engine to prove it follows the bridge contract (`assets/sdk-core/conformance.umd.cjs`; never published). diff --git a/apps/playground/e2e/golden-journey.e2e.js b/apps/playground/e2e/golden-journey.e2e.js index d65303a..a855ba5 100644 --- a/apps/playground/e2e/golden-journey.e2e.js +++ b/apps/playground/e2e/golden-journey.e2e.js @@ -44,8 +44,9 @@ const TRACK_RETRY_INTERVAL_MS = 10_000; const STEP_TIMEOUT_MS = 30_000; const RESPONSE_TIMEOUT_MS = 60_000; -// The SDK's WebView is the only one in the app, so `web` needs no matcher. -const webElement = (matcher) => web.element(matcher); +// The survey's WebView, by its testID: SDK Core runs in a second, 0×0 WebView. +const SURVEY_WEBVIEW = by.id("formbricks-survey-webview"); +const webElement = (matcher) => web(SURVEY_WEBVIEW).element(matcher); const expectStatus = (text) => waitFor(element(by.id("status"))) @@ -93,14 +94,12 @@ const read = async (matcher, fn, args = []) => { * - `typeInto` types into a survey text field. Android: Espresso-Web's key events. iOS: Detox's * web typing left the field empty, so the value is set the way the browser does it and an input * event follows, which is what the renderer listens to. - * - `webViewClass`: the native class of the survey's WebView. */ const PLATFORMS = { android: { afterFill: async () => {}, press: (matcher) => webElement(matcher).tap(), typeInto: (matcher, text) => webElement(matcher).replaceText(text), - webViewClass: "android.webkit.WebView", }, ios: { afterFill: (testID) => element(by.id(testID)).tapReturnKey(), @@ -116,7 +115,6 @@ const PLATFORMS = { }`, [text], ), - webViewClass: "WKWebView", }, }; @@ -133,12 +131,11 @@ const press = (matcher) => platform().press(matcher); const typeInto = (matcher, text) => platform().typeInto(matcher, text); /** - * Passes only once no WebView is on screen (the survey's is the only one). A native query, so a + * Passes only once the survey's WebView is gone. A native query, so a * failed web query is never mistaken for a closed survey, and errors such as the app being gone * propagate. */ -const surveyIsClosed = () => - expect(element(by.type(platform().webViewClass))).not.toExist(); +const surveyIsClosed = () => expect(element(SURVEY_WEBVIEW)).not.toExist(); const SETTLE_MS = 2_000; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -148,7 +145,7 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); * WebView is still being created can take the app down on a cold Android emulator. */ const surveyIsOpen = async () => { - await expect(element(by.type(platform().webViewClass))).toExist(); + await expect(element(SURVEY_WEBVIEW)).toExist(); await sleep(SETTLE_MS); await expect(webElement(by.web.xpath(NPS_9))).toExist(); }; diff --git a/apps/playground/e2e/jest.config.js b/apps/playground/e2e/jest.config.js index 645dd23..e543831 100644 --- a/apps/playground/e2e/jest.config.js +++ b/apps/playground/e2e/jest.config.js @@ -1,4 +1,4 @@ -// Jest runs only the Detox journey; plain CommonJS, so no transform. +// Jest runs the Detox specs (the golden journey, SDK Core conformance); plain CommonJS, no transform. /** @type {import('jest').Config} */ module.exports = { rootDir: "..", diff --git a/apps/playground/e2e/sdk-core-conformance.e2e.js b/apps/playground/e2e/sdk-core-conformance.e2e.js new file mode 100644 index 0000000..f59aa89 --- /dev/null +++ b/apps/playground/e2e/sdk-core-conformance.e2e.js @@ -0,0 +1,63 @@ +/** + * SDK Core's conformance script in the SDK's real hidden WebView (the playground's conformance + * screen, src/sdk-core-conformance.tsx). This file is the script's test server: the app reaches it + * at http://127.0.0.1:3457 and, as the second origin the shell must refuse, http://localhost:3457. + * Android reaches the host through `adb reverse`. No Formbricks server is needed. + */ +const http = require("node:http"); +const { by, device, element, waitFor } = require("detox"); + +const PORT = 3457; +const OTHER_ORIGIN = `http://localhost:${PORT}`; + +/** What the script's README asks of the server. */ +const answer = (request, body, response) => { + if (request.method === "GET" && request.url === "/conformance/config") { + response.writeHead(200, { "Content-Type": "application/json" }); + response.end(JSON.stringify({ otherOrigin: OTHER_ORIGIN })); + } else if (request.method === "POST" && request.url === "/conformance/echo") { + response.writeHead(201, { + "X-Conformance": request.headers["x-conformance"] ?? "", + }); + response.end(body); + } else { + response.writeHead(404); + response.end(); + } +}; + +let server; + +describe("SDK Core conformance", () => { + beforeAll(async () => { + server = http.createServer((request, response) => { + const chunks = []; + request.on("data", (chunk) => chunks.push(chunk)); + request.on("end", () => answer(request, Buffer.concat(chunks), response)); + }); + await new Promise((resolve) => server.listen(PORT, resolve)); + await device.launchApp({ newInstance: true, delete: true }); + if (device.getPlatform() === "android") await device.reverseTcpPort(PORT); + // SDK Core keeps timers busy, so Detox would wait for "idle" forever. + await device.disableSynchronization(); + }); + + afterAll(async () => { + await new Promise((resolve) => server.close(resolve)); + }); + + it("passes every check in the SDK's hidden WebView", async () => { + await waitFor(element(by.id("sdk-core-conformance-button"))) + .toBeVisible() + .whileElement(by.id("playground-scroll")) + .scroll(300, "down"); + await element(by.id("sdk-core-conformance-button")).tap(); + + const result = element(by.id("sdk-core-conformance-result")); + await waitFor(result).not.toHaveText("running").withTimeout(180_000); + const { text } = await result.getAttributes(); + const locale = await element(by.id("hermes-intl-locale")).getAttributes(); + console.log(`${text}; ${locale.text}`); + if (text !== "passed") throw new Error(`SDK Core conformance ${text}`); + }); +}); diff --git a/apps/playground/metro.config.js b/apps/playground/metro.config.js new file mode 100644 index 0000000..bdbf57f --- /dev/null +++ b/apps/playground/metro.config.js @@ -0,0 +1,17 @@ +// Expo's defaults, plus one name for the SDK's conformance build (packages/react-native/ +// dist-conformance, made by its `build`), which only the SDK Core conformance screen imports. +const path = require("node:path"); +const { getDefaultConfig } = require("expo/metro-config"); + +const config = getDefaultConfig(__dirname); +const conformanceBuild = path.resolve( + __dirname, + "../../packages/react-native/dist-conformance/index.js", +); +const resolveRequest = config.resolver.resolveRequest; +config.resolver.resolveRequest = (context, name, platform) => + name === "@formbricks/react-native-conformance" + ? { type: "sourceFile", filePath: conformanceBuild } + : (resolveRequest ?? context.resolveRequest)(context, name, platform); + +module.exports = config; diff --git a/apps/playground/package.json b/apps/playground/package.json index 943258a..2f4bcfc 100644 --- a/apps/playground/package.json +++ b/apps/playground/package.json @@ -4,8 +4,8 @@ "main": "index.ts", "scripts": { "dev": "expo start --reset-cache", - "android": "expo start --android", - "ios": "expo start --ios", + "android": "expo run:android", + "ios": "expo run:ios", "clean": "rimraf .turbo node_modules .expo", "build": "expo export --no-bytecode", "check-types": "tsc --noEmit", diff --git a/apps/playground/src/app.tsx b/apps/playground/src/app.tsx index ad9792a..ba56d54 100644 --- a/apps/playground/src/app.tsx +++ b/apps/playground/src/app.tsx @@ -21,6 +21,8 @@ import { View, } from "react-native"; +import { SdkCoreConformance } from "./sdk-core-conformance"; + LogBox.ignoreAllLogs(); type SdkConfig = { appUrl: string; workspaceId: string }; @@ -45,6 +47,7 @@ export default function App(): JSX.Element { const [attributeValue, setAttributeValue] = useState("pro"); const [action, setAction] = useState("qa-action"); const [status, setStatus] = useState("Not set up"); + const [conformance, setConformance] = useState(false); // The status line tells a person (and the E2E journey) that a call has returned. const run = (label: string, call: () => Promise): void => { @@ -59,6 +62,8 @@ export default function App(): JSX.Element { const inputStyle = [styles.input, { color: textColor }]; + if (conformance) return ; + return ( run("setLanguage(de)", () => setLanguage("de"))} /> + + {/* e2e/sdk-core-conformance.e2e.js; it clears the SDK's saved data. */} +