@ait-co/devtools 0.1.137 → 0.1.139

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.
Files changed (119) hide show
  1. package/dist/{attach-orchestrator-Cjdhir2U.js → attach-orchestrator-6kz_ZdWL.js} +5 -3
  2. package/dist/{attach-orchestrator-Cjdhir2U.js.map → attach-orchestrator-6kz_ZdWL.js.map} +1 -1
  3. package/dist/{attach-orchestrator-CE0S09YU.js → attach-orchestrator-BEiz3wAx.js} +5 -3
  4. package/dist/{attach-orchestrator-CMoDuG2A.js.map → attach-orchestrator-BEiz3wAx.js.map} +1 -1
  5. package/dist/{attach-orchestrator-CMoDuG2A.js → attach-orchestrator-BG8TGJOZ.js} +5 -3
  6. package/dist/{attach-orchestrator-CE0S09YU.js.map → attach-orchestrator-BG8TGJOZ.js.map} +1 -1
  7. package/dist/{bundle-BKqyhEK9.d.ts → bundle-C796JIwG.d.ts} +65 -2
  8. package/dist/bundle-C796JIwG.d.ts.map +1 -0
  9. package/dist/{capture-ltuV0gZa.d.ts → capture-DsP525OZ.d.ts} +1 -1
  10. package/dist/{capture-ltuV0gZa.d.ts.map → capture-DsP525OZ.d.ts.map} +1 -1
  11. package/dist/{cdp-connection-BYE9meXe.d.ts → cdp-connection-rP1WdnH5.d.ts} +1 -1
  12. package/dist/{cdp-connection-BYE9meXe.d.ts.map → cdp-connection-rP1WdnH5.d.ts.map} +1 -1
  13. package/dist/{cell-D1y4shoV.js → cell-BMlFh08P.js} +2 -2
  14. package/dist/cell-BMlFh08P.js.map +1 -0
  15. package/dist/{cell-DHA578lX.js → cell-Dtgtusog.js} +90 -16
  16. package/dist/cell-Dtgtusog.js.map +1 -0
  17. package/dist/{cell-BIdSQb9T.js → cell-KsRXFdDs.js} +122 -16
  18. package/dist/cell-KsRXFdDs.js.map +1 -0
  19. package/dist/{debug-server-CBK7dn8O.js → debug-server-6c22qSWa.js} +132 -9
  20. package/dist/debug-server-6c22qSWa.js.map +1 -0
  21. package/dist/{debug-server-BQplCzf8.js → debug-server-BQHbaKPT.js} +134 -11
  22. package/dist/debug-server-BQHbaKPT.js.map +1 -0
  23. package/dist/{debug-server-D2wpPK3_.js → debug-server-DWat7d-9.js} +82 -6
  24. package/dist/debug-server-DWat7d-9.js.map +1 -0
  25. package/dist/devtools-opener-3Drge_RJ.js +75 -0
  26. package/dist/devtools-opener-3Drge_RJ.js.map +1 -0
  27. package/dist/devtools-opener-CJpEsXXQ.js +76 -0
  28. package/dist/devtools-opener-CJpEsXXQ.js.map +1 -0
  29. package/dist/devtools-opener-CxtryS8c.js +75 -0
  30. package/dist/devtools-opener-CxtryS8c.js.map +1 -0
  31. package/dist/in-app/auto.js +59 -12
  32. package/dist/in-app/auto.js.map +1 -1
  33. package/dist/in-app/index.d.ts +21 -2
  34. package/dist/in-app/index.d.ts.map +1 -1
  35. package/dist/in-app/index.js +60 -13
  36. package/dist/in-app/index.js.map +1 -1
  37. package/dist/mcp/cli.js +299 -60
  38. package/dist/mcp/cli.js.map +1 -1
  39. package/dist/mcp/server.js +1 -1
  40. package/dist/mock/index.d.ts +79 -1
  41. package/dist/mock/index.d.ts.map +1 -1
  42. package/dist/mock/index.js +218 -14
  43. package/dist/mock/index.js.map +1 -1
  44. package/dist/panel/index.js +171 -10
  45. package/dist/panel/index.js.map +1 -1
  46. package/dist/{pool-CmfvXnwh.d.ts → pool-CrP5CPvU.d.ts} +3 -3
  47. package/dist/{pool-CmfvXnwh.d.ts.map → pool-CrP5CPvU.d.ts.map} +1 -1
  48. package/dist/{qr-http-server-ZkT6F7is.js → qr-http-server-D1hpoyBF.js} +1 -1
  49. package/dist/{qr-http-server-ZkT6F7is.js.map → qr-http-server-D1hpoyBF.js.map} +1 -1
  50. package/dist/qr-http-server-D4rGz8M7.js +1640 -0
  51. package/dist/qr-http-server-D4rGz8M7.js.map +1 -0
  52. package/dist/{qr-http-server-C7q8Gn04.js → qr-http-server-DIjCV7h_.js} +1 -1
  53. package/dist/{qr-http-server-C7q8Gn04.js.map → qr-http-server-DIjCV7h_.js.map} +1 -1
  54. package/dist/{relay-factory-DVzpBRxz.js → relay-factory-C1X3G3WY.js} +71 -15
  55. package/dist/relay-factory-C1X3G3WY.js.map +1 -0
  56. package/dist/{relay-secret-store-CLEGyHou.js → relay-secret-store-Bmyleu0A.js} +1 -1
  57. package/dist/{relay-secret-store-CLEGyHou.js.map → relay-secret-store-Bmyleu0A.js.map} +1 -1
  58. package/dist/{relay-secret-store-DhzAnnj-.js → relay-secret-store-CQenfcSL.js} +2 -2
  59. package/dist/{relay-secret-store-DhzAnnj-.js.map → relay-secret-store-CQenfcSL.js.map} +1 -1
  60. package/dist/{relay-secret-store-BcVrWwTq.js → relay-secret-store-DKxs7zwq.js} +1 -1
  61. package/dist/{relay-secret-store-BcVrWwTq.js.map → relay-secret-store-DKxs7zwq.js.map} +1 -1
  62. package/dist/{relay-secret-store-DGduVJhs.js → relay-secret-store-WJ8EGkIl.js} +1 -1
  63. package/dist/{relay-secret-store-DGduVJhs.js.map → relay-secret-store-WJ8EGkIl.js.map} +1 -1
  64. package/dist/{relay-url-store-CKW8RQzf.js → relay-url-store-BR2XodiO.js} +2 -2
  65. package/dist/{relay-url-store-CKW8RQzf.js.map → relay-url-store-BR2XodiO.js.map} +1 -1
  66. package/dist/{relay-url-store-CdA58fgw.js → relay-url-store-CH63fVCm.js} +2 -2
  67. package/dist/{relay-url-store-B0X8TsGr.js.map → relay-url-store-CH63fVCm.js.map} +1 -1
  68. package/dist/{relay-url-store-CwKT7i04.js → relay-url-store-DaY1QPes.js} +2 -2
  69. package/dist/{relay-url-store-CwKT7i04.js.map → relay-url-store-DaY1QPes.js.map} +1 -1
  70. package/dist/{relay-url-store-B0X8TsGr.js → relay-url-store-xmUuTjXA.js} +2 -2
  71. package/dist/{relay-url-store-CdA58fgw.js.map → relay-url-store-xmUuTjXA.js.map} +1 -1
  72. package/dist/{relay-worker-6fy1eaIo.js → relay-worker-BUXI0K0b.js} +8 -4
  73. package/dist/{relay-worker-6fy1eaIo.js.map → relay-worker-BUXI0K0b.js.map} +1 -1
  74. package/dist/{relay-worker-DJnZkXza.d.ts → relay-worker-DcyboK43.d.ts} +30 -5
  75. package/dist/relay-worker-DcyboK43.d.ts.map +1 -0
  76. package/dist/{runtime-DfHHZms2.d.ts → runtime-BiigOuvb.d.ts} +30 -3
  77. package/dist/runtime-BiigOuvb.d.ts.map +1 -0
  78. package/dist/test-runner/bin.js +376 -38
  79. package/dist/test-runner/bin.js.map +1 -1
  80. package/dist/test-runner/bundle.d.ts +2 -2
  81. package/dist/test-runner/bundle.js +66 -13
  82. package/dist/test-runner/bundle.js.map +1 -1
  83. package/dist/test-runner/capture.d.ts +1 -1
  84. package/dist/test-runner/config.d.ts +58 -5
  85. package/dist/test-runner/config.d.ts.map +1 -1
  86. package/dist/test-runner/config.js +1 -1
  87. package/dist/test-runner/method-pace.d.ts +82 -0
  88. package/dist/test-runner/method-pace.d.ts.map +1 -0
  89. package/dist/test-runner/method-pace.js +120 -0
  90. package/dist/test-runner/method-pace.js.map +1 -0
  91. package/dist/test-runner/pool.d.ts +1 -1
  92. package/dist/test-runner/pool.js +1 -1
  93. package/dist/test-runner/relay-factory.d.ts +57 -4
  94. package/dist/test-runner/relay-factory.d.ts.map +1 -1
  95. package/dist/test-runner/relay-factory.js +70 -14
  96. package/dist/test-runner/relay-factory.js.map +1 -1
  97. package/dist/test-runner/relay-worker.d.ts +1 -1
  98. package/dist/test-runner/relay-worker.js +1 -1
  99. package/dist/test-runner/report.d.ts +3 -3
  100. package/dist/test-runner/rpc.d.ts +2 -2
  101. package/dist/test-runner/runtime.d.ts +2 -2
  102. package/dist/test-runner/runtime.js +83 -6
  103. package/dist/test-runner/runtime.js.map +1 -1
  104. package/dist/test-runner/task-graph.d.ts +1 -1
  105. package/dist/throttle-DKKzX1qC.js +59 -0
  106. package/dist/throttle-DKKzX1qC.js.map +1 -0
  107. package/dist/totp-Dwft0Kz7.js +3 -0
  108. package/package.json +1 -1
  109. package/dist/bundle-BKqyhEK9.d.ts.map +0 -1
  110. package/dist/cell-BIdSQb9T.js.map +0 -1
  111. package/dist/cell-D1y4shoV.js.map +0 -1
  112. package/dist/cell-DHA578lX.js.map +0 -1
  113. package/dist/debug-server-BQplCzf8.js.map +0 -1
  114. package/dist/debug-server-CBK7dn8O.js.map +0 -1
  115. package/dist/debug-server-D2wpPK3_.js.map +0 -1
  116. package/dist/relay-factory-DVzpBRxz.js.map +0 -1
  117. package/dist/relay-worker-DJnZkXza.d.ts.map +0 -1
  118. package/dist/runtime-DfHHZms2.d.ts.map +0 -1
  119. package/dist/totp-D1pulXLa.js +0 -3
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","names":["#received","#negated","#assert"],"sources":["../../src/test-runner/runtime.ts"],"sourcesContent":["/**\n * Thin test runtime for WebView execution.\n *\n * This file is bundled by `bundle.ts` together with the user's test file\n * into a single IIFE injected into the WebView via `Runtime.evaluate`.\n * It MUST stay browser-compatible — no Node.js APIs allowed.\n *\n * Design: rather than shipping @vitest/runner verbatim into a WebView (where\n * its Node-side internals cause issues), this runtime provides a minimal\n * compatible API surface — describe/it/test/expect globals — collects results\n * into a plain JSON-safe object, and exports `runTestModule` as the entry point.\n *\n * @vitest/runner and @vitest/expect are listed as dependencies so that the\n * package's type contracts are available and so the browser-compatible subsets\n * can be referenced. The Vitest custom pool that drives this runtime through\n * Vitest's `PoolRunnerInitializer` lives in `pool.ts`.\n *\n * NOTE: this file is imported by type from Node-side code (rpc.ts / relay-worker.ts)\n * for the RunReport / TestResult type shapes. The runtime ITSELF is not imported\n * at runtime on the Node side — only the types are used.\n */\n\n/* -------------------------------------------------------------------------- */\n/* Public result types (used by rpc.ts and relay-worker.ts) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Result of a single test case.\n * All fields are JSON-serialisable.\n */\nexport interface TestResult {\n /** Full dot-joined test name including nested suite names. */\n name: string;\n /** `'pass'` or `'fail'`. `'skip'` for skipped tests. */\n status: 'pass' | 'fail' | 'skip';\n /** Duration in milliseconds. */\n duration: number;\n /** Error message (fail only). Does NOT include the expression/secret. */\n error?: string;\n /**\n * Optional note attached to a skip — populated when the test body itself\n * calls `ctx.skip(cond, note)` (devtools#746), mirroring the static\n * `it.skip`/`it.skipIf` path which has no note today. `'skip'` status only.\n */\n note?: string;\n}\n\n/** Aggregate report returned by `runTestModule`. */\nexport interface RunReport {\n /** ISO timestamp of when `runTestModule` was called. */\n startedAt: string;\n /** Total elapsed milliseconds (wall-clock). */\n duration: number;\n passed: number;\n failed: number;\n skipped: number;\n tests: TestResult[];\n}\n\n/* -------------------------------------------------------------------------- */\n/* Asymmetric matchers (devtools#692) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Brand property that tags asymmetric matcher markers (`expect.any(String)`,\n * `expect.objectContaining(...)`, etc). A reserved string key is used as the\n * brand so the guard stays a plain own-property check — markers are only ever\n * compared in-process by reference, so no cross-realm Symbol coordination is\n * needed.\n */\nconst ASYMMETRIC_BRAND = '$$asymmetricMatch' as const;\n\n/**\n * An asymmetric matcher: a placeholder that, when found on the `expected` side\n * of a deep comparison, runs its own `asymmetricMatch(actual)` predicate\n * instead of being structurally compared as a plain object. This is what makes\n * `toMatchObject({ hash: expect.any(String) })` match any string `hash`.\n */\ninterface AsymmetricMatcher {\n /** Brand discriminator — present only on asymmetric markers. */\n [ASYMMETRIC_BRAND]: true;\n /** Human-readable label used in failure messages. */\n toString(): string;\n /** Returns true when `actual` satisfies this matcher. */\n asymmetricMatch(actual: unknown): boolean;\n}\n\n/** Narrowing guard: is `v` an asymmetric matcher marker? */\nfunction isAsymmetric(v: unknown): v is AsymmetricMatcher {\n return (\n typeof v === 'object' &&\n v !== null &&\n (v as Record<string, unknown>)[ASYMMETRIC_BRAND] === true &&\n typeof (v as { asymmetricMatch?: unknown }).asymmetricMatch === 'function'\n );\n}\n\n/** The widest constructor type TypeScript allows without `any` (see toBeInstanceOf). */\ntype AnyCtor = abstract new (...args: never) => unknown;\n\n/**\n * `expect.any(Ctor)` — matches a value by its constructor. Primitive wrappers\n * (`String`/`Number`/`Boolean`) are matched by `typeof` (so the unboxed\n * primitive matches) AND by `instanceof` (so a boxed wrapper instance also\n * matches). `BigInt`/`Symbol` match by `typeof`. `Object` matches any non-null\n * object (NOT functions, matching vitest), `Array` uses `Array.isArray`,\n * `Function` uses `typeof === 'function'`, and any other constructor (user\n * classes) falls back to `instanceof`.\n */\nfunction makeAny(ctor: AnyCtor): AsymmetricMatcher {\n const name = (ctor as { name?: string }).name ?? String(ctor);\n const ctorAsFn = ctor as unknown as (new (...args: unknown[]) => unknown) | undefined;\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `Any<${name}>`,\n asymmetricMatch(actual: unknown): boolean {\n if (actual === null || actual === undefined) return false;\n switch (ctor as unknown) {\n case String:\n return typeof actual === 'string' || actual instanceof String;\n case Number:\n return typeof actual === 'number' || actual instanceof Number;\n case Boolean:\n return typeof actual === 'boolean' || actual instanceof Boolean;\n case BigInt:\n return typeof actual === 'bigint';\n case Symbol:\n return typeof actual === 'symbol';\n case Function:\n return typeof actual === 'function';\n case Object:\n // Match vitest: `expect.any(Object)` accepts objects only, NOT\n // functions (vitest checks `typeof other === 'object'`). `null` is\n // already excluded by the guard above.\n return typeof actual === 'object';\n case Array:\n return Array.isArray(actual);\n default:\n return ctorAsFn ? actual instanceof ctorAsFn : false;\n }\n },\n };\n}\n\n/** `expect.anything()` — matches any value except `null`/`undefined`. */\nfunction makeAnything(): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => 'Anything',\n asymmetricMatch: (actual: unknown): boolean => actual !== null && actual !== undefined,\n };\n}\n\n/** `expect.objectContaining(obj)` — partial-match every key of `obj` on `actual`. */\nfunction makeObjectContaining(expected: Record<string, unknown>): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `ObjectContaining<${safeStringify(expected)}>`,\n asymmetricMatch: (actual: unknown): boolean => deepMatchObject(actual, expected),\n };\n}\n\n/** `expect.arrayContaining(arr)` — `actual` is an array containing each element of `arr`. */\nfunction makeArrayContaining(expected: unknown[]): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `ArrayContaining<${safeStringify(expected)}>`,\n asymmetricMatch(actual: unknown): boolean {\n if (!Array.isArray(actual)) return false;\n return expected.every((exp) =>\n actual.some((act) => (isAsymmetric(exp) ? exp.asymmetricMatch(act) : deepEqual(act, exp))),\n );\n },\n };\n}\n\n/** `expect.stringContaining(sub)` — `actual` is a string containing `sub`. */\nfunction makeStringContaining(sub: string): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `StringContaining<${sub}>`,\n asymmetricMatch: (actual: unknown): boolean =>\n typeof actual === 'string' && actual.includes(sub),\n };\n}\n\n/** `expect.stringMatching(re)` — `actual` is a string matching `re` (string or RegExp). */\nfunction makeStringMatching(re: string | RegExp): AsymmetricMatcher {\n const pattern = typeof re === 'string' ? new RegExp(re) : re;\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `StringMatching<${String(pattern)}>`,\n asymmetricMatch: (actual: unknown): boolean =>\n typeof actual === 'string' && pattern.test(actual),\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Deep equality helpers */\n/* -------------------------------------------------------------------------- */\n\n/** JSON.stringify that never throws (cycles/BigInt) — for failure messages. */\nfunction safeStringify(v: unknown): string {\n try {\n return (\n JSON.stringify(v, (_k, val) =>\n isAsymmetric(val) ? val.toString() : typeof val === 'bigint' ? `${val}n` : val,\n ) ?? String(v)\n );\n } catch {\n return String(v);\n }\n}\n\n/**\n * Recursive structural equality — replaces JSON.stringify comparison to\n * handle key-order differences and undefined values correctly.\n *\n * When the `b` (expected) side is an asymmetric marker, its `asymmetricMatch`\n * predicate decides the result instead of structural comparison — markers are\n * placeholders, not plain objects, so deep-comparing them never matches.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (isAsymmetric(b)) return b.asymmetricMatch(a);\n if (Object.is(a, b)) return true;\n if (a === null || b === null) return false;\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (Array.isArray(a) || Array.isArray(b)) return false;\n\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.hasOwn(bObj, key)) return false;\n if (!deepEqual(aObj[key], bObj[key])) return false;\n }\n return true;\n}\n\n/**\n * Partial-match: every key in `expected` must exist in `received` with a\n * recursively matching value. Extra keys in `received` are ignored.\n *\n * As in `deepEqual`, an asymmetric marker on the `expected` side delegates to\n * its `asymmetricMatch` predicate rather than being compared structurally.\n */\nfunction deepMatchObject(received: unknown, expected: unknown): boolean {\n if (isAsymmetric(expected)) return expected.asymmetricMatch(received);\n if (Object.is(received, expected)) return true;\n if (expected === null || received === null) return Object.is(received, expected);\n if (typeof expected !== 'object' || typeof received !== 'object')\n return Object.is(received, expected);\n\n if (Array.isArray(expected) && Array.isArray(received)) {\n if (expected.length !== received.length) return false;\n for (let i = 0; i < expected.length; i++) {\n if (!deepMatchObject(received[i], expected[i])) return false;\n }\n return true;\n }\n if (Array.isArray(expected) || Array.isArray(received)) return false;\n\n const expObj = expected as Record<string, unknown>;\n const recObj = received as Record<string, unknown>;\n for (const key of Object.keys(expObj)) {\n if (!Object.hasOwn(recObj, key)) return false;\n if (!deepMatchObject(recObj[key], expObj[key])) return false;\n }\n return true;\n}\n\n/**\n * Resolves a dot-separated property path on an object.\n * Returns `{ found: true, value }` or `{ found: false }`.\n */\nfunction resolvePath(obj: unknown, dotPath: string): { found: boolean; value?: unknown } {\n const parts = dotPath.split('.');\n let cur: unknown = obj;\n for (const part of parts) {\n if (cur === null || cur === undefined || typeof cur !== 'object') return { found: false };\n const record = cur as Record<string, unknown>;\n if (!Object.hasOwn(record, part)) return { found: false };\n cur = record[part];\n }\n return { found: true, value: cur };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Lightweight expect implementation */\n/* -------------------------------------------------------------------------- */\n\n/** Thrown by expect matchers on failure. */\nclass AssertionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AssertionError';\n }\n}\n\n/** Minimal expect builder compatible with Vitest's jest-style API. */\nclass Expectation {\n #received: unknown;\n #negated = false;\n\n constructor(received: unknown) {\n this.#received = received;\n }\n\n get not(): this {\n const neg = new Expectation(this.#received) as this;\n neg.#negated = true;\n return neg;\n }\n\n #assert(pass: boolean, msg: string): void {\n const actual = this.#negated ? !pass : pass;\n if (!actual) {\n throw new AssertionError(this.#negated ? `Expected NOT: ${msg}` : msg);\n }\n }\n\n toBe(expected: unknown): void {\n this.#assert(\n Object.is(this.#received, expected),\n `Expected ${String(expected)}, received ${String(this.#received)}`,\n );\n }\n\n toEqual(expected: unknown): void {\n this.#assert(\n deepEqual(this.#received, expected),\n `Expected ${JSON.stringify(expected)}, received ${JSON.stringify(this.#received)}`,\n );\n }\n\n toBeTruthy(): void {\n this.#assert(Boolean(this.#received), `Expected truthy, received ${String(this.#received)}`);\n }\n\n toBeFalsy(): void {\n this.#assert(!this.#received, `Expected falsy, received ${String(this.#received)}`);\n }\n\n toBeNull(): void {\n this.#assert(this.#received === null, `Expected null, received ${String(this.#received)}`);\n }\n\n toBeUndefined(): void {\n this.#assert(\n this.#received === undefined,\n `Expected undefined, received ${String(this.#received)}`,\n );\n }\n\n toBeGreaterThan(n: number): void {\n this.#assert(\n typeof this.#received === 'number' && this.#received > n,\n `Expected > ${n}, received ${String(this.#received)}`,\n );\n }\n\n toBeLessThan(n: number): void {\n this.#assert(\n typeof this.#received === 'number' && this.#received < n,\n `Expected < ${n}, received ${String(this.#received)}`,\n );\n }\n\n toContain(sub: unknown): void {\n if (Array.isArray(this.#received)) {\n this.#assert(\n this.#received.includes(sub),\n `Expected array to contain ${JSON.stringify(sub)}, received ${JSON.stringify(this.#received)}`,\n );\n return;\n }\n this.#assert(\n typeof this.#received === 'string' && typeof sub === 'string' && this.#received.includes(sub),\n `Expected to contain \"${String(sub)}\", received \"${String(this.#received)}\"`,\n );\n }\n\n toThrow(msgFragment?: string): void {\n if (typeof this.#received !== 'function') {\n throw new AssertionError('toThrow: expected a function');\n }\n let threw = false;\n let errorMsg = '';\n try {\n (this.#received as () => unknown)();\n } catch (e) {\n threw = true;\n errorMsg = e instanceof Error ? e.message : String(e);\n }\n if (msgFragment !== undefined) {\n this.#assert(\n threw && errorMsg.includes(msgFragment),\n `Expected to throw containing \"${msgFragment}\", got \"${errorMsg}\"`,\n );\n } else {\n this.#assert(threw, 'Expected function to throw');\n }\n }\n\n // ---- New matchers (devtools#683) -----------------------------------------\n\n toMatchObject(expected: Record<string, unknown>): void {\n this.#assert(\n deepMatchObject(this.#received, expected),\n `Expected object to match ${JSON.stringify(expected)}, received ${JSON.stringify(this.#received)}`,\n );\n }\n\n toHaveProperty(dotPath: string, ...rest: unknown[]): void {\n const { found, value: actual } = resolvePath(this.#received, dotPath);\n if (rest.length > 0) {\n const value = rest[0];\n this.#assert(\n found && deepEqual(actual, value),\n `Expected property \"${dotPath}\" to equal ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`,\n );\n } else {\n this.#assert(found, `Expected property \"${dotPath}\" to exist`);\n }\n }\n\n // The `abstract new (...args: never) => unknown` signature is the widest\n // constructor type that TypeScript allows without explicit `any`. Real-world\n // constructors like `ErrorConstructor` are assignable to it because `never`\n // in parameter position is contravariant (any arg list satisfies `never[]`).\n toBeInstanceOf(ctor: abstract new (...args: never) => unknown): void {\n this.#assert(\n this.#received instanceof (ctor as new (...args: unknown[]) => unknown),\n `Expected instance of ${(ctor as { name?: string }).name ?? String(ctor)}, received ${String(this.#received)}`,\n );\n }\n\n toBeTypeOf(typeStr: string): void {\n this.#assert(\n typeof this.#received === typeStr,\n `Expected typeof \"${typeStr}\", received \"${typeof this.#received}\"`,\n );\n }\n}\n\n/**\n * The `expect` callable plus its asymmetric-matcher static surface\n * (`expect.any`, `expect.objectContaining`, …). The user file accesses these as\n * `expect.any(String)`; the vitest redirect (`bundle.ts`) re-exports `expect` by\n * reading `globalThis.expect`, so attaching the statics to this function object\n * makes them reachable through the getter (a function's own properties survive\n * the getter that returns the function itself).\n */\ninterface ExpectStatic {\n (received: unknown): Expectation;\n any(ctor: AnyCtor): AsymmetricMatcher;\n anything(): AsymmetricMatcher;\n objectContaining(expected: Record<string, unknown>): AsymmetricMatcher;\n arrayContaining(expected: unknown[]): AsymmetricMatcher;\n stringContaining(sub: string): AsymmetricMatcher;\n stringMatching(re: string | RegExp): AsymmetricMatcher;\n}\n\n/** The `expect` function installed as a global. */\nconst expect: ExpectStatic = ((received: unknown): Expectation =>\n new Expectation(received)) as ExpectStatic;\n\n// Asymmetric matcher statics — vitest-compatible surface (devtools#692).\nexpect.any = makeAny;\nexpect.anything = makeAnything;\nexpect.objectContaining = makeObjectContaining;\nexpect.arrayContaining = makeArrayContaining;\nexpect.stringContaining = makeStringContaining;\nexpect.stringMatching = makeStringMatching;\n\n/* -------------------------------------------------------------------------- */\n/* Vitest-4-compatible task context (devtools#746) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Internal sentinel thrown by `ctx.skip()` to unwind the test body early.\n * Caught by the run loop (never surfaced as a failure) — see `runTestModule`'s\n * test-execution `catch` branch.\n */\nclass InPageSkipSentinel {\n constructor(readonly note: string | undefined) {}\n}\n\n/**\n * Minimal vitest-4-compatible task context passed as the first argument to a\n * test function, e.g. `it('...', async (ctx) => { ctx.skip(cond, note); })`.\n *\n * Real vitest's `TestContext` is much larger (`expect`, `onTestFailed`, …) —\n * this shim only implements what sdk-example's device-fixture suites actually\n * use: `ctx.skip` (vitest 4 semantics below) and a trivial `ctx.task.name`.\n */\nexport interface TestContext {\n /**\n * `ctx.skip()` (no args) unconditionally skips the remainder of the test\n * body. `ctx.skip(cond, note)` skips only when `cond` is truthy; when falsy,\n * this is a no-op and the body continues normally. Skipping throws an\n * internal sentinel — do not catch `InPageSkipSentinel` in user code.\n */\n skip(condition?: boolean, note?: string): void;\n /** Trivial task descriptor — nice-to-have, mirrors vitest's `ctx.task.name`. */\n task: { name: string };\n}\n\nfunction _makeTestContext(name: string): TestContext {\n return {\n skip(condition?: boolean, note?: string): void {\n if (condition === undefined || condition) {\n throw new InPageSkipSentinel(note);\n }\n },\n task: { name },\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* describe / it / test registry */\n/* -------------------------------------------------------------------------- */\n\n/** A test function as the user writes it — 0-arg or 1-arg (vitest task context). */\ntype TestFn = (ctx: TestContext) => void | Promise<void>;\n\ninterface PendingTest {\n suitePath: string[];\n name: string;\n fn: TestFn;\n skip: boolean;\n}\n\nconst _pendingTests: PendingTest[] = [];\nconst _suiteStack: string[] = [];\n\n/** Registers a suite scope; calls `fn` synchronously to collect inner tests. */\nfunction describe(name: string, fn: () => void): void {\n _suiteStack.push(name);\n fn();\n _suiteStack.pop();\n}\n\n/** Registers a test. */\nfunction it(name: string, fn: TestFn): void {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn, skip: false });\n}\n\n/** Alias for `it`. */\nconst test = it;\n\n/** Skipped test — registered but not executed. */\ndescribe.skip = (name: string, _fn: () => void): void => {\n void name;\n};\nit.skip = (name: string, _fn?: TestFn): void => {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn: () => {}, skip: true });\n};\ntest.skip = it.skip;\n\n/**\n * `it.skipIf(cond)(name, fn)` / `it.runIf(cond)(name, fn)` — conditional test\n * registration. `skipIf` skips when `cond` is truthy; `runIf` runs only when\n * `cond` is truthy (skips otherwise). sdk-example uses\n * `it.skipIf(cell.platform === 'mock')(...)` to skip real-SDK-only cases in env1.\n */\ntype ItRegistrar = (name: string, fn: TestFn) => void;\nfunction _conditionalIt(skip: boolean): ItRegistrar {\n return (name, fn) => {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn, skip });\n };\n}\nit.skipIf = (cond: unknown): ItRegistrar => _conditionalIt(Boolean(cond));\nit.runIf = (cond: unknown): ItRegistrar => _conditionalIt(!cond);\ntest.skipIf = it.skipIf;\ntest.runIf = it.runIf;\n\n/**\n * `describe.skipIf(cond)(name, fn)` / `describe.runIf(cond)(name, fn)`.\n * When skipped, the suite body still runs to register its tests but every test\n * inside is marked skipped (collected via a temporary skip flag is overkill —\n * a skipped describe simply does not invoke its body, mirroring `describe.skip`).\n */\ntype DescribeRegistrar = (name: string, fn: () => void) => void;\ndescribe.skipIf = (cond: unknown): DescribeRegistrar =>\n cond ? (name, _fn) => void name : (name, fn) => describe(name, fn);\ndescribe.runIf = (cond: unknown): DescribeRegistrar =>\n cond ? (name, fn) => describe(name, fn) : (name, _fn) => void name;\n\n/* -------------------------------------------------------------------------- */\n/* Lifecycle hooks (devtools#683) */\n/* -------------------------------------------------------------------------- */\n\ntype HookType = 'beforeAll' | 'afterAll' | 'beforeEach' | 'afterEach';\n\ninterface HookEntry {\n /** Suite path at the time of registration ([] = module scope). */\n suitePath: string[];\n type: HookType;\n fn: () => void | Promise<void>;\n}\n\nconst _hooks: HookEntry[] = [];\n\nfunction _registerHook(type: HookType, fn: () => void | Promise<void>): void {\n _hooks.push({ suitePath: [..._suiteStack], type, fn });\n}\n\n/**\n * Returns hooks whose suitePath is a prefix of `testSuitePath`\n * (i.e. the hook's scope contains the test).\n */\nfunction _hooksFor(type: HookType, testSuitePath: string[]): Array<() => void | Promise<void>> {\n return _hooks\n .filter((h) => {\n if (h.type !== type) return false;\n // Hook scope must be a prefix of the test's suite path\n if (h.suitePath.length > testSuitePath.length) return false;\n for (let i = 0; i < h.suitePath.length; i++) {\n if (h.suitePath[i] !== testSuitePath[i]) return false;\n }\n return true;\n })\n .map((h) => h.fn);\n}\n\n/** Runs an array of hook functions in order, awaiting each. */\nasync function _runHooks(fns: Array<() => void | Promise<void>>): Promise<Error | null> {\n for (const fn of fns) {\n try {\n await fn();\n } catch (e) {\n return e instanceof Error ? e : new Error(String(e));\n }\n }\n return null;\n}\n\nfunction beforeAll(fn: () => void | Promise<void>): void {\n _registerHook('beforeAll', fn);\n}\nfunction afterAll(fn: () => void | Promise<void>): void {\n _registerHook('afterAll', fn);\n}\nfunction beforeEach(fn: () => void | Promise<void>): void {\n _registerHook('beforeEach', fn);\n}\nfunction afterEach(fn: () => void | Promise<void>): void {\n _registerHook('afterEach', fn);\n}\n\n/* -------------------------------------------------------------------------- */\n/* vi shim (devtools#683) */\n/* -------------------------------------------------------------------------- */\n\ninterface SpyCall {\n args: unknown[];\n returnValue: unknown;\n}\n\ninterface MockFn<T extends unknown[], R> {\n (...args: T): R;\n mock: { calls: SpyCall[] };\n mockImplementation(fn: (...args: T) => R): this;\n mockReturnValue(value: R): this;\n mockRestore(): void;\n}\n\ninterface SpyRecord {\n obj: Record<string, unknown>;\n method: string;\n original: unknown;\n}\n\nconst _spyRegistry: SpyRecord[] = [];\n\nfunction _createMockFn<T extends unknown[], R>(impl?: (...args: T) => R): MockFn<T, R> {\n let currentImpl: ((...args: T) => R) | undefined = impl;\n const calls: SpyCall[] = [];\n\n const mockFn = ((...args: T): R => {\n const returnValue = currentImpl ? currentImpl(...args) : (undefined as unknown as R);\n calls.push({ args, returnValue });\n return returnValue;\n }) as MockFn<T, R>;\n\n mockFn.mock = { calls };\n\n mockFn.mockImplementation = function (fn: (...args: T) => R): typeof mockFn {\n currentImpl = fn;\n return this;\n };\n\n mockFn.mockReturnValue = function (value: R): typeof mockFn {\n currentImpl = () => value;\n return this;\n };\n\n // No-op restore for standalone fn (only spyOn-created fns have a real restore)\n mockFn.mockRestore = (): void => {};\n\n return mockFn;\n}\n\nconst vi = {\n /** Creates a spy on `obj[method]`, replacing it with a mock function. */\n spyOn<T extends Record<string, unknown>, K extends keyof T>(\n obj: T,\n method: K,\n ): MockFn<unknown[], unknown> {\n const original = obj[method];\n const spy = _createMockFn<unknown[], unknown>(\n typeof original === 'function' ? (original as (...args: unknown[]) => unknown) : undefined,\n );\n\n spy.mockRestore = (): void => {\n obj[method] = original as T[K];\n };\n\n _spyRegistry.push({ obj: obj as Record<string, unknown>, method: method as string, original });\n obj[method] = spy as unknown as T[K];\n return spy;\n },\n\n /** Creates a standalone mock function, optionally wrapping `impl`. */\n fn<T extends unknown[], R>(impl?: (...args: T) => R): MockFn<T, R> {\n return _createMockFn(impl);\n },\n\n /** Restores all spies created via `vi.spyOn` to their original values. */\n restoreAllMocks(): void {\n for (const { obj, method, original } of _spyRegistry) {\n obj[method] = original;\n }\n _spyRegistry.length = 0;\n },\n};\n\n/* -------------------------------------------------------------------------- */\n/* Runtime entry point */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Runtime globals object — exported for direct use in unit tests so that\n * test factories can reference runtime's own `it`/`expect`/`beforeAll`/etc.\n * without depending on `globalThis` injection.\n *\n * In a real WebView bundle these are accessed via globals installed by\n * `runTestModule`; in Node tests, import from here directly.\n */\nexport const runtimeGlobals = {\n describe,\n it,\n test,\n expect,\n beforeAll,\n afterAll,\n beforeEach,\n afterEach,\n vi,\n} as const;\n\n/**\n * Installs describe/it/test/expect/afterAll/afterEach/beforeAll/beforeEach/vi\n * as globals, invokes `moduleFactory` to register the user's tests, then\n * executes them and returns a RunReport.\n *\n * This function is exported as `__testBundle.runTestModule` by the IIFE wrapper\n * that bundle.ts generates. The Node-side rpc.ts calls it via `Runtime.evaluate`.\n *\n * @param moduleFactory - A zero-argument function that contains the user's\n * top-level test code (describe/it/test calls). The bundler wraps the entire\n * test module so that its top-level statements become the body of this factory.\n */\nexport async function runTestModule(\n moduleFactory?: () => void | Promise<void>,\n): Promise<RunReport> {\n // Reset state for re-entrant calls within the same page context.\n _pendingTests.length = 0;\n _suiteStack.length = 0;\n _hooks.length = 0;\n _spyRegistry.length = 0;\n\n // Install globals that user test code expects.\n type G = typeof globalThis & {\n describe: typeof describe;\n it: typeof it;\n test: typeof test;\n expect: typeof expect;\n beforeAll: typeof beforeAll;\n afterAll: typeof afterAll;\n beforeEach: typeof beforeEach;\n afterEach: typeof afterEach;\n vi: typeof vi;\n };\n const g = globalThis as G;\n g.describe = describe;\n g.it = it;\n g.test = test;\n g.expect = expect;\n g.beforeAll = beforeAll;\n g.afterAll = afterAll;\n g.beforeEach = beforeEach;\n g.afterEach = afterEach;\n g.vi = vi;\n\n // Run the factory (which registers describe/it/test blocks via globals).\n if (moduleFactory) {\n await moduleFactory();\n }\n\n const wallStart = Date.now();\n const startedAt = new Date(wallStart).toISOString();\n const results: TestResult[] = [];\n\n // Determine unique suite scopes from registered tests, in discovery order.\n // We need to fire beforeAll/afterAll once per scope (grouped by suitePath).\n //\n // Simplified model: we run beforeAll hooks before the first test in a scope\n // and afterAll hooks after the last test in a scope. Scope identity is the\n // entire suitePath string (e.g. \"Suite A > Suite B\").\n //\n // For module-scope hooks (suitePath=[]), they wrap the entire test run.\n\n // Group tests by their suite key to track beforeAll/afterAll per scope.\n // We keep a Set of scopes for which beforeAll has been fired.\n const firedBeforeAll = new Set<string>();\n // Map from scope key → last index in _pendingTests that belongs to that scope.\n const lastIndexForScope = new Map<string, number>();\n for (let i = 0; i < _pendingTests.length; i++) {\n const key = _pendingTests[i].suitePath.join('\\0');\n lastIndexForScope.set(key, i);\n // Also compute for parent scopes (module scope = '')\n const path = _pendingTests[i].suitePath;\n for (let depth = 0; depth < path.length; depth++) {\n const parentKey = path.slice(0, depth).join('\\0');\n const cur = lastIndexForScope.get(parentKey) ?? -1;\n if (i > cur) lastIndexForScope.set(parentKey, i);\n }\n }\n // Module scope key\n const MODULE_KEY = '';\n if (!lastIndexForScope.has(MODULE_KEY) && _pendingTests.length > 0) {\n lastIndexForScope.set(MODULE_KEY, _pendingTests.length - 1);\n }\n\n // Fire module-scope beforeAll before any tests\n if (_pendingTests.length > 0) {\n const baFns = _hooksFor('beforeAll', []);\n const baErr = await _runHooks(baFns);\n firedBeforeAll.add(MODULE_KEY);\n if (baErr) {\n // If module beforeAll fails, mark all tests as failed.\n for (const pending of _pendingTests) {\n const fullName = [...pending.suitePath, pending.name].join(' > ');\n results.push({\n name: fullName,\n status: 'fail',\n duration: 0,\n error: `beforeAll failed: ${baErr.message}`,\n });\n }\n const duration = Date.now() - wallStart;\n const passed = results.filter((r) => r.status === 'pass').length;\n const failed = results.filter((r) => r.status === 'fail').length;\n const skipped = results.filter((r) => r.status === 'skip').length;\n // Still run module afterAll for cleanup (e.g. flushCapture)\n const aaFns = _hooksFor('afterAll', []);\n await _runHooks(aaFns);\n return { startedAt, duration, passed, failed, skipped, tests: results };\n }\n }\n\n for (let i = 0; i < _pendingTests.length; i++) {\n const pending = _pendingTests[i];\n const fullName = [...pending.suitePath, pending.name].join(' > ');\n\n if (pending.skip) {\n results.push({ name: fullName, status: 'skip', duration: 0 });\n continue;\n }\n\n // Fire suite-scoped beforeAll for any new scopes entered by this test\n for (let depth = 1; depth <= pending.suitePath.length; depth++) {\n const scopePath = pending.suitePath.slice(0, depth);\n const scopeKey = scopePath.join('\\0');\n if (!firedBeforeAll.has(scopeKey)) {\n // Only hooks registered exactly at this scope (not broader/narrower)\n const scopedFns = _hooks\n .filter((h) => h.type === 'beforeAll' && h.suitePath.join('\\0') === scopeKey)\n .map((h) => h.fn);\n const baErr = await _runHooks(scopedFns);\n firedBeforeAll.add(scopeKey);\n if (baErr) {\n // Mark remaining tests in this scope as failed\n results.push({\n name: fullName,\n status: 'fail',\n duration: 0,\n error: `beforeAll failed: ${baErr.message}`,\n });\n }\n }\n }\n\n // beforeEach\n const beFns = _hooksFor('beforeEach', pending.suitePath);\n const beErr = await _runHooks(beFns);\n\n const tStart = Date.now();\n let testErr: string | undefined;\n let inPageSkip: InPageSkipSentinel | undefined;\n\n if (beErr) {\n testErr = `beforeEach failed: ${beErr.message}`;\n } else {\n try {\n await pending.fn(_makeTestContext(fullName));\n } catch (e) {\n if (e instanceof InPageSkipSentinel) {\n inPageSkip = e;\n } else {\n testErr = e instanceof Error ? e.message : String(e);\n }\n }\n }\n\n // afterEach — always run even if test failed or was skipped mid-body.\n const aeFns = _hooksFor('afterEach', pending.suitePath);\n const aeErr = await _runHooks(aeFns);\n if (aeErr && !testErr && !inPageSkip) testErr = `afterEach failed: ${aeErr.message}`;\n\n if (inPageSkip) {\n // ctx.skip() unwound the body — record as skipped (not pass/fail), same\n // as the static it.skip path. The note (if any) rides on TestResult.note.\n results.push({\n name: fullName,\n status: 'skip',\n duration: Date.now() - tStart,\n ...(inPageSkip.note !== undefined ? { note: inPageSkip.note } : {}),\n });\n } else if (testErr !== undefined) {\n results.push({\n name: fullName,\n status: 'fail',\n duration: Date.now() - tStart,\n error: testErr,\n });\n } else {\n results.push({ name: fullName, status: 'pass', duration: Date.now() - tStart });\n }\n\n // Fire suite-scoped afterAll when this is the last test in each scope\n for (let depth = pending.suitePath.length; depth >= 1; depth--) {\n const scopePath = pending.suitePath.slice(0, depth);\n const scopeKey = scopePath.join('\\0');\n const lastIdx = lastIndexForScope.get(scopeKey) ?? -1;\n if (lastIdx === i) {\n const scopedFns = _hooks\n .filter((h) => h.type === 'afterAll' && h.suitePath.join('\\0') === scopeKey)\n .map((h) => h.fn);\n await _runHooks(scopedFns);\n }\n }\n }\n\n // Fire module-scope afterAll after all tests — critical for flushCapture\n const moduleAfterAllFns = _hooks\n .filter((h) => h.type === 'afterAll' && h.suitePath.length === 0)\n .map((h) => h.fn);\n await _runHooks(moduleAfterAllFns);\n\n const duration = Date.now() - wallStart;\n const passed = results.filter((r) => r.status === 'pass').length;\n const failed = results.filter((r) => r.status === 'fail').length;\n const skipped = results.filter((r) => r.status === 'skip').length;\n\n return { startedAt, duration, passed, failed, skipped, tests: results };\n}\n"],"mappings":";;;;;;;;AAsEA,MAAM,mBAAmB;;AAkBzB,SAAS,aAAa,GAAoC;AACxD,QACE,OAAO,MAAM,YACb,MAAM,QACL,EAA8B,sBAAsB,QACrD,OAAQ,EAAoC,oBAAoB;;;;;;;;;;;AAgBpE,SAAS,QAAQ,MAAkC;CACjD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E,MAAI,WAGF,SAAQ,KAAK;GACX,MAAM;GACN,QAAQ;GACR,UAAU,KAAK,KAAK,GAAG;GACvB,GAAI,WAAW,SAAS,KAAA,IAAY,EAAE,MAAM,WAAW,MAAM,GAAG,EAAE;GACnE,CAAC;WACO,YAAY,KAAA,EACrB,SAAQ,KAAK;GACX,MAAM;GACN,QAAQ;GACR,UAAU,KAAK,KAAK,GAAG;GACvB,OAAO;GACR,CAAC;MAEF,SAAQ,KAAK;GAAE,MAAM;GAAU,QAAQ;GAAQ,UAAU,KAAK,KAAK,GAAG;GAAQ,CAAC;AAIjF,OAAK,IAAI,QAAQ,QAAQ,UAAU,QAAQ,SAAS,GAAG,SAAS;GAE9D,MAAM,WADY,QAAQ,UAAU,MAAM,GAAG,MAAM,CACxB,KAAK,KAAK;AAErC,QADgB,kBAAkB,IAAI,SAAS,IAAI,QACnC,EAId,OAAM,UAHY,OACf,QAAQ,MAAM,EAAE,SAAS,cAAc,EAAE,UAAU,KAAK,KAAK,KAAK,SAAS,CAC3E,KAAK,MAAM,EAAE,GAAG,CACO;;;AAShC,OAAM,UAHoB,OACvB,QAAQ,MAAM,EAAE,SAAS,cAAc,EAAE,UAAU,WAAW,EAAE,CAChE,KAAK,MAAM,EAAE,GAAG,CACe;AAOlC,QAAO;EAAE;EAAW,UALH,KAAK,KAAK,GAAG;EAKA,QAJf,QAAQ,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC;EAIpB,QAHvB,QAAQ,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC;EAGZ,SAF9B,QAAQ,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC;EAEJ,OAAO;EAAS"}
1
+ {"version":3,"file":"runtime.js","names":["#received","#negated","#assert"],"sources":["../../src/test-runner/runtime.ts"],"sourcesContent":["/**\n * Thin test runtime for WebView execution.\n *\n * This file is bundled by `bundle.ts` together with the user's test file\n * into a single IIFE injected into the WebView via `Runtime.evaluate`.\n * It MUST stay browser-compatible — no Node.js APIs allowed.\n *\n * Design: rather than shipping @vitest/runner verbatim into a WebView (where\n * its Node-side internals cause issues), this runtime provides a minimal\n * compatible API surface — describe/it/test/expect globals — collects results\n * into a plain JSON-safe object, and exports `runTestModule` as the entry point.\n *\n * @vitest/runner and @vitest/expect are listed as dependencies so that the\n * package's type contracts are available and so the browser-compatible subsets\n * can be referenced. The Vitest custom pool that drives this runtime through\n * Vitest's `PoolRunnerInitializer` lives in `pool.ts`.\n *\n * NOTE: this file is imported by type from Node-side code (rpc.ts / relay-worker.ts)\n * for the RunReport / TestResult type shapes. The runtime ITSELF is not imported\n * at runtime on the Node side — only the types are used.\n */\n\nimport { isThrottledError } from './throttle.js';\n\n/* -------------------------------------------------------------------------- */\n/* Public result types (used by rpc.ts and relay-worker.ts) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Result of a single test case.\n * All fields are JSON-serialisable.\n */\nexport interface TestResult {\n /** Full dot-joined test name including nested suite names. */\n name: string;\n /** `'pass'` or `'fail'`. `'skip'` for skipped tests. */\n status: 'pass' | 'fail' | 'skip';\n /** Duration in milliseconds. */\n duration: number;\n /** Error message (fail only). Does NOT include the expression/secret. */\n error?: string;\n /**\n * Optional note attached to a skip — populated when the test body itself\n * calls `ctx.skip(cond, note)` (devtools#746), mirroring the static\n * `it.skip`/`it.skipIf` path which has no note today. `'skip'` status only.\n */\n note?: string;\n /**\n * Number of throttle-aware re-executions of the test BODY (devtools#767) —\n * present only when at least one retry was attempted (`>= 1`); omitted\n * (never `0`) for every test that never hit `APP_BRIDGE_THROTTLED`, so\n * existing consumers (sdk-example's diff script) see byte-identical reports\n * for the common case. A test that eventually PASSES after retrying still\n * carries this field — it is provenance, not a failure flag.\n */\n throttleRetries?: number;\n}\n\n/** Aggregate report returned by `runTestModule`. */\nexport interface RunReport {\n /** ISO timestamp of when `runTestModule` was called. */\n startedAt: string;\n /** Total elapsed milliseconds (wall-clock). */\n duration: number;\n passed: number;\n failed: number;\n skipped: number;\n tests: TestResult[];\n}\n\n/* -------------------------------------------------------------------------- */\n/* THROTTLED-aware test retry (devtools#767) */\n/* -------------------------------------------------------------------------- */\n\n/** Backoff delays (ms) between throttle-retry attempts: 1s, then 2s. */\nconst TEST_RETRY_BACKOFF_MS = [1_000, 2_000] as const;\n\n/** Max retry attempts per test after the initial run (devtools#767: \"최대 2회 재시도\"). */\nconst TEST_MAX_RETRIES = TEST_RETRY_BACKOFF_MS.length;\n\n/** Real `setTimeout`-backed sleep — the production default for {@link RunTestModuleOptions.sleep}. */\nconst DEFAULT_SLEEP = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Test-only override surface for `runTestModule`. Never populated by the\n * generated bundle — see that function's doc.\n */\nexport interface RunTestModuleOptions {\n /**\n * Overrides the backoff/pacing sleep implementation. Defaults to a real\n * `setTimeout`-backed sleep. Unit tests pass a fake (e.g. an\n * immediately-resolving spy) so retry/pacing tests don't take real\n * wall-clock seconds.\n */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/**\n * Renders a thrown value into a `TestResult.error` string. Handles three\n * shapes:\n * - a real `Error` (or subclass) — its `.message`;\n * - an error-LIKE plain object with a string `.message` (the 2.x native\n * bridge envelope this test-runner observes, e.g.\n * `{name, code, userInfo, moduleName, __isError}` — devtools#767's\n * `APP_BRIDGE_THROTTLED` rejections are exactly this shape, not an\n * `Error` instance) — its `.message` field;\n * - anything else — `String(e)` (the pre-#767 fallback, unchanged).\n *\n * Without the middle case, a native envelope's `.message` (the only useful\n * diagnostic text) was discarded in favor of the useless `\"[object Object]\"`.\n */\nfunction stringifyThrown(e: unknown): string {\n if (e instanceof Error) return e.message;\n if (typeof e === 'object' && e !== null) {\n const rec = e as { message?: unknown };\n if (typeof rec.message === 'string') return rec.message;\n }\n return String(e);\n}\n\n/* -------------------------------------------------------------------------- */\n/* Asymmetric matchers (devtools#692) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Brand property that tags asymmetric matcher markers (`expect.any(String)`,\n * `expect.objectContaining(...)`, etc). A reserved string key is used as the\n * brand so the guard stays a plain own-property check — markers are only ever\n * compared in-process by reference, so no cross-realm Symbol coordination is\n * needed.\n */\nconst ASYMMETRIC_BRAND = '$$asymmetricMatch' as const;\n\n/**\n * An asymmetric matcher: a placeholder that, when found on the `expected` side\n * of a deep comparison, runs its own `asymmetricMatch(actual)` predicate\n * instead of being structurally compared as a plain object. This is what makes\n * `toMatchObject({ hash: expect.any(String) })` match any string `hash`.\n */\ninterface AsymmetricMatcher {\n /** Brand discriminator — present only on asymmetric markers. */\n [ASYMMETRIC_BRAND]: true;\n /** Human-readable label used in failure messages. */\n toString(): string;\n /** Returns true when `actual` satisfies this matcher. */\n asymmetricMatch(actual: unknown): boolean;\n}\n\n/** Narrowing guard: is `v` an asymmetric matcher marker? */\nfunction isAsymmetric(v: unknown): v is AsymmetricMatcher {\n return (\n typeof v === 'object' &&\n v !== null &&\n (v as Record<string, unknown>)[ASYMMETRIC_BRAND] === true &&\n typeof (v as { asymmetricMatch?: unknown }).asymmetricMatch === 'function'\n );\n}\n\n/** The widest constructor type TypeScript allows without `any` (see toBeInstanceOf). */\ntype AnyCtor = abstract new (...args: never) => unknown;\n\n/**\n * `expect.any(Ctor)` — matches a value by its constructor. Primitive wrappers\n * (`String`/`Number`/`Boolean`) are matched by `typeof` (so the unboxed\n * primitive matches) AND by `instanceof` (so a boxed wrapper instance also\n * matches). `BigInt`/`Symbol` match by `typeof`. `Object` matches any non-null\n * object (NOT functions, matching vitest), `Array` uses `Array.isArray`,\n * `Function` uses `typeof === 'function'`, and any other constructor (user\n * classes) falls back to `instanceof`.\n */\nfunction makeAny(ctor: AnyCtor): AsymmetricMatcher {\n const name = (ctor as { name?: string }).name ?? String(ctor);\n const ctorAsFn = ctor as unknown as (new (...args: unknown[]) => unknown) | undefined;\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `Any<${name}>`,\n asymmetricMatch(actual: unknown): boolean {\n if (actual === null || actual === undefined) return false;\n switch (ctor as unknown) {\n case String:\n return typeof actual === 'string' || actual instanceof String;\n case Number:\n return typeof actual === 'number' || actual instanceof Number;\n case Boolean:\n return typeof actual === 'boolean' || actual instanceof Boolean;\n case BigInt:\n return typeof actual === 'bigint';\n case Symbol:\n return typeof actual === 'symbol';\n case Function:\n return typeof actual === 'function';\n case Object:\n // Match vitest: `expect.any(Object)` accepts objects only, NOT\n // functions (vitest checks `typeof other === 'object'`). `null` is\n // already excluded by the guard above.\n return typeof actual === 'object';\n case Array:\n return Array.isArray(actual);\n default:\n return ctorAsFn ? actual instanceof ctorAsFn : false;\n }\n },\n };\n}\n\n/** `expect.anything()` — matches any value except `null`/`undefined`. */\nfunction makeAnything(): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => 'Anything',\n asymmetricMatch: (actual: unknown): boolean => actual !== null && actual !== undefined,\n };\n}\n\n/** `expect.objectContaining(obj)` — partial-match every key of `obj` on `actual`. */\nfunction makeObjectContaining(expected: Record<string, unknown>): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `ObjectContaining<${safeStringify(expected)}>`,\n asymmetricMatch: (actual: unknown): boolean => deepMatchObject(actual, expected),\n };\n}\n\n/** `expect.arrayContaining(arr)` — `actual` is an array containing each element of `arr`. */\nfunction makeArrayContaining(expected: unknown[]): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `ArrayContaining<${safeStringify(expected)}>`,\n asymmetricMatch(actual: unknown): boolean {\n if (!Array.isArray(actual)) return false;\n return expected.every((exp) =>\n actual.some((act) => (isAsymmetric(exp) ? exp.asymmetricMatch(act) : deepEqual(act, exp))),\n );\n },\n };\n}\n\n/** `expect.stringContaining(sub)` — `actual` is a string containing `sub`. */\nfunction makeStringContaining(sub: string): AsymmetricMatcher {\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `StringContaining<${sub}>`,\n asymmetricMatch: (actual: unknown): boolean =>\n typeof actual === 'string' && actual.includes(sub),\n };\n}\n\n/** `expect.stringMatching(re)` — `actual` is a string matching `re` (string or RegExp). */\nfunction makeStringMatching(re: string | RegExp): AsymmetricMatcher {\n const pattern = typeof re === 'string' ? new RegExp(re) : re;\n return {\n [ASYMMETRIC_BRAND]: true,\n toString: () => `StringMatching<${String(pattern)}>`,\n asymmetricMatch: (actual: unknown): boolean =>\n typeof actual === 'string' && pattern.test(actual),\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Deep equality helpers */\n/* -------------------------------------------------------------------------- */\n\n/** JSON.stringify that never throws (cycles/BigInt) — for failure messages. */\nfunction safeStringify(v: unknown): string {\n try {\n return (\n JSON.stringify(v, (_k, val) =>\n isAsymmetric(val) ? val.toString() : typeof val === 'bigint' ? `${val}n` : val,\n ) ?? String(v)\n );\n } catch {\n return String(v);\n }\n}\n\n/**\n * Recursive structural equality — replaces JSON.stringify comparison to\n * handle key-order differences and undefined values correctly.\n *\n * When the `b` (expected) side is an asymmetric marker, its `asymmetricMatch`\n * predicate decides the result instead of structural comparison — markers are\n * placeholders, not plain objects, so deep-comparing them never matches.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (isAsymmetric(b)) return b.asymmetricMatch(a);\n if (Object.is(a, b)) return true;\n if (a === null || b === null) return false;\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (Array.isArray(a) || Array.isArray(b)) return false;\n\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.hasOwn(bObj, key)) return false;\n if (!deepEqual(aObj[key], bObj[key])) return false;\n }\n return true;\n}\n\n/**\n * Partial-match: every key in `expected` must exist in `received` with a\n * recursively matching value. Extra keys in `received` are ignored.\n *\n * As in `deepEqual`, an asymmetric marker on the `expected` side delegates to\n * its `asymmetricMatch` predicate rather than being compared structurally.\n */\nfunction deepMatchObject(received: unknown, expected: unknown): boolean {\n if (isAsymmetric(expected)) return expected.asymmetricMatch(received);\n if (Object.is(received, expected)) return true;\n if (expected === null || received === null) return Object.is(received, expected);\n if (typeof expected !== 'object' || typeof received !== 'object')\n return Object.is(received, expected);\n\n if (Array.isArray(expected) && Array.isArray(received)) {\n if (expected.length !== received.length) return false;\n for (let i = 0; i < expected.length; i++) {\n if (!deepMatchObject(received[i], expected[i])) return false;\n }\n return true;\n }\n if (Array.isArray(expected) || Array.isArray(received)) return false;\n\n const expObj = expected as Record<string, unknown>;\n const recObj = received as Record<string, unknown>;\n for (const key of Object.keys(expObj)) {\n if (!Object.hasOwn(recObj, key)) return false;\n if (!deepMatchObject(recObj[key], expObj[key])) return false;\n }\n return true;\n}\n\n/**\n * Resolves a dot-separated property path on an object.\n * Returns `{ found: true, value }` or `{ found: false }`.\n */\nfunction resolvePath(obj: unknown, dotPath: string): { found: boolean; value?: unknown } {\n const parts = dotPath.split('.');\n let cur: unknown = obj;\n for (const part of parts) {\n if (cur === null || cur === undefined || typeof cur !== 'object') return { found: false };\n const record = cur as Record<string, unknown>;\n if (!Object.hasOwn(record, part)) return { found: false };\n cur = record[part];\n }\n return { found: true, value: cur };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Lightweight expect implementation */\n/* -------------------------------------------------------------------------- */\n\n/** Thrown by expect matchers on failure. */\nclass AssertionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AssertionError';\n }\n}\n\n/** Minimal expect builder compatible with Vitest's jest-style API. */\nclass Expectation {\n #received: unknown;\n #negated = false;\n\n constructor(received: unknown) {\n this.#received = received;\n }\n\n get not(): this {\n const neg = new Expectation(this.#received) as this;\n neg.#negated = true;\n return neg;\n }\n\n #assert(pass: boolean, msg: string): void {\n const actual = this.#negated ? !pass : pass;\n if (!actual) {\n throw new AssertionError(this.#negated ? `Expected NOT: ${msg}` : msg);\n }\n }\n\n toBe(expected: unknown): void {\n this.#assert(\n Object.is(this.#received, expected),\n `Expected ${String(expected)}, received ${String(this.#received)}`,\n );\n }\n\n toEqual(expected: unknown): void {\n this.#assert(\n deepEqual(this.#received, expected),\n `Expected ${JSON.stringify(expected)}, received ${JSON.stringify(this.#received)}`,\n );\n }\n\n toBeTruthy(): void {\n this.#assert(Boolean(this.#received), `Expected truthy, received ${String(this.#received)}`);\n }\n\n toBeFalsy(): void {\n this.#assert(!this.#received, `Expected falsy, received ${String(this.#received)}`);\n }\n\n toBeNull(): void {\n this.#assert(this.#received === null, `Expected null, received ${String(this.#received)}`);\n }\n\n toBeUndefined(): void {\n this.#assert(\n this.#received === undefined,\n `Expected undefined, received ${String(this.#received)}`,\n );\n }\n\n toBeGreaterThan(n: number): void {\n this.#assert(\n typeof this.#received === 'number' && this.#received > n,\n `Expected > ${n}, received ${String(this.#received)}`,\n );\n }\n\n toBeLessThan(n: number): void {\n this.#assert(\n typeof this.#received === 'number' && this.#received < n,\n `Expected < ${n}, received ${String(this.#received)}`,\n );\n }\n\n toContain(sub: unknown): void {\n if (Array.isArray(this.#received)) {\n this.#assert(\n this.#received.includes(sub),\n `Expected array to contain ${JSON.stringify(sub)}, received ${JSON.stringify(this.#received)}`,\n );\n return;\n }\n this.#assert(\n typeof this.#received === 'string' && typeof sub === 'string' && this.#received.includes(sub),\n `Expected to contain \"${String(sub)}\", received \"${String(this.#received)}\"`,\n );\n }\n\n toThrow(msgFragment?: string): void {\n if (typeof this.#received !== 'function') {\n throw new AssertionError('toThrow: expected a function');\n }\n let threw = false;\n let errorMsg = '';\n try {\n (this.#received as () => unknown)();\n } catch (e) {\n threw = true;\n errorMsg = e instanceof Error ? e.message : String(e);\n }\n if (msgFragment !== undefined) {\n this.#assert(\n threw && errorMsg.includes(msgFragment),\n `Expected to throw containing \"${msgFragment}\", got \"${errorMsg}\"`,\n );\n } else {\n this.#assert(threw, 'Expected function to throw');\n }\n }\n\n // ---- New matchers (devtools#683) -----------------------------------------\n\n toMatchObject(expected: Record<string, unknown>): void {\n this.#assert(\n deepMatchObject(this.#received, expected),\n `Expected object to match ${JSON.stringify(expected)}, received ${JSON.stringify(this.#received)}`,\n );\n }\n\n toHaveProperty(dotPath: string, ...rest: unknown[]): void {\n const { found, value: actual } = resolvePath(this.#received, dotPath);\n if (rest.length > 0) {\n const value = rest[0];\n this.#assert(\n found && deepEqual(actual, value),\n `Expected property \"${dotPath}\" to equal ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`,\n );\n } else {\n this.#assert(found, `Expected property \"${dotPath}\" to exist`);\n }\n }\n\n // The `abstract new (...args: never) => unknown` signature is the widest\n // constructor type that TypeScript allows without explicit `any`. Real-world\n // constructors like `ErrorConstructor` are assignable to it because `never`\n // in parameter position is contravariant (any arg list satisfies `never[]`).\n toBeInstanceOf(ctor: abstract new (...args: never) => unknown): void {\n this.#assert(\n this.#received instanceof (ctor as new (...args: unknown[]) => unknown),\n `Expected instance of ${(ctor as { name?: string }).name ?? String(ctor)}, received ${String(this.#received)}`,\n );\n }\n\n toBeTypeOf(typeStr: string): void {\n this.#assert(\n typeof this.#received === typeStr,\n `Expected typeof \"${typeStr}\", received \"${typeof this.#received}\"`,\n );\n }\n}\n\n/**\n * The `expect` callable plus its asymmetric-matcher static surface\n * (`expect.any`, `expect.objectContaining`, …). The user file accesses these as\n * `expect.any(String)`; the vitest redirect (`bundle.ts`) re-exports `expect` by\n * reading `globalThis.expect`, so attaching the statics to this function object\n * makes them reachable through the getter (a function's own properties survive\n * the getter that returns the function itself).\n */\ninterface ExpectStatic {\n (received: unknown): Expectation;\n any(ctor: AnyCtor): AsymmetricMatcher;\n anything(): AsymmetricMatcher;\n objectContaining(expected: Record<string, unknown>): AsymmetricMatcher;\n arrayContaining(expected: unknown[]): AsymmetricMatcher;\n stringContaining(sub: string): AsymmetricMatcher;\n stringMatching(re: string | RegExp): AsymmetricMatcher;\n}\n\n/** The `expect` function installed as a global. */\nconst expect: ExpectStatic = ((received: unknown): Expectation =>\n new Expectation(received)) as ExpectStatic;\n\n// Asymmetric matcher statics — vitest-compatible surface (devtools#692).\nexpect.any = makeAny;\nexpect.anything = makeAnything;\nexpect.objectContaining = makeObjectContaining;\nexpect.arrayContaining = makeArrayContaining;\nexpect.stringContaining = makeStringContaining;\nexpect.stringMatching = makeStringMatching;\n\n/* -------------------------------------------------------------------------- */\n/* Vitest-4-compatible task context (devtools#746) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Internal sentinel thrown by `ctx.skip()` to unwind the test body early.\n * Caught by the run loop (never surfaced as a failure) — see `runTestModule`'s\n * test-execution `catch` branch.\n */\nclass InPageSkipSentinel {\n constructor(readonly note: string | undefined) {}\n}\n\n/**\n * Minimal vitest-4-compatible task context passed as the first argument to a\n * test function, e.g. `it('...', async (ctx) => { ctx.skip(cond, note); })`.\n *\n * Real vitest's `TestContext` is much larger (`expect`, `onTestFailed`, …) —\n * this shim only implements what sdk-example's device-fixture suites actually\n * use: `ctx.skip` (vitest 4 semantics below) and a trivial `ctx.task.name`.\n */\nexport interface TestContext {\n /**\n * `ctx.skip()` (no args) unconditionally skips the remainder of the test\n * body. `ctx.skip(cond, note)` skips only when `cond` is truthy; when falsy,\n * this is a no-op and the body continues normally. Skipping throws an\n * internal sentinel — do not catch `InPageSkipSentinel` in user code.\n */\n skip(condition?: boolean, note?: string): void;\n /** Trivial task descriptor — nice-to-have, mirrors vitest's `ctx.task.name`. */\n task: { name: string };\n}\n\nfunction _makeTestContext(name: string): TestContext {\n return {\n skip(condition?: boolean, note?: string): void {\n if (condition === undefined || condition) {\n throw new InPageSkipSentinel(note);\n }\n },\n task: { name },\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* describe / it / test registry */\n/* -------------------------------------------------------------------------- */\n\n/** A test function as the user writes it — 0-arg or 1-arg (vitest task context). */\ntype TestFn = (ctx: TestContext) => void | Promise<void>;\n\ninterface PendingTest {\n suitePath: string[];\n name: string;\n fn: TestFn;\n skip: boolean;\n}\n\nconst _pendingTests: PendingTest[] = [];\nconst _suiteStack: string[] = [];\n\n/** Registers a suite scope; calls `fn` synchronously to collect inner tests. */\nfunction describe(name: string, fn: () => void): void {\n _suiteStack.push(name);\n fn();\n _suiteStack.pop();\n}\n\n/** Registers a test. */\nfunction it(name: string, fn: TestFn): void {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn, skip: false });\n}\n\n/** Alias for `it`. */\nconst test = it;\n\n/** Skipped test — registered but not executed. */\ndescribe.skip = (name: string, _fn: () => void): void => {\n void name;\n};\nit.skip = (name: string, _fn?: TestFn): void => {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn: () => {}, skip: true });\n};\ntest.skip = it.skip;\n\n/**\n * `it.skipIf(cond)(name, fn)` / `it.runIf(cond)(name, fn)` — conditional test\n * registration. `skipIf` skips when `cond` is truthy; `runIf` runs only when\n * `cond` is truthy (skips otherwise). sdk-example uses\n * `it.skipIf(cell.platform === 'mock')(...)` to skip real-SDK-only cases in env1.\n */\ntype ItRegistrar = (name: string, fn: TestFn) => void;\nfunction _conditionalIt(skip: boolean): ItRegistrar {\n return (name, fn) => {\n _pendingTests.push({ suitePath: [..._suiteStack], name, fn, skip });\n };\n}\nit.skipIf = (cond: unknown): ItRegistrar => _conditionalIt(Boolean(cond));\nit.runIf = (cond: unknown): ItRegistrar => _conditionalIt(!cond);\ntest.skipIf = it.skipIf;\ntest.runIf = it.runIf;\n\n/**\n * `describe.skipIf(cond)(name, fn)` / `describe.runIf(cond)(name, fn)`.\n * When skipped, the suite body still runs to register its tests but every test\n * inside is marked skipped (collected via a temporary skip flag is overkill —\n * a skipped describe simply does not invoke its body, mirroring `describe.skip`).\n */\ntype DescribeRegistrar = (name: string, fn: () => void) => void;\ndescribe.skipIf = (cond: unknown): DescribeRegistrar =>\n cond ? (name, _fn) => void name : (name, fn) => describe(name, fn);\ndescribe.runIf = (cond: unknown): DescribeRegistrar =>\n cond ? (name, fn) => describe(name, fn) : (name, _fn) => void name;\n\n/* -------------------------------------------------------------------------- */\n/* Lifecycle hooks (devtools#683) */\n/* -------------------------------------------------------------------------- */\n\ntype HookType = 'beforeAll' | 'afterAll' | 'beforeEach' | 'afterEach';\n\ninterface HookEntry {\n /** Suite path at the time of registration ([] = module scope). */\n suitePath: string[];\n type: HookType;\n fn: () => void | Promise<void>;\n}\n\nconst _hooks: HookEntry[] = [];\n\nfunction _registerHook(type: HookType, fn: () => void | Promise<void>): void {\n _hooks.push({ suitePath: [..._suiteStack], type, fn });\n}\n\n/**\n * Returns hooks whose suitePath is a prefix of `testSuitePath`\n * (i.e. the hook's scope contains the test).\n */\nfunction _hooksFor(type: HookType, testSuitePath: string[]): Array<() => void | Promise<void>> {\n return _hooks\n .filter((h) => {\n if (h.type !== type) return false;\n // Hook scope must be a prefix of the test's suite path\n if (h.suitePath.length > testSuitePath.length) return false;\n for (let i = 0; i < h.suitePath.length; i++) {\n if (h.suitePath[i] !== testSuitePath[i]) return false;\n }\n return true;\n })\n .map((h) => h.fn);\n}\n\n/** Runs an array of hook functions in order, awaiting each. */\nasync function _runHooks(fns: Array<() => void | Promise<void>>): Promise<Error | null> {\n for (const fn of fns) {\n try {\n await fn();\n } catch (e) {\n return e instanceof Error ? e : new Error(String(e));\n }\n }\n return null;\n}\n\nfunction beforeAll(fn: () => void | Promise<void>): void {\n _registerHook('beforeAll', fn);\n}\nfunction afterAll(fn: () => void | Promise<void>): void {\n _registerHook('afterAll', fn);\n}\nfunction beforeEach(fn: () => void | Promise<void>): void {\n _registerHook('beforeEach', fn);\n}\nfunction afterEach(fn: () => void | Promise<void>): void {\n _registerHook('afterEach', fn);\n}\n\n/* -------------------------------------------------------------------------- */\n/* vi shim (devtools#683) */\n/* -------------------------------------------------------------------------- */\n\ninterface SpyCall {\n args: unknown[];\n returnValue: unknown;\n}\n\ninterface MockFn<T extends unknown[], R> {\n (...args: T): R;\n mock: { calls: SpyCall[] };\n mockImplementation(fn: (...args: T) => R): this;\n mockReturnValue(value: R): this;\n mockRestore(): void;\n}\n\ninterface SpyRecord {\n obj: Record<string, unknown>;\n method: string;\n original: unknown;\n}\n\nconst _spyRegistry: SpyRecord[] = [];\n\nfunction _createMockFn<T extends unknown[], R>(impl?: (...args: T) => R): MockFn<T, R> {\n let currentImpl: ((...args: T) => R) | undefined = impl;\n const calls: SpyCall[] = [];\n\n const mockFn = ((...args: T): R => {\n const returnValue = currentImpl ? currentImpl(...args) : (undefined as unknown as R);\n calls.push({ args, returnValue });\n return returnValue;\n }) as MockFn<T, R>;\n\n mockFn.mock = { calls };\n\n mockFn.mockImplementation = function (fn: (...args: T) => R): typeof mockFn {\n currentImpl = fn;\n return this;\n };\n\n mockFn.mockReturnValue = function (value: R): typeof mockFn {\n currentImpl = () => value;\n return this;\n };\n\n // No-op restore for standalone fn (only spyOn-created fns have a real restore)\n mockFn.mockRestore = (): void => {};\n\n return mockFn;\n}\n\nconst vi = {\n /** Creates a spy on `obj[method]`, replacing it with a mock function. */\n spyOn<T extends Record<string, unknown>, K extends keyof T>(\n obj: T,\n method: K,\n ): MockFn<unknown[], unknown> {\n const original = obj[method];\n const spy = _createMockFn<unknown[], unknown>(\n typeof original === 'function' ? (original as (...args: unknown[]) => unknown) : undefined,\n );\n\n spy.mockRestore = (): void => {\n obj[method] = original as T[K];\n };\n\n _spyRegistry.push({ obj: obj as Record<string, unknown>, method: method as string, original });\n obj[method] = spy as unknown as T[K];\n return spy;\n },\n\n /** Creates a standalone mock function, optionally wrapping `impl`. */\n fn<T extends unknown[], R>(impl?: (...args: T) => R): MockFn<T, R> {\n return _createMockFn(impl);\n },\n\n /** Restores all spies created via `vi.spyOn` to their original values. */\n restoreAllMocks(): void {\n for (const { obj, method, original } of _spyRegistry) {\n obj[method] = original;\n }\n _spyRegistry.length = 0;\n },\n};\n\n/* -------------------------------------------------------------------------- */\n/* Runtime entry point */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Runtime globals object — exported for direct use in unit tests so that\n * test factories can reference runtime's own `it`/`expect`/`beforeAll`/etc.\n * without depending on `globalThis` injection.\n *\n * In a real WebView bundle these are accessed via globals installed by\n * `runTestModule`; in Node tests, import from here directly.\n */\nexport const runtimeGlobals = {\n describe,\n it,\n test,\n expect,\n beforeAll,\n afterAll,\n beforeEach,\n afterEach,\n vi,\n} as const;\n\n/**\n * Installs describe/it/test/expect/afterAll/afterEach/beforeAll/beforeEach/vi\n * as globals, invokes `moduleFactory` to register the user's tests, then\n * executes them and returns a RunReport.\n *\n * This function is exported as `__testBundle.runTestModule` by the IIFE wrapper\n * that bundle.ts generates. The Node-side rpc.ts calls it via `Runtime.evaluate`.\n *\n * @param moduleFactory - A zero-argument function that contains the user's\n * top-level test code (describe/it/test calls). The bundler wraps the entire\n * test module so that its top-level statements become the body of this factory.\n * @param opts - Test-only overrides (see {@link RunTestModuleOptions}). Never\n * passed by the generated bundle (`rpc.ts#buildRunTestsExpression` calls\n * `runTestModule(__userFactory)` with exactly one argument) — this second\n * parameter exists so unit tests can inject a fake sleep and assert the\n * THROTTLED-retry timing without real delays.\n */\nexport async function runTestModule(\n moduleFactory?: () => void | Promise<void>,\n opts?: RunTestModuleOptions,\n): Promise<RunReport> {\n const sleep = opts?.sleep ?? DEFAULT_SLEEP;\n // Reset state for re-entrant calls within the same page context.\n _pendingTests.length = 0;\n _suiteStack.length = 0;\n _hooks.length = 0;\n _spyRegistry.length = 0;\n\n // Install globals that user test code expects.\n type G = typeof globalThis & {\n describe: typeof describe;\n it: typeof it;\n test: typeof test;\n expect: typeof expect;\n beforeAll: typeof beforeAll;\n afterAll: typeof afterAll;\n beforeEach: typeof beforeEach;\n afterEach: typeof afterEach;\n vi: typeof vi;\n };\n const g = globalThis as G;\n g.describe = describe;\n g.it = it;\n g.test = test;\n g.expect = expect;\n g.beforeAll = beforeAll;\n g.afterAll = afterAll;\n g.beforeEach = beforeEach;\n g.afterEach = afterEach;\n g.vi = vi;\n\n // Run the factory (which registers describe/it/test blocks via globals).\n if (moduleFactory) {\n await moduleFactory();\n }\n\n const wallStart = Date.now();\n const startedAt = new Date(wallStart).toISOString();\n const results: TestResult[] = [];\n\n // Determine unique suite scopes from registered tests, in discovery order.\n // We need to fire beforeAll/afterAll once per scope (grouped by suitePath).\n //\n // Simplified model: we run beforeAll hooks before the first test in a scope\n // and afterAll hooks after the last test in a scope. Scope identity is the\n // entire suitePath string (e.g. \"Suite A > Suite B\").\n //\n // For module-scope hooks (suitePath=[]), they wrap the entire test run.\n\n // Group tests by their suite key to track beforeAll/afterAll per scope.\n // We keep a Set of scopes for which beforeAll has been fired.\n const firedBeforeAll = new Set<string>();\n // Map from scope key → last index in _pendingTests that belongs to that scope.\n const lastIndexForScope = new Map<string, number>();\n for (let i = 0; i < _pendingTests.length; i++) {\n const key = _pendingTests[i].suitePath.join('\\0');\n lastIndexForScope.set(key, i);\n // Also compute for parent scopes (module scope = '')\n const path = _pendingTests[i].suitePath;\n for (let depth = 0; depth < path.length; depth++) {\n const parentKey = path.slice(0, depth).join('\\0');\n const cur = lastIndexForScope.get(parentKey) ?? -1;\n if (i > cur) lastIndexForScope.set(parentKey, i);\n }\n }\n // Module scope key\n const MODULE_KEY = '';\n if (!lastIndexForScope.has(MODULE_KEY) && _pendingTests.length > 0) {\n lastIndexForScope.set(MODULE_KEY, _pendingTests.length - 1);\n }\n\n // Fire module-scope beforeAll before any tests\n if (_pendingTests.length > 0) {\n const baFns = _hooksFor('beforeAll', []);\n const baErr = await _runHooks(baFns);\n firedBeforeAll.add(MODULE_KEY);\n if (baErr) {\n // If module beforeAll fails, mark all tests as failed.\n for (const pending of _pendingTests) {\n const fullName = [...pending.suitePath, pending.name].join(' > ');\n results.push({\n name: fullName,\n status: 'fail',\n duration: 0,\n error: `beforeAll failed: ${baErr.message}`,\n });\n }\n const duration = Date.now() - wallStart;\n const passed = results.filter((r) => r.status === 'pass').length;\n const failed = results.filter((r) => r.status === 'fail').length;\n const skipped = results.filter((r) => r.status === 'skip').length;\n // Still run module afterAll for cleanup (e.g. flushCapture)\n const aaFns = _hooksFor('afterAll', []);\n await _runHooks(aaFns);\n return { startedAt, duration, passed, failed, skipped, tests: results };\n }\n }\n\n // devtools#767 --pace: read the page-global __AIT_PACE_MS__ (injected by\n // relay-factory.ts the same way __AIT_CELL__ is, via cell.ts#injectGlobals)\n // ONCE per run. Absent/0 (the default) means zero behavior change — the\n // wait below becomes a no-op sleep(0) that resolves on the next microtask\n // tick, same as today's unpaced loop for every existing caller.\n const paceMs = (() => {\n const raw = (globalThis as { __AIT_PACE_MS__?: unknown }).__AIT_PACE_MS__;\n return typeof raw === 'number' && raw > 0 ? raw : 0;\n })();\n let ranFirstTest = false;\n\n for (let i = 0; i < _pendingTests.length; i++) {\n const pending = _pendingTests[i];\n const fullName = [...pending.suitePath, pending.name].join(' > ');\n\n if (pending.skip) {\n results.push({ name: fullName, status: 'skip', duration: 0 });\n continue;\n }\n\n // --pace inter-test spacing: wait BEFORE every test after the first one\n // that actually runs (skipped tests above never reach here). Mirrors the\n // permission preflight's \"no wait before the first probe\" pacing model\n // (cell.ts#buildPermissionPreflightExpression).\n if (paceMs > 0 && ranFirstTest) {\n await sleep(paceMs);\n }\n ranFirstTest = true;\n\n // Fire suite-scoped beforeAll for any new scopes entered by this test\n for (let depth = 1; depth <= pending.suitePath.length; depth++) {\n const scopePath = pending.suitePath.slice(0, depth);\n const scopeKey = scopePath.join('\\0');\n if (!firedBeforeAll.has(scopeKey)) {\n // Only hooks registered exactly at this scope (not broader/narrower)\n const scopedFns = _hooks\n .filter((h) => h.type === 'beforeAll' && h.suitePath.join('\\0') === scopeKey)\n .map((h) => h.fn);\n const baErr = await _runHooks(scopedFns);\n firedBeforeAll.add(scopeKey);\n if (baErr) {\n // Mark remaining tests in this scope as failed\n results.push({\n name: fullName,\n status: 'fail',\n duration: 0,\n error: `beforeAll failed: ${baErr.message}`,\n });\n }\n }\n }\n\n // beforeEach\n const beFns = _hooksFor('beforeEach', pending.suitePath);\n const beErr = await _runHooks(beFns);\n\n const tStart = Date.now();\n let testErr: string | undefined;\n let inPageSkip: InPageSkipSentinel | undefined;\n let throttleRetries = 0;\n\n if (beErr) {\n testErr = `beforeEach failed: ${beErr.message}`;\n } else {\n // THROTTLED-aware retry (devtools#767): only the test BODY is retried —\n // beforeEach (above) and afterEach (below) each run exactly once\n // regardless of how many times the body is attempted. This keeps any\n // capture-emitting hook (e.g. sdk-example's flushCapture) firing exactly\n // once per test, so a retried body can never duplicate a capture record\n // (see relay-worker.ts's harvesting model — it's a passive listener over\n // the whole run, not a per-attempt flush/drain, so this invariant is what\n // keeps a retry from polluting the capture stream).\n for (let attempt = 0; ; attempt++) {\n try {\n await pending.fn(_makeTestContext(fullName));\n testErr = undefined;\n break;\n } catch (e) {\n if (e instanceof InPageSkipSentinel) {\n inPageSkip = e;\n break;\n }\n testErr = stringifyThrown(e);\n if (isThrottledError(e) && attempt < TEST_MAX_RETRIES) {\n throttleRetries += 1;\n await sleep(TEST_RETRY_BACKOFF_MS[attempt]);\n continue;\n }\n break;\n }\n }\n }\n\n // afterEach — always run even if test failed or was skipped mid-body.\n const aeFns = _hooksFor('afterEach', pending.suitePath);\n const aeErr = await _runHooks(aeFns);\n if (aeErr && !testErr && !inPageSkip) testErr = `afterEach failed: ${aeErr.message}`;\n\n if (inPageSkip) {\n // ctx.skip() unwound the body — record as skipped (not pass/fail), same\n // as the static it.skip path. The note (if any) rides on TestResult.note.\n results.push({\n name: fullName,\n status: 'skip',\n duration: Date.now() - tStart,\n ...(inPageSkip.note !== undefined ? { note: inPageSkip.note } : {}),\n });\n } else if (testErr !== undefined) {\n results.push({\n name: fullName,\n status: 'fail',\n duration: Date.now() - tStart,\n error: testErr,\n ...(throttleRetries > 0 ? { throttleRetries } : {}),\n });\n } else {\n results.push({\n name: fullName,\n status: 'pass',\n duration: Date.now() - tStart,\n ...(throttleRetries > 0 ? { throttleRetries } : {}),\n });\n }\n\n // Fire suite-scoped afterAll when this is the last test in each scope\n for (let depth = pending.suitePath.length; depth >= 1; depth--) {\n const scopePath = pending.suitePath.slice(0, depth);\n const scopeKey = scopePath.join('\\0');\n const lastIdx = lastIndexForScope.get(scopeKey) ?? -1;\n if (lastIdx === i) {\n const scopedFns = _hooks\n .filter((h) => h.type === 'afterAll' && h.suitePath.join('\\0') === scopeKey)\n .map((h) => h.fn);\n await _runHooks(scopedFns);\n }\n }\n }\n\n // Fire module-scope afterAll after all tests — critical for flushCapture\n const moduleAfterAllFns = _hooks\n .filter((h) => h.type === 'afterAll' && h.suitePath.length === 0)\n .map((h) => h.fn);\n await _runHooks(moduleAfterAllFns);\n\n const duration = Date.now() - wallStart;\n const passed = results.filter((r) => r.status === 'pass').length;\n const failed = results.filter((r) => r.status === 'fail').length;\n const skipped = results.filter((r) => r.status === 'skip').length;\n\n return { startedAt, duration, passed, failed, skipped, tests: results };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2EA,MAAM,wBAAwB,CAAC,KAAO,IAAM;;AAG5C,MAAM,mBAAmB,sBAAsB;;AAG/C,MAAM,iBAAiB,OACrB,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;;;;;;;;;;;;;;AA8BnD,SAAS,gBAAgB,GAAoB;AAC3C,KAAI,aAAa,MAAO,QAAO,EAAE;AACjC,KAAI,OAAO,MAAM,YAAY,MAAM,MAAM;EACvC,MAAM,MAAM;AACZ,MAAI,OAAO,IAAI,YAAY,SAAU,QAAO,IAAI;;AAElD,QAAO,OAAO,EAAE;;;;;;;;;AAclB,MAAM,mBAAmB;;AAkBzB,SAAS,aAAa,GAAoC;AACxD,QACE,OAAO,MAAM,YACb,MAAM,QACL,EAA8B,sBAAsB,QACrD,OAAQ,EAAoC,oBAAoB;;;;;;;;;;;AAgBpE,SAAS,QAAQ,MAAkC;CACjD,MAAM,OAAQ,KAA2B,QAAQ,OAAO,KAAK;CAC7D,MAAM,WAAW;AACjB,QAAO;GACJ,mBAAmB;EACpB,gBAAgB,OAAO,KAAK;EAC5B,gBAAgB,QAA0B;AACxC,O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OAAO,CAAC;EAIpB,QAHvB,QAAQ,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC;EAGZ,SAF9B,QAAQ,QAAQ,MAAM,EAAE,WAAW,OAAO,CAAC;EAEJ,OAAO;EAAS"}
@@ -1,4 +1,4 @@
1
- import { t as RunReport } from "../runtime-DfHHZms2.js";
1
+ import { t as RunReport } from "../runtime-BiigOuvb.js";
2
2
  import { File, TaskEventPack, TaskResultPack } from "@vitest/runner";
3
3
 
4
4
  //#region src/test-runner/task-graph.d.ts
@@ -0,0 +1,59 @@
1
+ //#region src/test-runner/throttle.ts
2
+ /**
3
+ * Shared `APP_BRIDGE_THROTTLED` detection (devtools#767).
4
+ *
5
+ * 2026-07-10 real-device observation: the Toss app native side added a
6
+ * per-method rate limit to the 2.x bridge — calling the SAME bridge method
7
+ * twice within a short window rejects the second call immediately with a
8
+ * 2.x native envelope (`{name, code, userInfo, moduleName, __isError}`) whose
9
+ * `code` is `'APP_BRIDGE_THROTTLED'` and whose `message` reads
10
+ * `"Too many app bridge calls from <method>."`. The 3.x bridge path is
11
+ * unaffected (devtools#767 issue body, sdk-example#284 2026-07-10 comment).
12
+ *
13
+ * This module is the SINGLE source of the detection predicate. Today's only
14
+ * consumer is `runtime.ts` (in-page, per-test retry loop) — a plain static
15
+ * import; esbuild inlines this file into the same IIFE bundle (same
16
+ * mechanism as `bridge-stub.ts`, see `bundle.ts#getPageSideModulePath`). It
17
+ * is exported from this standalone, dependency-free module (rather than
18
+ * defined inline in `runtime.ts`) so a Node-side consumer could import the
19
+ * exact same predicate in future if whole-FILE throttle-aware retry is ever
20
+ * added on top of the per-test retry `runtime.ts` already performs — no such
21
+ * Node-side caller exists yet (whole-file retry today only triggers on an
22
+ * `injectAndRunBundle`-level timeout/exception, a distinct failure mode from
23
+ * a `RunReport` that completed normally but contains a THROTTLED-failed
24
+ * test — see `relay-worker.ts`'s `EVALUATE_TIMEOUT_MARKER` gate).
25
+ *
26
+ * Browser-compatible, dependency-free (no Node APIs) — safe to import from
27
+ * either side of the CDP boundary, mirroring `runtime.ts`'s own constraint.
28
+ */
29
+ /** The native error code the Toss app bridge returns when rate-limited. */
30
+ const THROTTLED_ERROR_CODE = "APP_BRIDGE_THROTTLED";
31
+ /** The message substring the native envelope carries when rate-limited. */
32
+ const THROTTLED_MESSAGE_SUBSTRING = "Too many app bridge calls";
33
+ /**
34
+ * True when `err` looks like a native `APP_BRIDGE_THROTTLED` rejection —
35
+ * either the 2.x native envelope's `code` field equals
36
+ * {@link THROTTLED_ERROR_CODE}, or the error's message contains
37
+ * {@link THROTTLED_MESSAGE_SUBSTRING}. Either signal alone is sufficient: the
38
+ * `code` field is the precise native signal, but a caller may only have a
39
+ * stringified message (e.g. `Error#message` after the native envelope was
40
+ * flattened) — checking both keeps detection robust across both shapes.
41
+ *
42
+ * Accepts `unknown` because callers may pass a caught page-side exception
43
+ * (whose shape is not statically known), a `TestResult.error` string, or a
44
+ * `FileResult` error string — never throws.
45
+ */
46
+ function isThrottledError(err) {
47
+ if (err === null || err === void 0) return false;
48
+ if (typeof err === "string") return err.includes(THROTTLED_MESSAGE_SUBSTRING);
49
+ if (typeof err === "object") {
50
+ const rec = err;
51
+ if (rec.code === "APP_BRIDGE_THROTTLED") return true;
52
+ if (typeof rec.message === "string" && rec.message.includes("Too many app bridge calls")) return true;
53
+ }
54
+ return false;
55
+ }
56
+ //#endregion
57
+ export { THROTTLED_MESSAGE_SUBSTRING as n, isThrottledError as r, THROTTLED_ERROR_CODE as t };
58
+
59
+ //# sourceMappingURL=throttle-DKKzX1qC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throttle-DKKzX1qC.js","names":[],"sources":["../src/test-runner/throttle.ts"],"sourcesContent":["/**\n * Shared `APP_BRIDGE_THROTTLED` detection (devtools#767).\n *\n * 2026-07-10 real-device observation: the Toss app native side added a\n * per-method rate limit to the 2.x bridge — calling the SAME bridge method\n * twice within a short window rejects the second call immediately with a\n * 2.x native envelope (`{name, code, userInfo, moduleName, __isError}`) whose\n * `code` is `'APP_BRIDGE_THROTTLED'` and whose `message` reads\n * `\"Too many app bridge calls from <method>.\"`. The 3.x bridge path is\n * unaffected (devtools#767 issue body, sdk-example#284 2026-07-10 comment).\n *\n * This module is the SINGLE source of the detection predicate. Today's only\n * consumer is `runtime.ts` (in-page, per-test retry loop) — a plain static\n * import; esbuild inlines this file into the same IIFE bundle (same\n * mechanism as `bridge-stub.ts`, see `bundle.ts#getPageSideModulePath`). It\n * is exported from this standalone, dependency-free module (rather than\n * defined inline in `runtime.ts`) so a Node-side consumer could import the\n * exact same predicate in future if whole-FILE throttle-aware retry is ever\n * added on top of the per-test retry `runtime.ts` already performs — no such\n * Node-side caller exists yet (whole-file retry today only triggers on an\n * `injectAndRunBundle`-level timeout/exception, a distinct failure mode from\n * a `RunReport` that completed normally but contains a THROTTLED-failed\n * test — see `relay-worker.ts`'s `EVALUATE_TIMEOUT_MARKER` gate).\n *\n * Browser-compatible, dependency-free (no Node APIs) — safe to import from\n * either side of the CDP boundary, mirroring `runtime.ts`'s own constraint.\n */\n\n/** The native error code the Toss app bridge returns when rate-limited. */\nexport const THROTTLED_ERROR_CODE = 'APP_BRIDGE_THROTTLED';\n\n/** The message substring the native envelope carries when rate-limited. */\nexport const THROTTLED_MESSAGE_SUBSTRING = 'Too many app bridge calls';\n\n/**\n * True when `err` looks like a native `APP_BRIDGE_THROTTLED` rejection —\n * either the 2.x native envelope's `code` field equals\n * {@link THROTTLED_ERROR_CODE}, or the error's message contains\n * {@link THROTTLED_MESSAGE_SUBSTRING}. Either signal alone is sufficient: the\n * `code` field is the precise native signal, but a caller may only have a\n * stringified message (e.g. `Error#message` after the native envelope was\n * flattened) — checking both keeps detection robust across both shapes.\n *\n * Accepts `unknown` because callers may pass a caught page-side exception\n * (whose shape is not statically known), a `TestResult.error` string, or a\n * `FileResult` error string — never throws.\n */\nexport function isThrottledError(err: unknown): boolean {\n if (err === null || err === undefined) return false;\n\n if (typeof err === 'string') {\n return err.includes(THROTTLED_MESSAGE_SUBSTRING);\n }\n\n if (typeof err === 'object') {\n const rec = err as { code?: unknown; message?: unknown };\n if (rec.code === THROTTLED_ERROR_CODE) return true;\n if (typeof rec.message === 'string' && rec.message.includes(THROTTLED_MESSAGE_SUBSTRING)) {\n return true;\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,uBAAuB;;AAGpC,MAAa,8BAA8B;;;;;;;;;;;;;;AAe3C,SAAgB,iBAAiB,KAAuB;AACtD,KAAI,QAAQ,QAAQ,QAAQ,KAAA,EAAW,QAAO;AAE9C,KAAI,OAAO,QAAQ,SACjB,QAAO,IAAI,SAAS,4BAA4B;AAGlD,KAAI,OAAO,QAAQ,UAAU;EAC3B,MAAM,MAAM;AACZ,MAAI,IAAI,SAAA,uBAA+B,QAAO;AAC9C,MAAI,OAAO,IAAI,YAAY,YAAY,IAAI,QAAQ,SAAA,4BAAqC,CACtF,QAAO;;AAIX,QAAO"}
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { a as isValidRelayAuthSecret, i as generateTotp } from "./totp-WY6l0ysP.js";
3
+ export { generateTotp, isValidRelayAuthSecret };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ait-co/devtools",
3
- "version": "0.1.137",
3
+ "version": "0.1.139",
4
4
  "description": "Development tools for Apps in Toss mini-apps — mock SDK, floating devtools panel, and universal bundler plugin",
5
5
  "type": "module",
6
6
  "engines": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"bundle-BKqyhEK9.d.ts","names":[],"sources":["../src/test-runner/bundle.ts"],"mappings":";;AAqEA;;;;;AAmBA;;;;;AA8XA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAjZiB,aAAA;;;;;;;EAOf,cAAA;;;;;EAKA,UAAA;AAAA;;;;;UAOe,YAAA;EACf,IAAA;EACA,QAAA;AAAA;;;;;;;;;;;;;;;iBA4XoB,cAAA,CAAe,OAAA,UAAiB,IAAA,GAAO,aAAA,GAAgB,OAAA,CAAQ,YAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"cell-BIdSQb9T.js","names":[],"sources":["../src/test-runner/cell.ts"],"sourcesContent":["/**\n * Cell injection utility for the `devtools-test` CLI (issue #684 §4.1).\n *\n * Injects arbitrary globals into the page via `Runtime.evaluate` BEFORE the\n * first test bundle is injected. The injected values are session-global — one\n * call covers all files in the run.\n *\n * The primary use-case is injecting `__AIT_CELL__` (sdkLine/platform) so\n * sdk-example's `aitCapture.ts` picks up the correct test-axis values instead\n * of falling back to `'2.x'`/`'mock'`.\n *\n * devtools does NOT know the shape of `__AIT_CELL__` — it only provides the\n * general injection mechanism. The caller (CLI or MCP auto-attach path) is\n * responsible for constructing the cell object.\n *\n * SECRET-HANDLING: cell values (sdkLine/platform) are not secrets and may be\n * logged at the caller's discretion. This module does NOT log them itself.\n *\n * Node-only. react-free. CdpConnection only.\n */\n\n/**\n * `__AIT_PERMS__` key → SDK function name whose `.getPermission()` is probed\n * (devtools#739). This is the exact contract sdk-example#265 consumes — do\n * not rename keys without a coordinated sdk-example update.\n *\n * Each SDK function is reached via `window.__sdk` — the SAME page-global\n * bridge `src/in-app/auto.ts` installs for `call_sdk`/`__sdkCall` (see\n * `src/test-runner/bundle.ts`'s `sdkRedirectPlugin`, which redirects bundled\n * `@apps-in-toss/web-framework` imports to this same object at runtime). The\n * test-runner bundle owns no independent SDK import — `window.__sdk` is a\n * page global regardless of whether a bundle has been injected yet, so this\n * preflight runs standalone via `injectGlobals`'s `Runtime.evaluate`\n * mechanism BEFORE the first bundle, rather than being prepended into\n * `rpc.ts#buildRunTestsExpression`. (Design choice documented in PR #739 —\n * bundle-prepend was the fallback plan if the SDK were only reachable from\n * inside bundle scope, which reality ruled out.)\n */\nconst PERMISSION_PROBE_MAP: Record<string, string> = {\n clipboardRead: 'getClipboardText',\n clipboardWrite: 'setClipboardText',\n album: 'fetchAlbumPhotos',\n camera: 'openCamera',\n contacts: 'fetchContacts',\n location: 'getCurrentLocation',\n};\n\n/** Non-fatal bound for the permission preflight `Runtime.evaluate` round-trip. */\nexport const PERMISSION_PREFLIGHT_TIMEOUT_MS = 10_000;\n\n/**\n * Builds the `Runtime.evaluate` expression for the permission-state preflight\n * (devtools#739). Evaluated ONCE per relay session, before the first test\n * bundle is injected (see `relay-worker.ts#runTestFilesOverRelay`).\n *\n * For each entry in {@link PERMISSION_PROBE_MAP}, probes\n * `window.__sdk.<fn>.getPermission()` — a NON-blocking query (never\n * `openPermissionDialog`/`requestPermission`, which open native UI) — and\n * assigns the resolved `'allowed'|'denied'|'notDetermined'` status to\n * `globalThis.__AIT_PERMS__[<key>]`. A probe that is absent, throws, or\n * rejects resolves to `'unavailable'` — this expression never throws to its\n * caller, and a single slow/broken permission must not fail the others (each\n * probe is awaited independently, not short-circuited).\n *\n * Tests (sdk-example#265) read `globalThis.__AIT_PERMS__` to branch\n * deterministically per permission state instead of blanket outcome-branching.\n *\n * Returns a JSON-serialised string (the same double-serialisation pattern\n * `rpc.ts#buildRunTestsExpression` uses) rather than relying on CDP\n * `returnByValue` structural fidelity for a plain object across the Chii\n * relay — the Node side re-parses via `JSON.parse`.\n *\n * Pure function — no I/O, no CDP call. Callers pass the returned string to\n * `Runtime.evaluate`.\n */\nexport function buildPermissionPreflightExpression(): string {\n const probeEntries = Object.entries(PERMISSION_PROBE_MAP)\n .map(\n ([key, fnName]) =>\n ` result[${JSON.stringify(key)}] = await probe(${JSON.stringify(fnName)});`,\n )\n .join('\\n');\n\n return (\n `(async () => {` +\n ` const probe = async (fnName) => {` +\n ` try {` +\n ` const fn = globalThis.__sdk && globalThis.__sdk[fnName];` +\n ` if (!fn || typeof fn.getPermission !== 'function') return 'unavailable';` +\n ` const status = await fn.getPermission();` +\n ` if (status === 'allowed' || status === 'denied' || status === 'notDetermined') return status;` +\n ` return 'unavailable';` +\n ` } catch (e) {` +\n ` return 'unavailable';` +\n ` }` +\n ` };` +\n ` const result = {};` +\n `${probeEntries}\\n` +\n ` globalThis.__AIT_PERMS__ = result;` +\n ` return JSON.stringify(result);` +\n `})()`\n );\n}\n\n/**\n * Runs the permission-state preflight (devtools#739) via `Runtime.evaluate`\n * and returns the collected `__AIT_PERMS__` map, or `undefined` when the\n * preflight itself failed or timed out.\n *\n * NON-FATAL by design: any failure (CDP exception, timeout, page-side throw)\n * is caught here, logged as ONE stderr line, and swallowed — the whole test\n * run must proceed even when the preflight cannot complete (e.g. `window.__sdk`\n * not yet installed, or a page navigation mid-attach). Callers that want the\n * result for report provenance (`RelayRunReport.preflight`) get `undefined`\n * in that case, which downstream code treats the same as \"not run\".\n *\n * SECRET-HANDLING: no relay/wss/secret values are read or logged; only\n * permission-state strings cross this boundary.\n *\n * @param conn - The live CDP connection (relay-attached page).\n * @param timeoutMs - Round-trip bound. Defaults to {@link PERMISSION_PREFLIGHT_TIMEOUT_MS}.\n */\nexport async function runPermissionPreflight(\n conn: CdpConnection,\n timeoutMs = PERMISSION_PREFLIGHT_TIMEOUT_MS,\n): Promise<Record<string, string> | undefined> {\n const TIMEOUT_SENTINEL = Symbol('permission-preflight-timeout');\n const timeoutPromise = new Promise<typeof TIMEOUT_SENTINEL>((resolve) =>\n setTimeout(() => resolve(TIMEOUT_SENTINEL), timeoutMs),\n );\n\n try {\n const evalPromise = conn.send('Runtime.evaluate', {\n expression: buildPermissionPreflightExpression(),\n returnByValue: true,\n awaitPromise: true,\n });\n\n const raceResult = await Promise.race([\n evalPromise.then((v) => ({ tag: 'eval' as const, v })),\n timeoutPromise.then(() => ({ tag: 'timeout' as const })),\n ]);\n\n if (raceResult.tag === 'timeout') {\n process.stderr.write(\n `test-runner: permission preflight timed out after ${timeoutMs}ms — proceeding with __AIT_PERMS__ unset\\n`,\n );\n return undefined;\n }\n\n if (raceResult.v.exceptionDetails) {\n process.stderr.write(\n 'test-runner: permission preflight threw — proceeding with __AIT_PERMS__ unset\\n',\n );\n return undefined;\n }\n\n const rawValue = raceResult.v.result.value;\n if (typeof rawValue !== 'string') return undefined;\n const parsed: unknown = JSON.parse(rawValue);\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n return parsed as Record<string, string>;\n } catch (e) {\n process.stderr.write(\n `test-runner: permission preflight failed (${\n e instanceof Error ? e.message : String(e)\n }) — proceeding with __AIT_PERMS__ unset\\n`,\n );\n return undefined;\n }\n}\n\nimport { buildIndicatorExpression } from '../mcp/attach-orchestrator.js';\nimport type { CdpConnection } from '../mcp/cdp-connection.js';\n\n/**\n * Injects each key of `globals` into `globalThis` in the page via a single\n * `Runtime.evaluate` call. Must be called BEFORE the first `bundleTestFile`\n * inject — the cell is session-global and applies to all subsequent files.\n *\n * Throws if the CDP evaluate returns an exception.\n *\n * @param conn - The live CDP connection (relay-attached page).\n * @param globals - Plain-JSON-serialisable key→value map to assign onto `globalThis`.\n */\nexport async function injectGlobals(\n conn: CdpConnection,\n globals: Record<string, unknown>,\n): Promise<void> {\n // JSON.stringify is safe here: globals values are plain data (sdkLine/platform\n // strings or simple objects). If a value is not JSON-serialisable this throws\n // at call time, which surfaces the error early and clearly.\n const expr = `(() => { Object.assign(globalThis, ${JSON.stringify(globals)}); return true; })()`;\n const result = await conn.send('Runtime.evaluate', { expression: expr, returnByValue: true });\n if (result.exceptionDetails) {\n const msg =\n result.exceptionDetails.exception?.description ??\n result.exceptionDetails.text ??\n 'unknown error';\n throw new Error(`injectGlobals: Runtime.evaluate threw: ${msg}`);\n }\n}\n\n/**\n * Injects (or updates) the \"Debugger Connected\"/\"Debugger Disconnected\"\n * on-phone indicator via `Runtime.evaluate` (#730).\n *\n * Uses the same CDP mechanism as {@link injectGlobals} — a single\n * `Runtime.evaluate` round-trip with the expression built by\n * {@link buildIndicatorExpression}. The indicator is a LIVE badge rendered at\n * the bottom-left of the page (position:fixed, safe-area-aware): the badge's\n * controller is idempotent, so calling this again (e.g. right before\n * `close()` with `{ state: 'disconnected' }`) UPDATES the existing badge in\n * place instead of injecting a duplicate.\n *\n * **Isolation**: unlike {@link injectGlobals}, this function NEVER throws to\n * its caller. Injection failure (e.g. page detached during inject, CSS not\n * supported) is swallowed and logged as `console.debug` — the badge is\n * informational UI and must never block attach success or test execution.\n * This is the same fire-and-forget spirit as the in-page console mount in\n * `src/in-app/attach.ts`.\n *\n * Call this ONLY on the manual debug paths (start_attach MCP, devtools-test\n * CLI). Do NOT call on the `run_tests` auto-attach path — the badge\n * would contaminate screenshots, measure_safe_area probes, and DOM snapshots\n * taken during automated measurement runs.\n *\n * SECRET-HANDLING: the injected expression contains no secrets, relay URLs,\n * wss addresses, or TOTP codes — it is pure DOM UI text + enum state built by\n * {@link buildIndicatorExpression}.\n *\n * @param conn - The live CDP connection (relay-attached page).\n * @param opts - Optional overrides forwarded to {@link buildIndicatorExpression}.\n */\nexport async function injectDebugIndicator(\n conn: CdpConnection,\n opts?: { label?: string; disconnectedLabel?: string; state?: 'attached' | 'disconnected' },\n): Promise<void> {\n try {\n await conn.send('Runtime.evaluate', {\n expression: buildIndicatorExpression(opts),\n returnByValue: true,\n });\n } catch (err) {\n // Badge injection is informational UI — swallow and log; never propagate.\n console.debug('[@ait-co/devtools] debug indicator inject skipped:', err);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,uBAA+C;CACnD,eAAe;CACf,gBAAgB;CAChB,OAAO;CACP,QAAQ;CACR,UAAU;CACV,UAAU;CACX;;AAGD,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;AA2B/C,SAAgB,qCAA6C;AAQ3D,QACE,8bARmB,OAAO,QAAQ,qBAAqB,CACtD,KACE,CAAC,KAAK,YACL,cAAc,KAAK,UAAU,IAAI,CAAC,kBAAkB,KAAK,UAAU,OAAO,CAAC,IAC9E,CACA,KAAK,KAAK,CAgBK;;;;;;;;;;;;;;;;;;;;AAyBpB,eAAsB,uBACpB,MACA,YAAY,iCACiC;CAC7C,MAAM,mBA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AK;GAC1C,eAAe;GAChB,CAAC;UACK,KAAK;AAEZ,UAAQ,MAAM,sDAAsD,IAAI"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"cell-D1y4shoV.js","names":[],"sources":["../src/test-runner/cell.ts"],"sourcesContent":["/**\n * Cell injection utility for the `devtools-test` CLI (issue #684 §4.1).\n *\n * Injects arbitrary globals into the page via `Runtime.evaluate` BEFORE the\n * first test bundle is injected. The injected values are session-global — one\n * call covers all files in the run.\n *\n * The primary use-case is injecting `__AIT_CELL__` (sdkLine/platform) so\n * sdk-example's `aitCapture.ts` picks up the correct test-axis values instead\n * of falling back to `'2.x'`/`'mock'`.\n *\n * devtools does NOT know the shape of `__AIT_CELL__` — it only provides the\n * general injection mechanism. The caller (CLI or MCP auto-attach path) is\n * responsible for constructing the cell object.\n *\n * SECRET-HANDLING: cell values (sdkLine/platform) are not secrets and may be\n * logged at the caller's discretion. This module does NOT log them itself.\n *\n * Node-only. react-free. CdpConnection only.\n */\n\n/**\n * `__AIT_PERMS__` key → SDK function name whose `.getPermission()` is probed\n * (devtools#739). This is the exact contract sdk-example#265 consumes — do\n * not rename keys without a coordinated sdk-example update.\n *\n * Each SDK function is reached via `window.__sdk` — the SAME page-global\n * bridge `src/in-app/auto.ts` installs for `call_sdk`/`__sdkCall` (see\n * `src/test-runner/bundle.ts`'s `sdkRedirectPlugin`, which redirects bundled\n * `@apps-in-toss/web-framework` imports to this same object at runtime). The\n * test-runner bundle owns no independent SDK import — `window.__sdk` is a\n * page global regardless of whether a bundle has been injected yet, so this\n * preflight runs standalone via `injectGlobals`'s `Runtime.evaluate`\n * mechanism BEFORE the first bundle, rather than being prepended into\n * `rpc.ts#buildRunTestsExpression`. (Design choice documented in PR #739 —\n * bundle-prepend was the fallback plan if the SDK were only reachable from\n * inside bundle scope, which reality ruled out.)\n */\nconst PERMISSION_PROBE_MAP: Record<string, string> = {\n clipboardRead: 'getClipboardText',\n clipboardWrite: 'setClipboardText',\n album: 'fetchAlbumPhotos',\n camera: 'openCamera',\n contacts: 'fetchContacts',\n location: 'getCurrentLocation',\n};\n\n/** Non-fatal bound for the permission preflight `Runtime.evaluate` round-trip. */\nexport const PERMISSION_PREFLIGHT_TIMEOUT_MS = 10_000;\n\n/**\n * Builds the `Runtime.evaluate` expression for the permission-state preflight\n * (devtools#739). Evaluated ONCE per relay session, before the first test\n * bundle is injected (see `relay-worker.ts#runTestFilesOverRelay`).\n *\n * For each entry in {@link PERMISSION_PROBE_MAP}, probes\n * `window.__sdk.<fn>.getPermission()` — a NON-blocking query (never\n * `openPermissionDialog`/`requestPermission`, which open native UI) — and\n * assigns the resolved `'allowed'|'denied'|'notDetermined'` status to\n * `globalThis.__AIT_PERMS__[<key>]`. A probe that is absent, throws, or\n * rejects resolves to `'unavailable'` — this expression never throws to its\n * caller, and a single slow/broken permission must not fail the others (each\n * probe is awaited independently, not short-circuited).\n *\n * Tests (sdk-example#265) read `globalThis.__AIT_PERMS__` to branch\n * deterministically per permission state instead of blanket outcome-branching.\n *\n * Returns a JSON-serialised string (the same double-serialisation pattern\n * `rpc.ts#buildRunTestsExpression` uses) rather than relying on CDP\n * `returnByValue` structural fidelity for a plain object across the Chii\n * relay — the Node side re-parses via `JSON.parse`.\n *\n * Pure function — no I/O, no CDP call. Callers pass the returned string to\n * `Runtime.evaluate`.\n */\nexport function buildPermissionPreflightExpression(): string {\n const probeEntries = Object.entries(PERMISSION_PROBE_MAP)\n .map(\n ([key, fnName]) =>\n ` result[${JSON.stringify(key)}] = await probe(${JSON.stringify(fnName)});`,\n )\n .join('\\n');\n\n return (\n `(async () => {` +\n ` const probe = async (fnName) => {` +\n ` try {` +\n ` const fn = globalThis.__sdk && globalThis.__sdk[fnName];` +\n ` if (!fn || typeof fn.getPermission !== 'function') return 'unavailable';` +\n ` const status = await fn.getPermission();` +\n ` if (status === 'allowed' || status === 'denied' || status === 'notDetermined') return status;` +\n ` return 'unavailable';` +\n ` } catch (e) {` +\n ` return 'unavailable';` +\n ` }` +\n ` };` +\n ` const result = {};` +\n `${probeEntries}\\n` +\n ` globalThis.__AIT_PERMS__ = result;` +\n ` return JSON.stringify(result);` +\n `})()`\n );\n}\n\n/**\n * Runs the permission-state preflight (devtools#739) via `Runtime.evaluate`\n * and returns the collected `__AIT_PERMS__` map, or `undefined` when the\n * preflight itself failed or timed out.\n *\n * NON-FATAL by design: any failure (CDP exception, timeout, page-side throw)\n * is caught here, logged as ONE stderr line, and swallowed — the whole test\n * run must proceed even when the preflight cannot complete (e.g. `window.__sdk`\n * not yet installed, or a page navigation mid-attach). Callers that want the\n * result for report provenance (`RelayRunReport.preflight`) get `undefined`\n * in that case, which downstream code treats the same as \"not run\".\n *\n * SECRET-HANDLING: no relay/wss/secret values are read or logged; only\n * permission-state strings cross this boundary.\n *\n * @param conn - The live CDP connection (relay-attached page).\n * @param timeoutMs - Round-trip bound. Defaults to {@link PERMISSION_PREFLIGHT_TIMEOUT_MS}.\n */\nexport async function runPermissionPreflight(\n conn: CdpConnection,\n timeoutMs = PERMISSION_PREFLIGHT_TIMEOUT_MS,\n): Promise<Record<string, string> | undefined> {\n const TIMEOUT_SENTINEL = Symbol('permission-preflight-timeout');\n const timeoutPromise = new Promise<typeof TIMEOUT_SENTINEL>((resolve) =>\n setTimeout(() => resolve(TIMEOUT_SENTINEL), timeoutMs),\n );\n\n try {\n const evalPromise = conn.send('Runtime.evaluate', {\n expression: buildPermissionPreflightExpression(),\n returnByValue: true,\n awaitPromise: true,\n });\n\n const raceResult = await Promise.race([\n evalPromise.then((v) => ({ tag: 'eval' as const, v })),\n timeoutPromise.then(() => ({ tag: 'timeout' as const })),\n ]);\n\n if (raceResult.tag === 'timeout') {\n process.stderr.write(\n `test-runner: permission preflight timed out after ${timeoutMs}ms — proceeding with __AIT_PERMS__ unset\\n`,\n );\n return undefined;\n }\n\n if (raceResult.v.exceptionDetails) {\n process.stderr.write(\n 'test-runner: permission preflight threw — proceeding with __AIT_PERMS__ unset\\n',\n );\n return undefined;\n }\n\n const rawValue = raceResult.v.result.value;\n if (typeof rawValue !== 'string') return undefined;\n const parsed: unknown = JSON.parse(rawValue);\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n return parsed as Record<string, string>;\n } catch (e) {\n process.stderr.write(\n `test-runner: permission preflight failed (${\n e instanceof Error ? e.message : String(e)\n }) — proceeding with __AIT_PERMS__ unset\\n`,\n );\n return undefined;\n }\n}\n\nimport { buildIndicatorExpression } from '../mcp/attach-orchestrator.js';\nimport type { CdpConnection } from '../mcp/cdp-connection.js';\n\n/**\n * Injects each key of `globals` into `globalThis` in the page via a single\n * `Runtime.evaluate` call. Must be called BEFORE the first `bundleTestFile`\n * inject — the cell is session-global and applies to all subsequent files.\n *\n * Throws if the CDP evaluate returns an exception.\n *\n * @param conn - The live CDP connection (relay-attached page).\n * @param globals - Plain-JSON-serialisable key→value map to assign onto `globalThis`.\n */\nexport async function injectGlobals(\n conn: CdpConnection,\n globals: Record<string, unknown>,\n): Promise<void> {\n // JSON.stringify is safe here: globals values are plain data (sdkLine/platform\n // strings or simple objects). If a value is not JSON-serialisable this throws\n // at call time, which surfaces the error early and clearly.\n const expr = `(() => { Object.assign(globalThis, ${JSON.stringify(globals)}); return true; })()`;\n const result = await conn.send('Runtime.evaluate', { expression: expr, returnByValue: true });\n if (result.exceptionDetails) {\n const msg =\n result.exceptionDetails.exception?.description ??\n result.exceptionDetails.text ??\n 'unknown error';\n throw new Error(`injectGlobals: Runtime.evaluate threw: ${msg}`);\n }\n}\n\n/**\n * Injects (or updates) the \"Debugger Connected\"/\"Debugger Disconnected\"\n * on-phone indicator via `Runtime.evaluate` (#730).\n *\n * Uses the same CDP mechanism as {@link injectGlobals} — a single\n * `Runtime.evaluate` round-trip with the expression built by\n * {@link buildIndicatorExpression}. The indicator is a LIVE badge rendered at\n * the bottom-left of the page (position:fixed, safe-area-aware): the badge's\n * controller is idempotent, so calling this again (e.g. right before\n * `close()` with `{ state: 'disconnected' }`) UPDATES the existing badge in\n * place instead of injecting a duplicate.\n *\n * **Isolation**: unlike {@link injectGlobals}, this function NEVER throws to\n * its caller. Injection failure (e.g. page detached during inject, CSS not\n * supported) is swallowed and logged as `console.debug` — the badge is\n * informational UI and must never block attach success or test execution.\n * This is the same fire-and-forget spirit as the in-page console mount in\n * `src/in-app/attach.ts`.\n *\n * Call this ONLY on the manual debug paths (start_attach MCP, devtools-test\n * CLI). Do NOT call on the `run_tests` auto-attach path — the badge\n * would contaminate screenshots, measure_safe_area probes, and DOM snapshots\n * taken during automated measurement runs.\n *\n * SECRET-HANDLING: the injected expression contains no secrets, relay URLs,\n * wss addresses, or TOTP codes — it is pure DOM UI text + enum state built by\n * {@link buildIndicatorExpression}.\n *\n * @param conn - The live CDP connection (relay-attached page).\n * @param opts - Optional overrides forwarded to {@link buildIndicatorExpression}.\n */\nexport async function injectDebugIndicator(\n conn: CdpConnection,\n opts?: { label?: string; disconnectedLabel?: string; state?: 'attached' | 'disconnected' },\n): Promise<void> {\n try {\n await conn.send('Runtime.evaluate', {\n expression: buildIndicatorExpression(opts),\n returnByValue: true,\n });\n } catch (err) {\n // Badge injection is informational UI — swallow and log; never propagate.\n console.debug('[@ait-co/devtools] debug indicator inject skipped:', err);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyLA,eAAsB,cACpB,MACA,SACe;CAIf,MAAM,OAAO,sCAAsC,KAAK,UAAU,QAAQ,CAAC;CAC3E,MAAM,SAAS,MAAM,KAAK,KAAK,oBAAoB;EAAE,YAAY;EAAM,eAAe;EAAM,CAAC;AAC7F,KAAI,OAAO,kBAAkB;EAC3B,MAAM,MACJ,OAAO,iBAAiB,WAAW,eACnC,OAAO,iBAAiB,QACxB;AACF,QAAM,IAAI,MAAM,0CAA0C,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCpE,eAAsB,qBACpB,MACA,MACe;AACf,KAAI;AACF,QAAM,KAAK,KAAK,oBAAoB;GAClC,YAAY,yBAAyB,KAAK;GAC1C,eAAe;GAChB,CAAC;UACK,KAAK;AAEZ,UAAQ,MAAM,sDAAsD,IAAI"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"cell-DHA578lX.js","names":[],"sources":["../src/test-runner/cell.ts"],"sourcesContent":["/**\n * Cell injection utility for the `devtools-test` CLI (issue #684 §4.1).\n *\n * Injects arbitrary globals into the page via `Runtime.evaluate` BEFORE the\n * first test bundle is injected. The injected values are session-global — one\n * call covers all files in the run.\n *\n * The primary use-case is injecting `__AIT_CELL__` (sdkLine/platform) so\n * sdk-example's `aitCapture.ts` picks up the correct test-axis values instead\n * of falling back to `'2.x'`/`'mock'`.\n *\n * devtools does NOT know the shape of `__AIT_CELL__` — it only provides the\n * general injection mechanism. The caller (CLI or MCP auto-attach path) is\n * responsible for constructing the cell object.\n *\n * SECRET-HANDLING: cell values (sdkLine/platform) are not secrets and may be\n * logged at the caller's discretion. This module does NOT log them itself.\n *\n * Node-only. react-free. CdpConnection only.\n */\n\n/**\n * `__AIT_PERMS__` key → SDK function name whose `.getPermission()` is probed\n * (devtools#739). This is the exact contract sdk-example#265 consumes — do\n * not rename keys without a coordinated sdk-example update.\n *\n * Each SDK function is reached via `window.__sdk` — the SAME page-global\n * bridge `src/in-app/auto.ts` installs for `call_sdk`/`__sdkCall` (see\n * `src/test-runner/bundle.ts`'s `sdkRedirectPlugin`, which redirects bundled\n * `@apps-in-toss/web-framework` imports to this same object at runtime). The\n * test-runner bundle owns no independent SDK import — `window.__sdk` is a\n * page global regardless of whether a bundle has been injected yet, so this\n * preflight runs standalone via `injectGlobals`'s `Runtime.evaluate`\n * mechanism BEFORE the first bundle, rather than being prepended into\n * `rpc.ts#buildRunTestsExpression`. (Design choice documented in PR #739 —\n * bundle-prepend was the fallback plan if the SDK were only reachable from\n * inside bundle scope, which reality ruled out.)\n */\nconst PERMISSION_PROBE_MAP: Record<string, string> = {\n clipboardRead: 'getClipboardText',\n clipboardWrite: 'setClipboardText',\n album: 'fetchAlbumPhotos',\n camera: 'openCamera',\n contacts: 'fetchContacts',\n location: 'getCurrentLocation',\n};\n\n/** Non-fatal bound for the permission preflight `Runtime.evaluate` round-trip. */\nexport const PERMISSION_PREFLIGHT_TIMEOUT_MS = 10_000;\n\n/**\n * Builds the `Runtime.evaluate` expression for the permission-state preflight\n * (devtools#739). Evaluated ONCE per relay session, before the first test\n * bundle is injected (see `relay-worker.ts#runTestFilesOverRelay`).\n *\n * For each entry in {@link PERMISSION_PROBE_MAP}, probes\n * `window.__sdk.<fn>.getPermission()` — a NON-blocking query (never\n * `openPermissionDialog`/`requestPermission`, which open native UI) — and\n * assigns the resolved `'allowed'|'denied'|'notDetermined'` status to\n * `globalThis.__AIT_PERMS__[<key>]`. A probe that is absent, throws, or\n * rejects resolves to `'unavailable'` — this expression never throws to its\n * caller, and a single slow/broken permission must not fail the others (each\n * probe is awaited independently, not short-circuited).\n *\n * Tests (sdk-example#265) read `globalThis.__AIT_PERMS__` to branch\n * deterministically per permission state instead of blanket outcome-branching.\n *\n * Returns a JSON-serialised string (the same double-serialisation pattern\n * `rpc.ts#buildRunTestsExpression` uses) rather than relying on CDP\n * `returnByValue` structural fidelity for a plain object across the Chii\n * relay — the Node side re-parses via `JSON.parse`.\n *\n * Pure function — no I/O, no CDP call. Callers pass the returned string to\n * `Runtime.evaluate`.\n */\nexport function buildPermissionPreflightExpression(): string {\n const probeEntries = Object.entries(PERMISSION_PROBE_MAP)\n .map(\n ([key, fnName]) =>\n ` result[${JSON.stringify(key)}] = await probe(${JSON.stringify(fnName)});`,\n )\n .join('\\n');\n\n return (\n `(async () => {` +\n ` const probe = async (fnName) => {` +\n ` try {` +\n ` const fn = globalThis.__sdk && globalThis.__sdk[fnName];` +\n ` if (!fn || typeof fn.getPermission !== 'function') return 'unavailable';` +\n ` const status = await fn.getPermission();` +\n ` if (status === 'allowed' || status === 'denied' || status === 'notDetermined') return status;` +\n ` return 'unavailable';` +\n ` } catch (e) {` +\n ` return 'unavailable';` +\n ` }` +\n ` };` +\n ` const result = {};` +\n `${probeEntries}\\n` +\n ` globalThis.__AIT_PERMS__ = result;` +\n ` return JSON.stringify(result);` +\n `})()`\n );\n}\n\n/**\n * Runs the permission-state preflight (devtools#739) via `Runtime.evaluate`\n * and returns the collected `__AIT_PERMS__` map, or `undefined` when the\n * preflight itself failed or timed out.\n *\n * NON-FATAL by design: any failure (CDP exception, timeout, page-side throw)\n * is caught here, logged as ONE stderr line, and swallowed — the whole test\n * run must proceed even when the preflight cannot complete (e.g. `window.__sdk`\n * not yet installed, or a page navigation mid-attach). Callers that want the\n * result for report provenance (`RelayRunReport.preflight`) get `undefined`\n * in that case, which downstream code treats the same as \"not run\".\n *\n * SECRET-HANDLING: no relay/wss/secret values are read or logged; only\n * permission-state strings cross this boundary.\n *\n * @param conn - The live CDP connection (relay-attached page).\n * @param timeoutMs - Round-trip bound. Defaults to {@link PERMISSION_PREFLIGHT_TIMEOUT_MS}.\n */\nexport async function runPermissionPreflight(\n conn: CdpConnection,\n timeoutMs = PERMISSION_PREFLIGHT_TIMEOUT_MS,\n): Promise<Record<string, string> | undefined> {\n const TIMEOUT_SENTINEL = Symbol('permission-preflight-timeout');\n const timeoutPromise = new Promise<typeof TIMEOUT_SENTINEL>((resolve) =>\n setTimeout(() => resolve(TIMEOUT_SENTINEL), timeoutMs),\n );\n\n try {\n const evalPromise = conn.send('Runtime.evaluate', {\n expression: buildPermissionPreflightExpression(),\n returnByValue: true,\n awaitPromise: true,\n });\n\n const raceResult = await Promise.race([\n evalPromise.then((v) => ({ tag: 'eval' as const, v })),\n timeoutPromise.then(() => ({ tag: 'timeout' as const })),\n ]);\n\n if (raceResult.tag === 'timeout') {\n process.stderr.write(\n `test-runner: permission preflight timed out after ${timeoutMs}ms — proceeding with __AIT_PERMS__ unset\\n`,\n );\n return undefined;\n }\n\n if (raceResult.v.exceptionDetails) {\n process.stderr.write(\n 'test-runner: permission preflight threw — proceeding with __AIT_PERMS__ unset\\n',\n );\n return undefined;\n }\n\n const rawValue = raceResult.v.result.value;\n if (typeof rawValue !== 'string') return undefined;\n const parsed: unknown = JSON.parse(rawValue);\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n return parsed as Record<string, string>;\n } catch (e) {\n process.stderr.write(\n `test-runner: permission preflight failed (${\n e instanceof Error ? e.message : String(e)\n }) — proceeding with __AIT_PERMS__ unset\\n`,\n );\n return undefined;\n }\n}\n\nimport { buildIndicatorExpression } from '../mcp/attach-orchestrator.js';\nimport type { CdpConnection } from '../mcp/cdp-connection.js';\n\n/**\n * Injects each key of `globals` into `globalThis` in the page via a single\n * `Runtime.evaluate` call. Must be called BEFORE the first `bundleTestFile`\n * inject — the cell is session-global and applies to all subsequent files.\n *\n * Throws if the CDP evaluate returns an exception.\n *\n * @param conn - The live CDP connection (relay-attached page).\n * @param globals - Plain-JSON-serialisable key→value map to assign onto `globalThis`.\n */\nexport async function injectGlobals(\n conn: CdpConnection,\n globals: Record<string, unknown>,\n): Promise<void> {\n // JSON.stringify is safe here: globals values are plain data (sdkLine/platform\n // strings or simple objects). If a value is not JSON-serialisable this throws\n // at call time, which surfaces the error early and clearly.\n const expr = `(() => { Object.assign(globalThis, ${JSON.stringify(globals)}); return true; })()`;\n const result = await conn.send('Runtime.evaluate', { expression: expr, returnByValue: true });\n if (result.exceptionDetails) {\n const msg =\n result.exceptionDetails.exception?.description ??\n result.exceptionDetails.text ??\n 'unknown error';\n throw new Error(`injectGlobals: Runtime.evaluate threw: ${msg}`);\n }\n}\n\n/**\n * Injects (or updates) the \"Debugger Connected\"/\"Debugger Disconnected\"\n * on-phone indicator via `Runtime.evaluate` (#730).\n *\n * Uses the same CDP mechanism as {@link injectGlobals} — a single\n * `Runtime.evaluate` round-trip with the expression built by\n * {@link buildIndicatorExpression}. The indicator is a LIVE badge rendered at\n * the bottom-left of the page (position:fixed, safe-area-aware): the badge's\n * controller is idempotent, so calling this again (e.g. right before\n * `close()` with `{ state: 'disconnected' }`) UPDATES the existing badge in\n * place instead of injecting a duplicate.\n *\n * **Isolation**: unlike {@link injectGlobals}, this function NEVER throws to\n * its caller. Injection failure (e.g. page detached during inject, CSS not\n * supported) is swallowed and logged as `console.debug` — the badge is\n * informational UI and must never block attach success or test execution.\n * This is the same fire-and-forget spirit as the in-page console mount in\n * `src/in-app/attach.ts`.\n *\n * Call this ONLY on the manual debug paths (start_attach MCP, devtools-test\n * CLI). Do NOT call on the `run_tests` auto-attach path — the badge\n * would contaminate screenshots, measure_safe_area probes, and DOM snapshots\n * taken during automated measurement runs.\n *\n * SECRET-HANDLING: the injected expression contains no secrets, relay URLs,\n * wss addresses, or TOTP codes — it is pure DOM UI text + enum state built by\n * {@link buildIndicatorExpression}.\n *\n * @param conn - The live CDP connection (relay-attached page).\n * @param opts - Optional overrides forwarded to {@link buildIndicatorExpression}.\n */\nexport async function injectDebugIndicator(\n conn: CdpConnection,\n opts?: { label?: string; disconnectedLabel?: string; state?: 'attached' | 'disconnected' },\n): Promise<void> {\n try {\n await conn.send('Runtime.evaluate', {\n expression: buildIndicatorExpression(opts),\n returnByValue: true,\n });\n } catch (err) {\n // Badge injection is informational UI — swallow and log; never propagate.\n console.debug('[@ait-co/devtools] debug indicator inject skipped:', err);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,uBAA+C;CACnD,eAAe;CACf,gBAAgB;CAChB,OAAO;CACP,QAAQ;CACR,UAAU;CACV,UAAU;CACX;;AAGD,MAAa,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;AA2B/C,SAAgB,qCAA6C;AAQ3D,QACE,8bARmB,OAAO,QAAQ,qBAAqB,CACtD,KACE,CAAC,KAAK,YACL,cAAc,KAAK,UAAU,IAAI,CAAC,kBAAkB,KAAK,UAAU,OAAO,CAAC,IAC9E,CACA,KAAK,KAAK,CAgBK;;;;;;;;;;;;;;;;;;;;AAyBpB,eAAsB,uBACpB,MACA,YAAY,iCACiC;CAC7C,MAAM,mBAAmB,OAAO,+BAA+B;CAC/D,MAAM,iBAAiB,IA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