@ultimat3/testing 31.25.0 → 31.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -54,6 +54,7 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
54
54
  | Every `e2eTest` is audited | `e2e-a11y*.ts`, `ax-node.ts`; no switch, `allow` needs a `because` † |
55
55
  | The exercise pass runs what is registered | `exercise.ts` (`runExercisePass`): every action, query, job once, own tenant pair; overrides only via `defineExercise` † |
56
56
  | A route `load` is exercised like a read | `exercise-route-loads.ts`: after the primitives, own tenant pair, swept and planned with them; its record is `RouteLoadRecord`, never in `records`; the crash proof's runs pace on the frozen clock (`exercise-crash.ts`) |
57
+ | Route entries, push | `defineExercise(…, { routes })` (`define-exercise-routes.ts`); a push is a `push` effect (`exercise-report.ts`) |
57
58
  | An override `input` is awaited, as the call's actor | `exercise-override-input.ts`: inside the call's own request — the one way to a signed input † |
58
59
  | A passkey test signs for real | `softAuthenticator` is `@ultimat3/auth/soft-authenticator`'s, never re-exported here (one value, one path: `flight-copies`) and never a second one (auth's own suites need it, and auth cannot import testing) |
59
60
  | A reached job is crash-proven | `exercise-crash.ts`: only `diverged` is red (`X_JOB_CRASH_DIVERGED`) † |
@@ -69,6 +70,7 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
69
70
  | One seed writer | `entitySeedWriter({ entities, client \| driver })` (`seed-writer.ts`) writes through each entity's own repository; `snapshot` is required; `entity` loads on the first write, so the barrel stays entity-free |
70
71
  | Factory values are DECLARED | `seed-graph-values.ts` for `factoriesFor` and `seedGraph`: default, enum, kind, pattern, `$meta.schema` — never the name † |
71
72
  | e2e without a driver | `e2eTest` becomes `test.skip`; the gate reports the step SKIPPED (or `X_VERIFY_SUITE_VANISHED` when `x.verify.json` requires it), never passed |
73
+ | A server is DECLARED, never probed by hand | `{ needs: ['postgres' \| 'redis' \| 'nats'] }` on every typed registrar (`test-types-services.ts`, `TEST_SERVICE_ENV`): unset `TEST_*_URL` is a `test.skip` whose name carries the variable and the start command, never a hand-rolled runner or `describe.skipIf` |
72
74
  | The seam has an inverse | `resetE2eDriver()`: `useE2eDriver` writes MODULE scope, so a file that installs a browser undoes it |
73
75
  | Built vs declared | `clock` `mail` `network` `runJobs` `statements` `subscribe` are built in-process; `page` `budget` `signIn` `deploy` are declared and wait for a driver (`X_TEST_FIXTURE_UNAVAILABLE`). |
74
76
  | `page` HAS a driver; `budget`, `signIn`, `deploy` do not | `installE2eDriver({ page, baseUrl })` registers `page` only. Byte counts, a sign-in route and a new build id are facts no page port can answer; a no-op would read as proof |
@@ -87,6 +89,7 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
87
89
  | A catalog restore is a MERGE, never a replace | the other three registries are replaced with the snapshot. `registerCatalog` has no inverse, so all a file can cost its neighbour is a `resetCatalogs()` |
88
90
  | A file's policy environment is ITS import graph | at the body's start the permission set and role map narrow to names a module the file's import graph reaches declared (`import-graph.ts`, `registry-environment.ts`), plus the preload's and any first declared during this load; the body's own declarations end with the file. Framework repo only: an app keeps the union (`loadApp()` is no static edge) |
89
91
  | Noted driver stores and mounted admins end with the file | `driver-store-boundary.ts`: back to the preload's notes (a store noted at a fixture's import is no later file's); `admin-mount-boundary.ts`: back to what the body inherited. Read through the require cache / the global symbol — never an import |
92
+ | So do channels, mcp recipes/remote servers, the authenticator and the persister | `declaration-boundary.ts` (`DECLARATION_TABLES`) and `factory-persist.ts`: back to what the body inherited; an owner unloaded at the body's start is left alone. `process-registries.test.ts` ledgers every module-scope `Map`/`Set` beside a `register*`/`define*` export — a new one reds until its row says restored, rerun, reported, boot or open |
90
93
  | Permissions are still REPLACED at a file boundary, and it is measured | a dynamic `loadApp()`'s `definePermissions()` is dropped there. Open. Full rule: `docs/history/testing.md` |
91
94
  | Guarded state is boot state | the guard covers only registries that must be clean at file end — `declareTags` and `registerTier` are boot installs; "filled" and "cleared" are two questions. Full rule: `docs/history/testing.md` |
92
95
  | An empty registry is a premise you state | a test whose subject is "nothing is declared" — `x db gen` with nothing to generate — calls `isolateEntityRegistry()` and restores in a `finally`. |
@@ -107,6 +110,7 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
107
110
  | A port's contract is shared examples | one suite per port on `@ultimat3/testing/conformance`: `behavesLike(<port>Conformance, () => yours)`, each with a broken adapter that must fail † |
108
111
  | An island needs a BUILDER, not an import | `buildIslands` is `@ultimat3/cli`'s; `testing → cli` fails `bun run boundaries` |
109
112
  | `mountIsland` AWAITS `mount` | `IslandEntry['mount']` returns `unknown`, not `void`, and the call is awaited |
113
+ | An island chunk counts for its source | under `ISLAND_COVERAGE_ENV` (`runCovered` sets it) `mountIsland` asks the builder for `coverage: true` and records each chunk's `map` (`fixture-island-coverage.ts`); the CLI credits the chunk's lines to the `.island.tsx` |
110
114
  | Dispose STOPS the island, then restores the globals | when `mount` resolved to a function, `[Symbol.dispose]` calls it BEFORE `restore()` |
111
115
  | The micro-DOM is the fixture's, once **for islands** | `island-dom.ts`. Full rule: `docs/history/testing.md` |
112
116
  | The micro-DOM records and does not pretend | records `style`/`classList`; the box is 0 until written; `ResizeObserver` never fires itself † |
package/README.md CHANGED
@@ -40,6 +40,9 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
40
40
  | `exercise.ts` | `runExercisePass({ entities, writer, roles, seed?, overrides?, only? })` — every registered action, query and job once, each on its own committed tenant pair, one `ExerciseRecord` per primitive, the tenant proof's verdict on its `tenant`. What `x exercise` runs |
41
41
  | `exercise-route-subjects.ts` · `exercise-route-loads.ts` | `routeLoadSubjects()` — every `app/`/`site/` file route with a `load`; handed to `runExercisePass({ …, routes, onRoutes })`, each load runs after the primitives in a tenant pair of its own (an `:id` bound to a seeded row, else the route's `prerender()` sample), one `RouteLoadRecord` each with the statement ceiling, scale and plan proofs |
42
42
  | `define-exercise.ts` | `defineExercise({ <name>: { actor, input?, runs? } \| { off: '<why>' } }, { actor?: <entity>, factories?: { <entity name>: defineFactory(…) }, setup?: () => mockFetch(…) \| cassette(…) })` — an app's overrides (the second argument names the entity whose rows are the actors, and the factories that build a table no generated row satisfies — a cross-column `satisfies` — keyed by entity name, unknown ones `X_DECLARATION_UNKNOWN`), `apps/web/exercise.ts`'s one export; a blank `off` is `X_CONTRACT_EXERCISE_UNDECLARED`, an unknown name `X_DECLARATION_UNKNOWN` when the pass runs. An entry's `statements: { max, why }` moves that primitive's statement ceiling (a blank `why` is `X_CONTRACT_EXERCISE_UNDECLARED`, `max` a whole count ≥ 1) |
43
+ | `define-exercise-routes.ts` · `exercise-route-override.ts` | `defineExercise(…, { routes: { '<pattern>': { params?, search?, actor?, statements?, empty? } \| { off } } })` — a route load's entry, keyed by its URL pattern: `params`/`search` (values or functions) and an `actor` function (of the seated actor: the app's request-boundary resolution, facts and all) run in the load's own request before the observed call; `off` makes the record `off`; an unknown pattern is `X_DECLARATION_UNKNOWN` before a row; a blank reason `X_CONTRACT_EXERCISE_UNDECLARED`. `empty: '<why>'` on any entry rides the record as `empty` |
44
+ | `exercise-shard.ts` | `runExercisePass({ …, shard: { index, total } })` — the `index`-th of `total` disjoint slices (primitives, then routes, by registry position); ignored beside `only` |
45
+ | `exercise-report.ts` (push) | `{ kind: 'push', host, count }`: each `outbound.request` with vendor `push` the observed call made — a pusher that sends nothing leaves none |
43
46
  | `exercise-setup.ts` | `withExerciseSetup(room, setup)`: the app's `setup` run inside the sealed room before the first row, its handle disposed before the room restores the network; an `allowHost` in it is `X_EXERCISE_SETUP_UNSEALED`. Types `ExerciseSetup`, `ExerciseSetupHandle` |
44
47
  | `exercise-actor.ts` · `exercise-input.ts` · `exercise-report.ts` | the first `x policy explain` actor the policy allows, minted in the primitive's tenant · the input: override, then a seeded id by field stem, then the minimal draw (`@ultimat3/schema/sample`, loaded dynamically) · the room one run executes in (network sealed, mail captured, clock frozen) and its record |
45
48
  | `exercise-override-line.ts` | `overrideLine`, the entry an unreached record says to paste: valid TS — the actor the pass ran as (`testActor(name, { roles, permissions }).actor`, `null` signed out, left out when the entry declares one) and each id field bound to the seeded row the pass used; an id it could not bind is the string `UNBOUND_ID` |
@@ -78,6 +81,7 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
78
81
  | `fixture-{clock,mail,jobs,network,statements}.ts` | the five fixtures the framework builds in-process |
79
82
  | `fixture-drivers.ts` | the five it declares but a driver must build — `page` `budget` `signIn` `deploy` `subscribe` |
80
83
  | `fixture-island.ts` | `mountIsland()` — build an island, import its chunk, run its `mount`. The BUILDER is a parameter |
84
+ | `fixture-island-coverage.ts` | `ISLAND_COVERAGE_ENV` — under `x verify`'s coverage run, each mounted chunk's source map is recorded so its lines count for the island's source |
81
85
  | `island-dom.ts` | the micro-DOM `mountIsland` drives: what compiled Solid touches, and nothing else |
82
86
  | `island-selector.ts` | the selector grammar `find`/`all` read — compounds and two combinators — and the refusal for the rest |
83
87
  | `island-observers.ts` | `ResizeObserver`, recording; `deliverResize` is the test's hand on the browser's layout |
@@ -321,7 +325,7 @@ there is no flag on the fixture and no code to silence.
321
325
  | `contractTest` | OpenAPI diff vs the committed spec, MCP exposure | `contract` |
322
326
  | `liveTest` | exactly what each subscriber receives | `live` |
323
327
  | `jobTest` | step sequence, retries, idempotency | `job` |
324
- | `e2eTest` | a browser driver; with none registered it SKIPS, and the gate's `e2e` step passes over the skip — ask `hasE2eDriver()` rather than reading that as a pass. Every one audits the page's accessibility tree; the only exception is `{ a11y: { allow: [{ role, selector, because }] } }` ([Testing](https://github.com/developerz-ai/ultimate/wiki/Testing#the-accessibility-audit)) | `e2e` |
328
+ | `e2eTest` | a browser driver; with none registered it SKIPS, and a step that ran nothing is reported SKIPPED, never passed; with `e2e` in `x.verify.json` it is red — `X_VERIFY_E2E_BROWSER_MISSING`, whose fix installs a browser, when this machine has none. `hasE2eDriver()` says which state a harness is in. Every one audits the page's accessibility tree; the only exception is `{ a11y: { allow: [{ role, selector, because }] } }` ([Testing](https://github.com/developerz-ai/ultimate/wiki/Testing#the-accessibility-audit)) | `e2e` |
325
329
  | `evalTest` | LLM output scoring against a threshold | `eval` |
326
330
 
327
331
  Each takes an optional `{ timeoutMs }` after the body — `unitTest(name, body, { timeoutMs: 30_000 })`,
@@ -345,6 +349,13 @@ It registers `page` and nothing else. `budget`, `signIn` and `deploy` keep refus
345
349
  browser's own network state and a second build id are not things a page port can answer for, and a
346
350
  fixture that silently no-opped would make the assertion after it read as proof.
347
351
 
352
+ **Real input, `As of 2026-11`.** A raw-CDP tab (`cdpE2eTab`, the `E2eTab` the framework implements)
353
+ sends trusted input the page cannot forge: `tab.touchDrag(from, to, steps)` is a finger
354
+ (`Input.dispatchTouchEvent`, touch emulation on once per tab) and `tab.press(key)` a key
355
+ (`Input.dispatchKeyEvent`, so Tab really moves focus) — a key from `PRESS_KEYS`, a letter or a digit.
356
+ A touch `PointerEvent` dispatched from page script is refused by `setPointerCapture`, so a drag
357
+ proven that way proves nothing; `TouchPoint` is the `{ x, y }` both ends take.
358
+
348
359
  **A browser call that is never answered says why.** `X_CDP_TIMEOUT` from the connection carries
349
360
  `meta.reading` — `target-gone` (session detached, target destroyed or crashed), `lost-in-transport`
350
361
  (`meta.framesDropped` frames arrived unparseable after the call) or `no-answer` — beside
@@ -1390,3 +1401,39 @@ X_TEST_MODULE_MOCK_UNRESTORABLE: a mocked module could not be put back at the fi
1390
1401
  "/app/a.test.ts" mocked "/app/vendor.ts", whose real module failed to load (…)
1391
1402
  fix: x test unit --isolate # or hand the mocked dependency to the code under test as a parameter
1392
1403
  ```
1404
+
1405
+ ## A test that needs a real server
1406
+
1407
+ Declared, never hand-rolled: `{ needs: [...] }` on any typed registrar (`unitTest`, `contractTest`,
1408
+ `liveTest`, `jobTest`, `e2eTest`, `evalTest`) names the services the test talks to. Each is read
1409
+ from the variable `docker/test-services.env` publishes it under — set, the test runs; unset or
1410
+ blank, it is **skipped**, and its reported name carries the service, the variable and the command
1411
+ that starts them. An app needs no Postgres runner or `describe.skipIf` of its own.
1412
+
1413
+ | `needs` | Variable |
1414
+ |---|---|
1415
+ | `postgres` | `TEST_DATABASE_URL` |
1416
+ | `redis` | `TEST_REDIS_URL` |
1417
+ | `nats` | `TEST_NATS_URL` |
1418
+
1419
+ The map is `TEST_SERVICE_ENV` and the start command `TEST_SERVICES_START`, both exported with the
1420
+ `TestService` type — the same map `x drill` reads its services from.
1421
+
1422
+ ```ts
1423
+ import { expect, unitTest } from '@ultimat3/testing';
1424
+
1425
+ unitTest(
1426
+ 'a uuid[] column decodes from the real driver',
1427
+ async () => {
1428
+ const url = Bun.env['TEST_DATABASE_URL'];
1429
+ expect(url).toBeDefined();
1430
+ },
1431
+ { needs: ['postgres'] },
1432
+ );
1433
+ ```
1434
+
1435
+ Unset, the line reads `unit · a uuid[] column decodes from the real driver (needs postgres
1436
+ (TEST_DATABASE_URL) unset: docker compose -f docker/docker-compose.test.yml up -d --wait && set -a
1437
+ && . docker/test-services.env && set +a)`. A skip is never a pass: a step whose every test skipped
1438
+ is `X_VERIFY_SUITE_VANISHED` when `x.verify.json` requires it, and under `CI` the `skipCeiling`
1439
+ judges how many may skip.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.25.0",
3
+ "version": "31.27.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -47,26 +47,26 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@ultimat3/action": "31.25.0",
51
- "@ultimat3/ai": "31.25.0",
52
- "@ultimat3/auth": "31.25.0",
53
- "@ultimat3/cache": "31.25.0",
54
- "@ultimat3/core": "31.25.0",
55
- "@ultimat3/db": "31.25.0",
56
- "@ultimat3/entity": "31.25.0",
57
- "@ultimat3/http": "31.25.0",
58
- "@ultimat3/i18n": "31.25.0",
59
- "@ultimat3/jobs": "31.25.0",
60
- "@ultimat3/mail": "31.25.0",
61
- "@ultimat3/notify": "31.25.0",
62
- "@ultimat3/policy": "31.25.0",
63
- "@ultimat3/pwa": "31.25.0",
64
- "@ultimat3/query": "31.25.0",
65
- "@ultimat3/realtime": "31.25.0",
66
- "@ultimat3/render": "31.25.0",
67
- "@ultimat3/schema": "31.25.0",
68
- "@ultimat3/scraping": "31.25.0",
69
- "@ultimat3/seo": "31.25.0",
70
- "@ultimat3/time": "31.25.0"
50
+ "@ultimat3/action": "31.27.0",
51
+ "@ultimat3/ai": "31.27.0",
52
+ "@ultimat3/auth": "31.27.0",
53
+ "@ultimat3/cache": "31.27.0",
54
+ "@ultimat3/core": "31.27.0",
55
+ "@ultimat3/db": "31.27.0",
56
+ "@ultimat3/entity": "31.27.0",
57
+ "@ultimat3/http": "31.27.0",
58
+ "@ultimat3/i18n": "31.27.0",
59
+ "@ultimat3/jobs": "31.27.0",
60
+ "@ultimat3/mail": "31.27.0",
61
+ "@ultimat3/notify": "31.27.0",
62
+ "@ultimat3/policy": "31.27.0",
63
+ "@ultimat3/pwa": "31.27.0",
64
+ "@ultimat3/query": "31.27.0",
65
+ "@ultimat3/realtime": "31.27.0",
66
+ "@ultimat3/render": "31.27.0",
67
+ "@ultimat3/schema": "31.27.0",
68
+ "@ultimat3/scraping": "31.27.0",
69
+ "@ultimat3/seo": "31.27.0",
70
+ "@ultimat3/time": "31.27.0"
71
71
  }
72
72
  }
@@ -3,8 +3,8 @@
3
3
  // condition, the init scripts, the socket and request log. Launching is `cdp-launch.ts` and the
4
4
  // wire is `cdp-connection.ts`.
5
5
  //
6
- // FIVE methods, which is the whole reason this exists next to `@ultimat3/scraping` rather than
7
- // through it: `ScrapePage` is a full scraping surface whose intended implementation is
6
+ // A handful of methods — and a real finger (`touchDrag`) and key (`press`) — which is why this sits
7
+ // next to `@ultimat3/scraping` rather than going through it: `ScrapePage` is a full scraping surface whose intended implementation is
8
8
  // `puppeteer-core`, and an e2e driver needs none of it.
9
9
 
10
10
  import type { CdpConnection } from '@ultimat3/scraping/cdp';
@@ -70,6 +70,19 @@ export interface E2eTab extends E2eBrowserPage {
70
70
  * dispatches straight at the element and can never see that.
71
71
  */
72
72
  pointerClick(selector: string): Promise<void>;
73
+ /**
74
+ * A REAL finger (`Input.dispatchTouchEvent`, touch emulation on for the tab the first time): a
75
+ * start at `from`, `steps` moves to `to`, an end, in viewport CSS px. Trusted input, so the
76
+ * browser hit-tests it, honours `touch-action`, and may take it for a scroll and send
77
+ * `pointercancel` — what a page-dispatched touch PointerEvent can never show (no active pointer).
78
+ */
79
+ touchDrag(from: TouchPoint, to: TouchPoint, steps?: number): Promise<void>;
80
+ /**
81
+ * A REAL key press (`Input.dispatchKeyEvent`, down then up) at whatever has focus, so its default
82
+ * action runs: Tab moves focus, which a dispatched `KeyboardEvent` never does. A name in
83
+ * `PRESS_KEYS` or one printable character.
84
+ */
85
+ press(key: string): Promise<void>;
73
86
  /** Required on a tab: the audit of every `e2eTest` reads it (`e2e-a11y-run.ts`). */
74
87
  accessibilityTree(request: AxTreeRequest): Promise<readonly AxTreeNode[]>;
75
88
  /** Reload and wait for the load, at the url the tab already had. */
@@ -81,6 +94,52 @@ export interface E2eTab extends E2eBrowserPage {
81
94
  close(): Promise<void>;
82
95
  }
83
96
 
97
+ /** A viewport point in CSS px, as `getBoundingClientRect()` answers it. */
98
+ export interface TouchPoint {
99
+ readonly x: number;
100
+ readonly y: number;
101
+ }
102
+
103
+ /** Named keys `press()` knows, with the Windows virtual key code Chrome routes them by. */
104
+ export const PRESS_KEYS: Readonly<Record<string, number>> = {
105
+ Tab: 9,
106
+ Enter: 13,
107
+ Escape: 27,
108
+ ' ': 32,
109
+ PageUp: 33,
110
+ PageDown: 34,
111
+ End: 35,
112
+ Home: 36,
113
+ ArrowLeft: 37,
114
+ ArrowUp: 38,
115
+ ArrowRight: 39,
116
+ ArrowDown: 40,
117
+ Backspace: 8,
118
+ Delete: 46,
119
+ };
120
+
121
+ /** The key code of a printable character: its upper-case code point for a letter or digit. */
122
+ const charCode = (key: string): number | undefined =>
123
+ key.length === 1 && /[a-z0-9]/i.test(key) ? key.toUpperCase().charCodeAt(0) : undefined;
124
+
125
+ /**
126
+ * The text a key TYPES, as puppeteer's key table has it. A key with text goes down as `keyDown`
127
+ * carrying it, so Chrome raises the character event — what makes Enter submit a focused button's
128
+ * form. A key with none (Tab, the arrows) goes down as `rawKeyDown`.
129
+ */
130
+ const typedText = (key: string): string | undefined =>
131
+ key === 'Enter' ? '\r' : key.length === 1 ? key : undefined;
132
+
133
+ /** `KeyboardEvent.code`: `KeyA`, `Digit7`, `Space`; a named key is its own code. */
134
+ const keyCodeName = (key: string): string =>
135
+ key === ' '
136
+ ? 'Space'
137
+ : /^[a-z]$/i.test(key)
138
+ ? `Key${key.toUpperCase()}`
139
+ : /^[0-9]$/.test(key)
140
+ ? `Digit${key}`
141
+ : key;
142
+
84
143
  export interface CdpE2eTabOptions {
85
144
  readonly connection: CdpConnection;
86
145
  /** The attached tab's flattened session — every page call carries it. */
@@ -135,6 +194,8 @@ export function cdpE2eTab(options: CdpE2eTabOptions): E2eTab {
135
194
  // url is tracked here. Seeded with the tab's own starting url rather than '' so a `reload()`
136
195
  // before any `goto()` navigates somewhere real.
137
196
  let current = 'about:blank';
197
+ // Touch emulation is per tab and stays on: switched on by the first `touchDrag`, once.
198
+ let touchOn = false;
138
199
 
139
200
  const evaluateRaw = (expression: string) =>
140
201
  send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, sessionId);
@@ -304,6 +365,55 @@ export function cdpE2eTab(options: CdpE2eTabOptions): E2eTab {
304
365
  );
305
366
  }
306
367
  },
368
+ async touchDrag(from: TouchPoint, to: TouchPoint, steps = 5): Promise<void> {
369
+ if (!Number.isInteger(steps) || steps < 1) {
370
+ throw new CdpCallFailedError({
371
+ method: `touchDrag(steps: ${String(steps)})`,
372
+ detail: 'steps is the number of moves, a whole number of at least 1',
373
+ });
374
+ }
375
+ if (!touchOn) {
376
+ await send(
377
+ 'Emulation.setTouchEmulationEnabled',
378
+ { enabled: true, maxTouchPoints: 1 },
379
+ sessionId,
380
+ );
381
+ touchOn = true;
382
+ }
383
+ const touch = (type: string, points: readonly TouchPoint[]) =>
384
+ send(
385
+ 'Input.dispatchTouchEvent',
386
+ { type, touchPoints: points.map((p) => ({ x: p.x, y: p.y })) },
387
+ sessionId,
388
+ );
389
+ await touch('touchStart', [from]);
390
+ for (let step = 1; step <= steps; step += 1) {
391
+ const at = (a: number, b: number): number => a + ((b - a) * step) / steps;
392
+ await touch('touchMove', [{ x: at(from.x, to.x), y: at(from.y, to.y) }]);
393
+ }
394
+ await touch('touchEnd', []);
395
+ },
396
+ async press(key: string): Promise<void> {
397
+ const code = (Object.hasOwn(PRESS_KEYS, key) ? PRESS_KEYS[key] : undefined) ?? charCode(key);
398
+ if (code === undefined) {
399
+ throw new CdpCallFailedError({
400
+ method: `press(${key})`,
401
+ detail: `not a key press() knows: one of ${Object.keys(PRESS_KEYS).join(', ')}, or one letter or digit`,
402
+ });
403
+ }
404
+ const text = typedText(key);
405
+ const common = { key, code: keyCodeName(key), windowsVirtualKeyCode: code };
406
+ await send(
407
+ 'Input.dispatchKeyEvent',
408
+ {
409
+ type: text === undefined ? 'rawKeyDown' : 'keyDown',
410
+ ...common,
411
+ ...(text === undefined ? {} : { text }),
412
+ },
413
+ sessionId,
414
+ );
415
+ await send('Input.dispatchKeyEvent', { type: 'keyUp', ...common }, sessionId);
416
+ },
307
417
  offline: (enabled: boolean) => options.offline(enabled),
308
418
  async accessibilityTree(request: AxTreeRequest): Promise<readonly AxTreeNode[]> {
309
419
  const nodes = toAxTreeNodes((await send(FULL_AX_TREE, {}, sessionId)).result);
@@ -0,0 +1,226 @@
1
+ // The module-scope declaration tables `registry-snapshot.ts` does not hold, put back at the file
2
+ // boundary to what the file's body inherited: realtime's channels and `@ultimat3/mcp`'s declared
3
+ // remote servers and served recipes. Each is read through the module cache, never imported — an
4
+ // unloaded package has nothing to restore, and `testing` does not depend on `@ultimat3/mcp`.
5
+
6
+ import type {
7
+ AuthenticatorOptions,
8
+ configureAuthenticator,
9
+ configuredAuthenticator,
10
+ configuredCredentialTtlMs,
11
+ resetAuthenticator,
12
+ } from '@ultimat3/http';
13
+ import type { Channel } from '@ultimat3/realtime';
14
+ import type { RouteSnapshot, restoreRoutes, routeSnapshot } from '@ultimat3/render';
15
+ import { loaded } from './per-test-reset';
16
+
17
+ /** One table: where it lives, how to read it, and the exact restore its owner publishes. */
18
+ export interface DeclarationTable {
19
+ /** `<package>/<file under src>` — the row `process-registries.test.ts` holds to the source. */
20
+ readonly owner: string;
21
+ /** `undefined` while the owner is unloaded. */
22
+ capture(): unknown;
23
+ /** Called with a defined snapshot only. */
24
+ restore(snapshot: unknown): void;
25
+ }
26
+
27
+ interface ChannelModule {
28
+ readonly registeredChannels: () => readonly Channel[];
29
+ readonly restoreChannels: (declared: readonly Channel[]) => void;
30
+ }
31
+
32
+ interface RouteModule {
33
+ readonly routeSnapshot: typeof routeSnapshot;
34
+ readonly restoreRoutes: typeof restoreRoutes;
35
+ }
36
+
37
+ /** `@ultimat3/ai`'s catalogue, restated: `ai` is reached dynamically only, never type-imported. */
38
+ interface ModelModule {
39
+ readonly registeredModels: () => readonly unknown[];
40
+ readonly restoreModels: (specs: readonly unknown[]) => void;
41
+ }
42
+
43
+ interface HooksModule {
44
+ readonly configureAuthenticator: typeof configureAuthenticator;
45
+ readonly configuredAuthenticator: typeof configuredAuthenticator;
46
+ readonly configuredCredentialTtlMs: typeof configuredCredentialTtlMs;
47
+ readonly resetAuthenticator: typeof resetAuthenticator;
48
+ }
49
+
50
+ interface AuthenticatorSlot {
51
+ readonly authenticate: ReturnType<typeof configuredAuthenticator>;
52
+ readonly ttl: number | undefined;
53
+ }
54
+
55
+ /** `@ultimat3/mcp`'s shapes, restated: `testing` neither depends on nor type-imports the package. */
56
+ interface RecipeModule {
57
+ readonly servedRecipes: () => ReadonlySet<string>;
58
+ readonly resetServedRecipes: () => void;
59
+ readonly noteServedRecipes: (names: readonly string[]) => void;
60
+ }
61
+ /** `@ultimat3/storage`'s registry, restated: `testing` does not depend on the package. */
62
+ interface StorageModule {
63
+ readonly definedStorage: () => unknown;
64
+ readonly resetStorage: () => void;
65
+ }
66
+
67
+ interface RemoteModule {
68
+ readonly declaredMcpServers: () => ReadonlyMap<string, unknown>;
69
+ readonly restoreDeclaredMcpServers: (servers: ReadonlyMap<string, unknown>) => void;
70
+ }
71
+
72
+ const found = new Map<string, string>();
73
+
74
+ /**
75
+ * A loaded module whose path ends in `suffix` and that exports every name in `shape`. For a
76
+ * package `testing` cannot resolve (not a dependency): the cache is scanned until it is seen,
77
+ * then the path is kept. The shape check is what keeps an app's own `packages/mcp/src/` out.
78
+ */
79
+ function cachedModule<M>(suffix: string, shape: readonly string[]): M | undefined {
80
+ const known = found.get(suffix);
81
+ if (known !== undefined) return require.cache[known]?.exports as M | undefined;
82
+ for (const [path, entry] of Object.entries(require.cache)) {
83
+ if (!path.replaceAll('\\', '/').endsWith(suffix)) continue;
84
+ const exports = entry?.exports as Record<string, unknown> | undefined;
85
+ if (exports === undefined || !shape.every((name) => typeof exports[name] === 'function')) {
86
+ continue;
87
+ }
88
+ found.set(suffix, path);
89
+ return exports as M;
90
+ }
91
+ return undefined;
92
+ }
93
+
94
+ const channelModule = (): ChannelModule | undefined => {
95
+ const path = loaded('@ultimat3/realtime', 'channel-registry.ts');
96
+ return path === undefined ? undefined : (require(path) as ChannelModule);
97
+ };
98
+
99
+ const routeModule = (): RouteModule | undefined => {
100
+ const path = loaded('@ultimat3/render', 'registry.ts');
101
+ return path === undefined ? undefined : (require(path) as RouteModule);
102
+ };
103
+
104
+ const modelModule = (): ModelModule | undefined => {
105
+ const path = loaded('@ultimat3/ai', 'models.ts');
106
+ return path === undefined ? undefined : (require(path) as ModelModule);
107
+ };
108
+
109
+ const hooksModule = (): HooksModule | undefined => {
110
+ const path = loaded('@ultimat3/http', 'hooks.ts');
111
+ return path === undefined ? undefined : (require(path) as HooksModule);
112
+ };
113
+
114
+ const STORAGE_SHAPE = ['definedStorage', 'defineStorage', 'resetStorage'] as const;
115
+ const storageModule = (): StorageModule | undefined =>
116
+ cachedModule<StorageModule>('/storage/src/storage.ts', STORAGE_SHAPE);
117
+
118
+ const RECIPE_SHAPE = ['servedRecipes', 'resetServedRecipes', 'noteServedRecipes'] as const;
119
+ const REMOTE_SHAPE = ['declaredMcpServers', 'restoreDeclaredMcpServers'] as const;
120
+ const recipeModule = (): RecipeModule | undefined =>
121
+ cachedModule<RecipeModule>('/mcp/src/recipe-links.ts', RECIPE_SHAPE);
122
+ const remoteModule = (): RemoteModule | undefined =>
123
+ cachedModule<RemoteModule>('/mcp/src/remote-tools.ts', REMOTE_SHAPE);
124
+
125
+ /** Every table the boundary restores. A new module-scope registry joins here, with its restore. */
126
+ export const DECLARATION_TABLES: readonly DeclarationTable[] = [
127
+ {
128
+ // One file's `site/` route was a later fixture app's `budgets` red (`X_STYLES_GLOBAL_MISSING`
129
+ // in `mcp-host-tools.test.ts`): `documentSurfaces()` reads the whole route table.
130
+ owner: '@ultimat3/render/registry.ts',
131
+ capture: () => routeModule()?.routeSnapshot(),
132
+ restore: (snapshot) => routeModule()?.restoreRoutes(snapshot as RouteSnapshot),
133
+ },
134
+ {
135
+ owner: '@ultimat3/ai/models.ts',
136
+ capture: () => modelModule()?.registeredModels(),
137
+ restore: (snapshot) => modelModule()?.restoreModels(snapshot as readonly unknown[]),
138
+ },
139
+ {
140
+ // A slot, not a table: one file's `configureAuthenticator` answered every later file's socket
141
+ // upgrade with its resolver — `role-sync-dev-origin.test.ts` read 401 where it wanted 101.
142
+ owner: '@ultimat3/http/hooks.ts',
143
+ capture: (): AuthenticatorSlot | undefined => {
144
+ const module = hooksModule();
145
+ return module === undefined
146
+ ? undefined
147
+ : {
148
+ authenticate: module.configuredAuthenticator(),
149
+ ttl: module.configuredCredentialTtlMs(),
150
+ };
151
+ },
152
+ restore: (snapshot) => {
153
+ const module = hooksModule();
154
+ if (module === undefined) return;
155
+ const { authenticate, ttl } = snapshot as AuthenticatorSlot;
156
+ if (authenticate === undefined) return module.resetAuthenticator();
157
+ const options: AuthenticatorOptions = ttl === undefined ? {} : { credentialTtlMs: ttl };
158
+ module.configureAuthenticator(authenticate, options);
159
+ },
160
+ },
161
+ {
162
+ // A slot with a reset and no setter: a body that installed storage over NONE is undone; one
163
+ // that replaced an inherited registry cannot be put back and is left (no exact writer exists).
164
+ // One file's `defineStorage({ disks: { assets } })` was every later boot's `appDeclared()`.
165
+ owner: '@ultimat3/storage/storage.ts',
166
+ capture: () => {
167
+ const module = storageModule();
168
+ return module === undefined ? undefined : { storage: module.definedStorage() };
169
+ },
170
+ restore: (snapshot) => {
171
+ const module = storageModule();
172
+ if (module === undefined) return;
173
+ if ((snapshot as { readonly storage: unknown }).storage === undefined) module.resetStorage();
174
+ },
175
+ },
176
+ {
177
+ owner: '@ultimat3/realtime/channel-registry.ts',
178
+ capture: () => channelModule()?.registeredChannels(),
179
+ restore: (snapshot) => {
180
+ const module = channelModule();
181
+ if (module !== undefined) module.restoreChannels(snapshot as readonly Channel[]);
182
+ },
183
+ },
184
+ {
185
+ owner: '@ultimat3/mcp/recipe-links.ts',
186
+ capture: () => {
187
+ const served = recipeModule()?.servedRecipes();
188
+ return served === undefined ? undefined : [...served];
189
+ },
190
+ restore: (snapshot) => {
191
+ const module = recipeModule();
192
+ if (module === undefined) return;
193
+ module.resetServedRecipes();
194
+ module.noteServedRecipes(snapshot as readonly string[]);
195
+ },
196
+ },
197
+ {
198
+ owner: '@ultimat3/mcp/remote-tools.ts',
199
+ capture: () => {
200
+ const declared = remoteModule()?.declaredMcpServers();
201
+ return declared === undefined ? undefined : new Map(declared);
202
+ },
203
+ restore: (snapshot) => {
204
+ const module = remoteModule();
205
+ if (module === undefined) return;
206
+ module.restoreDeclaredMcpServers(snapshot as ReadonlyMap<string, unknown>);
207
+ },
208
+ },
209
+ ];
210
+
211
+ /** Each table's contents now, in `DECLARATION_TABLES` order; `undefined` for an unloaded owner. */
212
+ export function captureDeclarationTables(): readonly unknown[] {
213
+ return DECLARATION_TABLES.map((table) => table.capture());
214
+ }
215
+
216
+ /**
217
+ * Exactly `snapshots` again. A table whose owner was not loaded at the capture is left alone: what
218
+ * it holds was declared by a module this file loaded lazily, at module scope — a cached module
219
+ * never declares again, so taking it away would cost every later file that imports it.
220
+ */
221
+ export function restoreDeclarationTables(snapshots: readonly unknown[]): void {
222
+ DECLARATION_TABLES.forEach((table, index) => {
223
+ const snapshot = snapshots[index];
224
+ if (snapshot !== undefined) table.restore(snapshot);
225
+ });
226
+ }
@@ -0,0 +1,97 @@
1
+ // A route `load`'s entry in `defineExercise(…, { routes: { '/posts/:id': { … } } })`: the params
2
+ // and the actor a page needs that a seeded id and a role cannot give it, its statement ceiling, why
3
+ // a load that reads nothing is right (`empty`), or why it cannot run (`off`). Keyed by the URL
4
+ // pattern `x routes` prints; an unknown one is refused when the pass runs.
5
+
6
+ import type { Actor } from '@ultimat3/core';
7
+ import { finiteCount, renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
8
+ import type { ExerciseStatementCeiling } from './exercise-statement-ceiling';
9
+
10
+ export type RouteParamsRecord = Readonly<Record<string, string>>;
11
+
12
+ /** What a route's load runs with — each field optional, the pass's own pick where omitted. */
13
+ export interface RouteExerciseEntry {
14
+ /**
15
+ * The params, or a function computing them — awaited inside the load's own request as its
16
+ * actor, so `useContext().actor.orgId` names the seeded tenant and `db()` reads its rows.
17
+ */
18
+ readonly params?: RouteParamsRecord | (() => Promise<RouteParamsRecord> | RouteParamsRecord);
19
+ /**
20
+ * The query string the load's URL carries (`response_type=code&…`, a leading `?` optional), or a
21
+ * function computing it in the load's request — a page that reads `url`, not params.
22
+ */
23
+ readonly search?: string | (() => Promise<string> | string);
24
+ /**
25
+ * Who loads it: an actor (moved into the route's tenant), or a function of the actor the pass
26
+ * seated — awaited in its request — answering the actor as the app's request boundary would
27
+ * resolve it (its facts: the member row, the org).
28
+ */
29
+ readonly actor?: Actor | null | ((seated: Actor | null) => Promise<Actor | null> | Actor | null);
30
+ /** The ceiling one load is held to, `STATEMENTS_MAX` when omitted. */
31
+ readonly statements?: ExerciseStatementCeiling;
32
+ /** Why a load that sends no statement and has no effect is right: its proofs are vacuous. */
33
+ readonly empty?: string;
34
+ }
35
+
36
+ export type RouteExerciseOverride = RouteExerciseEntry | { readonly off: string };
37
+
38
+ /** The one refusal for a stated reason left blank: the skip, or the exception, is silent. */
39
+ export const blankWhy = (where: string, field: string, paste: string): UltimateError =>
40
+ new UltimateError({
41
+ code: 'X_CONTRACT_EXERCISE_UNDECLARED',
42
+ cause: `defineExercise() gives ${renderCauseValue(where)} a blank ${field}, so the exception is silent`,
43
+ fix: `${paste} # in apps/web/exercise.ts`,
44
+ });
45
+
46
+ const blankText = (value: unknown): boolean =>
47
+ typeof value !== 'string' || value.trim().length === 0;
48
+
49
+ /** `empty: '<why>'` on any entry, primitive or route: present means stated. */
50
+ export function checkEmptyWhy(where: string, empty: unknown, paste: string): void {
51
+ if (empty !== undefined && blankText(empty)) throw blankWhy(where, 'empty why', paste);
52
+ }
53
+
54
+ /** Each route entry, its reasons stated and its ceiling a whole count ≥ 1. */
55
+ export function routeEntries(
56
+ routes: Readonly<Record<string, RouteExerciseOverride>>,
57
+ ): ReadonlyMap<string, RouteExerciseOverride> {
58
+ const entries = new Map<string, RouteExerciseOverride>();
59
+ for (const [path, entry] of Object.entries(routes)) {
60
+ const at = renderFixLiteral(path, '<pattern>');
61
+ const paste = (field: string): string =>
62
+ `defineExercise({}, { routes: { ${at}: { ${field} } } })`;
63
+ if ('off' in entry) {
64
+ if (blankText(entry.off)) throw blankWhy(path, 'off reason', paste("off: '<why>'"));
65
+ } else {
66
+ checkEmptyWhy(path, entry.empty, paste("empty: '<why it reads nothing>'"));
67
+ if (entry.statements !== undefined) {
68
+ finiteCount('defineExercise()', `${path}.statements.max`, entry.statements.max, 1);
69
+ if (blankText(entry.statements.why)) {
70
+ throw blankWhy(path, 'statements why', paste("statements: { max: <n>, why: '<why>' }"));
71
+ }
72
+ }
73
+ }
74
+ entries.set(path, entry);
75
+ }
76
+ return entries;
77
+ }
78
+
79
+ /**
80
+ * Every route entry names a registered route's pattern — checked when the pass runs, the route
81
+ * table full. `X_DECLARATION_UNKNOWN`, the code every unknown name answers; the cause lists them.
82
+ */
83
+ export function assertRoutesKnown(
84
+ overrides: { readonly routes?: ReadonlyMap<string, RouteExerciseOverride> } | undefined,
85
+ registered: readonly string[],
86
+ ): void {
87
+ const known = new Set(registered);
88
+ const unknown = [...(overrides?.routes?.keys() ?? [])].filter((path) => !known.has(path)).sort();
89
+ if (unknown.length === 0) return;
90
+ const listed = [...known].sort();
91
+ throw new UltimateError({
92
+ code: 'X_DECLARATION_UNKNOWN',
93
+ cause: `defineExercise() routes name ${unknown.map((path) => renderCauseValue(path)).join(', ')}, which no app/ or site/ route with a load is (registered: ${listed.length === 0 ? 'none' : renderCauseValue(listed.join(', '))})`,
94
+ fix: 'x routes --json # then rename or remove the entry under routes in apps/web/exercise.ts',
95
+ meta: { unknown, registered: listed },
96
+ });
97
+ }