@alwaysmeticulous/backend-recorder-workerd 2.326.0 → 2.329.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -0
- package/dist/binding-patch.js +2 -2
- package/dist/binding-patch.js.map +1 -1
- package/dist/body-capture.js +2 -2
- package/dist/body-capture.js.map +1 -1
- package/dist/capture-buffer.js +2 -2
- package/dist/capture-buffer.js.map +1 -1
- package/dist/context.js +2 -2
- package/dist/context.js.map +1 -1
- package/dist/coverage/coverage.types.d.ts +32 -0
- package/dist/coverage/replay-coverage.js +84 -0
- package/dist/coverage/replay-coverage.js.map +1 -0
- package/dist/coverage/runtime.d.ts +70 -0
- package/dist/coverage/runtime.js +138 -0
- package/dist/coverage/runtime.js.map +1 -0
- package/dist/error-capture.js +2 -2
- package/dist/error-capture.js.map +1 -1
- package/dist/fetch-patch.js +2 -2
- package/dist/fetch-patch.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/kv-capture.js +2 -2
- package/dist/kv-capture.js.map +1 -1
- package/dist/kv-patch.js +2 -2
- package/dist/kv-patch.js.map +1 -1
- package/dist/log.js +2 -2
- package/dist/log.js.map +1 -1
- package/dist/original-fetch.js +2 -2
- package/dist/original-fetch.js.map +1 -1
- package/dist/outbound-capture.js +2 -2
- package/dist/outbound-capture.js.map +1 -1
- package/dist/pages-function.js +2 -2
- package/dist/pages-function.js.map +1 -1
- package/dist/postgres/capture.js +2 -2
- package/dist/postgres/capture.js.map +1 -1
- package/dist/postgres/with-meticulous-postgres.js +2 -2
- package/dist/postgres/with-meticulous-postgres.js.map +1 -1
- package/dist/protocol.d.ts +48 -18
- package/dist/protocol.js +22 -6
- package/dist/protocol.js.map +1 -1
- package/dist/provisional-session-id.js +2 -2
- package/dist/provisional-session-id.js.map +1 -1
- package/dist/publish-session-id.js +2 -2
- package/dist/publish-session-id.js.map +1 -1
- package/dist/publish-shim-version.js +37 -0
- package/dist/publish-shim-version.js.map +1 -0
- package/dist/redact-body.js +2 -2
- package/dist/redact-body.js.map +1 -1
- package/dist/replay-fetch.js +15 -12
- package/dist/replay-fetch.js.map +1 -1
- package/dist/replay-log-tagging.js +57 -0
- package/dist/replay-log-tagging.js.map +1 -0
- package/dist/replay-sidecar-url.js +2 -2
- package/dist/replay-sidecar-url.js.map +1 -1
- package/dist/sidecar-client.js +47 -6
- package/dist/sidecar-client.js.map +1 -1
- package/dist/sidecar-transport.js +2 -2
- package/dist/sidecar-transport.js.map +1 -1
- package/dist/spans/attributes.js +2 -2
- package/dist/spans/attributes.js.map +1 -1
- package/dist/spans/readable-span.js +2 -2
- package/dist/spans/readable-span.js.map +1 -1
- package/dist/spans/serialize-span.js +2 -2
- package/dist/spans/serialize-span.js.map +1 -1
- package/dist/spans/span-builder.js +2 -2
- package/dist/spans/span-builder.js.map +1 -1
- package/dist/spans/url-redaction.js +2 -2
- package/dist/spans/url-redaction.js.map +1 -1
- package/dist/version.d.ts +14 -0
- package/dist/version.js +18 -0
- package/dist/version.js.map +1 -0
- package/dist/virtual-clock.js +2 -2
- package/dist/virtual-clock.js.map +1 -1
- package/dist/virtual-random.js +47 -20
- package/dist/virtual-random.js.map +1 -1
- package/dist/vite/index.d.ts +62 -0
- package/dist/vite/index.js +6764 -0
- package/dist/vite/index.js.map +1 -0
- package/dist/with-meticulous.js +0 -0
- package/dist/with-meticulous.js.map +1 -1
- package/package.json +5 -2
package/dist/version.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
//#region src/version.ts
|
|
2
|
+
/**
|
|
3
|
+
* npm package version of this shim, baked in at build time. Customers bump
|
|
4
|
+
* `@alwaysmeticulous/backend-recorder-workerd` independently of our cloud
|
|
5
|
+
* deploy, so this is the only way a replay can tell which bundled shim
|
|
6
|
+
* produced its After screenshots.
|
|
7
|
+
*
|
|
8
|
+
* Replaced by tsdown's `define`. The guard keeps a direct source import
|
|
9
|
+
* (vitest, typecheck) working, where no bundler has substituted the value.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0c5e2a0b-5a59-5d6c-8c0d-e032dfb10559")}catch(e){}}();
|
|
13
|
+
const WORKERD_SHIM_VERSION = "2.329.0";
|
|
14
|
+
//#endregion
|
|
15
|
+
export { WORKERD_SHIM_VERSION };
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=version.js.map
|
|
18
|
+
//# debugId=0c5e2a0b-5a59-5d6c-8c0d-e032dfb10559
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.js","sources":["../src/version.ts"],"sourcesContent":["declare const TSDOWN_WORKERD_SHIM_VERSION: string;\n\n/**\n * npm package version of this shim, baked in at build time. Customers bump\n * `@alwaysmeticulous/backend-recorder-workerd` independently of our cloud\n * deploy, so this is the only way a replay can tell which bundled shim\n * produced its After screenshots.\n *\n * Replaced by tsdown's `define`. The guard keeps a direct source import\n * (vitest, typecheck) working, where no bundler has substituted the value.\n */\nexport const WORKERD_SHIM_VERSION: string =\n typeof TSDOWN_WORKERD_SHIM_VERSION !== \"undefined\"\n ? TSDOWN_WORKERD_SHIM_VERSION\n : \"0.0.0-dev\";\n"],"names":[],"mappings":";;;;;;;;;;;;AAWA,MAAa,uBAAA","debugId":"0c5e2a0b-5a59-5d6c-8c0d-e032dfb10559"}
|
package/dist/virtual-clock.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="39c427c3-1a1e-58aa-9021-0bd113903895")}catch(e){}}();
|
|
3
3
|
import { requestCaptureContext } from "./context.js";
|
|
4
4
|
import { warnOnce } from "./log.js";
|
|
5
5
|
//#region src/virtual-clock.ts
|
|
@@ -133,4 +133,4 @@ const installVirtualClock = () => {
|
|
|
133
133
|
export { installVirtualClock };
|
|
134
134
|
|
|
135
135
|
//# sourceMappingURL=virtual-clock.js.map
|
|
136
|
-
//# debugId=
|
|
136
|
+
//# debugId=39c427c3-1a1e-58aa-9021-0bd113903895
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"virtual-clock.js","sources":["../src/virtual-clock.ts"],"sourcesContent":["import { requestCaptureContext } from \"./context\";\nimport { warnOnce } from \"./log\";\n\n/**\n * Freezes the worker's wall clock at the replayed session's last recorded activity.\n *\n * Without this, replay fails even when every outbound call is mocked correctly: credentials\n * minted during the recording (Firebase session cookies, OAuth access tokens) carry\n * short expiries, so by replay time the app rejects its own recorded credentials as stale.\n * Anchoring at the *end* of the recording means everything minted mid-session is already\n * issued but not yet expired.\n *\n * Ported from the Node backend recorder's replay clock, with two differences:\n * - the anchor comes from the request context rather than a session→anchor map, because\n * workerd's AsyncLocalStorage propagates reliably from the inbound handler. The Node\n * version needs a process-wide \"most recently seen session\" fallback, which can\n * resolve the wrong session on a replica serving several at once;\n * - the busy-wait breaker schedules on `setTimeout` — workerd has no `setImmediate`.\n *\n * Only `Date` is patched, matching the Node implementation's scope (no `Intl`, no\n * `Temporal`, no timer virtualisation).\n */\n\nconst OriginalDate = globalThis.Date;\n\n/** Real wall clock, immune to the patch below. */\nexport const nativeDateNow = (): number => OriginalDate.now();\n\n/**\n * The frozen time a replayed request with no anchor gets: 13 May 2026, World Cocktail Day.\n * A replay whose anchor is missing is already degraded, and live time there is the exact\n * non-determinism this file exists to remove — two replays of that session would render\n * different timestamps. A fixed recent date rather than the epoch, since app code routinely\n * renders or rejects an implausibly old timestamp differently. Matches the Node recorder's\n * unattributed fallback (`replay/virtual-clock.ts`).\n *\n * Exported for the tests: this is the time such a replay renders, so changing it changes\n * that replay's output.\n */\nexport const UNANCHORED_BASE_TIME_MS = OriginalDate.UTC(2026, 4, 13);\n\n// ---------------------------------------------------------------------------\n// Busy-wait loop breaker\n// ---------------------------------------------------------------------------\n\n// A frozen clock makes `while (Date.now() < deadline) {}` spin forever. Count reads that\n// return the same frozen value and, past the threshold, nudge the result forward 1ms per\n// extra read until the loop's deadline is met. The nudge is a pure function of the repeat\n// count, so a base and head replay break an identical loop identically.\nconst BREAK_AFTER = 20_000;\n\nlet lastLoopBreakBaseMs = 0;\nlet sameKeyCount = 0;\nlet loopBreakResetScheduled = false;\n\nconst applyLoopBreak = (baseMs: number): number => {\n // Reset at the end of the current macrotask. A synchronous busy-wait blocks the loop so\n // this cannot fire, letting the counter accumulate until it breaks the spin; once the\n // turn yields, the reset runs and the next turn starts fresh.\n if (!loopBreakResetScheduled) {\n loopBreakResetScheduled = true;\n try {\n setTimeout(() => {\n sameKeyCount = 0;\n loopBreakResetScheduled = false;\n }, 0);\n } catch {\n // Timers throw outside a request context in workerd. Nothing to reset in that case,\n // since clock reads there fall through to the real clock anyway.\n loopBreakResetScheduled = false;\n }\n }\n\n if (baseMs === lastLoopBreakBaseMs) {\n sameKeyCount++;\n } else {\n lastLoopBreakBaseMs = baseMs;\n sameKeyCount = 0;\n }\n return sameKeyCount <= BREAK_AFTER\n ? baseMs\n : baseMs + (sameKeyCount - BREAK_AFTER);\n};\n\n// ---------------------------------------------------------------------------\n// Resolver\n// ---------------------------------------------------------------------------\n\n/**\n * The virtual \"now\" for the request currently executing, or null when this is not a replayed\n * request — a recording, a deployed production worker, or a read outside any request (module\n * evaluation, background work) — in which case callers use the real clock. A replayed request\n * always gets a frozen time: its own anchor, or {@link UNANCHORED_BASE_TIME_MS} if it carries\n * none.\n */\nconst resolveVirtualNow = (): number | null => {\n const ctx = requestCaptureContext.getStore();\n if (ctx === undefined || ctx.mode !== \"replay\") {\n return null;\n }\n return applyLoopBreak(ctx.clockAnchorMs ?? UNANCHORED_BASE_TIME_MS);\n};\n\n// ---------------------------------------------------------------------------\n// Date shim\n// ---------------------------------------------------------------------------\n\n/**\n * What `Date.now()` reports. A standalone function rather than only a class static, so the\n * callable shim below can reuse it without referencing an unbound method — it touches no\n * `this`, so there is nothing to lose.\n */\nconst virtualDateNow = (): number => {\n const virtualNow = resolveVirtualNow();\n return virtualNow === null ? OriginalDate.now() : virtualNow;\n};\n\n// `Date` is heavily overloaded; capture args loosely and forward every explicit form\n// unchanged. Only the zero-arg form reads \"now\" and is virtualized.\nclass VirtualDateClass extends OriginalDate {\n constructor(...args: unknown[]) {\n if (args.length > 0) {\n super(...(args as ConstructorParameters<typeof OriginalDate>));\n return;\n }\n const virtualNow = resolveVirtualNow();\n if (virtualNow === null) {\n super();\n return;\n }\n super(virtualNow);\n }\n\n static override now(): number {\n return virtualDateNow();\n }\n}\n\n// Classes cannot be called without `new`, but native `Date()` can be (returning a string),\n// so wrap the class in a plain function supporting both.\nfunction VirtualDate(this: unknown, ...args: unknown[]): Date | string {\n if (!(this instanceof VirtualDate)) {\n return new VirtualDateClass().toString();\n }\n return new VirtualDateClass(...args);\n}\n\nVirtualDate.now = virtualDateNow;\nVirtualDate.parse = OriginalDate.parse;\nVirtualDate.UTC = OriginalDate.UTC;\n\n// Share the prototype so `new Date() instanceof Date` holds and every Date.prototype\n// method resolves on instances.\nObject.defineProperty(VirtualDate, \"prototype\", {\n value: VirtualDateClass.prototype,\n writable: false,\n configurable: false,\n});\n(VirtualDateClass.prototype as { constructor: unknown }).constructor =\n VirtualDate;\n\n// ---------------------------------------------------------------------------\n// Install\n// ---------------------------------------------------------------------------\n\nlet installed = false;\n\n/**\n * Replaces the global `Date` with the per-request virtual clock. Idempotent, and a no-op\n * failure: a worker that will not let its `Date` be replaced still replays, just without\n * clock virtualisation.\n *\n * Called lazily from the replay branch of the request wrapper rather than at module scope:\n * record mode and deployed production workers then pay nothing, and the package declares no\n * `sideEffects`, so a module-scope side effect could legitimately be tree-shaken away by a\n * customer's bundler.\n */\nexport const installVirtualClock = (): void => {\n if (installed) {\n return;\n }\n installed = true;\n try {\n globalThis.Date = VirtualDate as unknown as DateConstructor;\n } catch (error) {\n warnOnce(\n \"virtual-clock\",\n \"Could not install the Meticulous replay clock — recorded credentials may be treated as expired.\",\n error,\n );\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,eAAe,WAAW;;;;;;;;;;;;AAgBhC,MAAa,0BAA0B,aAAa,IAAI,MAAM,GAAG,GAAG;AAUpE,MAAM,cAAc;AAEpB,IAAI,sBAAsB;AAC1B,IAAI,eAAe;AACnB,IAAI,0BAA0B;AAE9B,MAAM,kBAAkB,WAA2B;AAIjD,KAAI,CAAC,yBAAyB;AAC5B,4BAA0B;AAC1B,MAAI;AACF,oBAAiB;AACf,mBAAe;AACf,8BAA0B;MACzB,EAAE;UACC;AAGN,6BAA0B;;;AAI9B,KAAI,WAAW,oBACb;MACK;AACL,wBAAsB;AACtB,iBAAe;;AAEjB,QAAO,gBAAgB,cACnB,SACA,UAAU,eAAe;;;;;;;;;AAc/B,MAAM,0BAAyC;CAC7C,MAAM,MAAM,sBAAsB,UAAU;AAC5C,KAAI,QAAQ,KAAA,KAAa,IAAI,SAAS,SACpC,QAAO;AAET,QAAO,eAAe,IAAI,iBAAiB,wBAAwB;;;;;;;AAYrE,MAAM,uBAA+B;CACnC,MAAM,aAAa,mBAAmB;AACtC,QAAO,eAAe,OAAO,aAAa,KAAK,GAAG;;AAKpD,IAAM,mBAAN,cAA+B,aAAa;CAC1C,YAAY,GAAG,MAAiB;AAC9B,MAAI,KAAK,SAAS,GAAG;AACnB,SAAM,GAAI,KAAoD;AAC9D;;EAEF,MAAM,aAAa,mBAAmB;AACtC,MAAI,eAAe,MAAM;AACvB,UAAO;AACP;;AAEF,QAAM,WAAW;;CAGnB,OAAgB,MAAc;AAC5B,SAAO,gBAAgB;;;AAM3B,SAAS,YAA2B,GAAG,MAAgC;AACrE,KAAI,EAAE,gBAAgB,aACpB,QAAO,IAAI,kBAAkB,CAAC,UAAU;AAE1C,QAAO,IAAI,iBAAiB,GAAG,KAAK;;AAGtC,YAAY,MAAM;AAClB,YAAY,QAAQ,aAAa;AACjC,YAAY,MAAM,aAAa;AAI/B,OAAO,eAAe,aAAa,aAAa;CAC9C,OAAO,iBAAiB;CACxB,UAAU;CACV,cAAc;CACf,CAAC;AACF,iBAAkB,UAAuC,cACvD;AAMF,IAAI,YAAY;;;;;;;;;;;AAYhB,MAAa,4BAAkC;AAC7C,KAAI,UACF;AAEF,aAAY;AACZ,KAAI;AACF,aAAW,OAAO;UACX,OAAO;AACd,WACE,iBACA,mGACA,MACD","debugId":"
|
|
1
|
+
{"version":3,"file":"virtual-clock.js","sources":["../src/virtual-clock.ts"],"sourcesContent":["import { requestCaptureContext } from \"./context\";\nimport { warnOnce } from \"./log\";\n\n/**\n * Freezes the worker's wall clock at the replayed session's last recorded activity.\n *\n * Without this, replay fails even when every outbound call is mocked correctly: credentials\n * minted during the recording (Firebase session cookies, OAuth access tokens) carry\n * short expiries, so by replay time the app rejects its own recorded credentials as stale.\n * Anchoring at the *end* of the recording means everything minted mid-session is already\n * issued but not yet expired.\n *\n * Ported from the Node backend recorder's replay clock, with two differences:\n * - the anchor comes from the request context rather than a session→anchor map, because\n * workerd's AsyncLocalStorage propagates reliably from the inbound handler. The Node\n * version needs a process-wide \"most recently seen session\" fallback, which can\n * resolve the wrong session on a replica serving several at once;\n * - the busy-wait breaker schedules on `setTimeout` — workerd has no `setImmediate`.\n *\n * Only `Date` is patched, matching the Node implementation's scope (no `Intl`, no\n * `Temporal`, no timer virtualisation).\n */\n\nconst OriginalDate = globalThis.Date;\n\n/** Real wall clock, immune to the patch below. */\nexport const nativeDateNow = (): number => OriginalDate.now();\n\n/**\n * The frozen time a replayed request with no anchor gets: 13 May 2026, World Cocktail Day.\n * A replay whose anchor is missing is already degraded, and live time there is the exact\n * non-determinism this file exists to remove — two replays of that session would render\n * different timestamps. A fixed recent date rather than the epoch, since app code routinely\n * renders or rejects an implausibly old timestamp differently. Matches the Node recorder's\n * unattributed fallback (`replay/virtual-clock.ts`).\n *\n * Exported for the tests: this is the time such a replay renders, so changing it changes\n * that replay's output.\n */\nexport const UNANCHORED_BASE_TIME_MS = OriginalDate.UTC(2026, 4, 13);\n\n// ---------------------------------------------------------------------------\n// Busy-wait loop breaker\n// ---------------------------------------------------------------------------\n\n// A frozen clock makes `while (Date.now() < deadline) {}` spin forever. Count reads that\n// return the same frozen value and, past the threshold, nudge the result forward 1ms per\n// extra read until the loop's deadline is met. The nudge is a pure function of the repeat\n// count, so a base and head replay break an identical loop identically.\nconst BREAK_AFTER = 20_000;\n\nlet lastLoopBreakBaseMs = 0;\nlet sameKeyCount = 0;\nlet loopBreakResetScheduled = false;\n\nconst applyLoopBreak = (baseMs: number): number => {\n // Reset at the end of the current macrotask. A synchronous busy-wait blocks the loop so\n // this cannot fire, letting the counter accumulate until it breaks the spin; once the\n // turn yields, the reset runs and the next turn starts fresh.\n if (!loopBreakResetScheduled) {\n loopBreakResetScheduled = true;\n try {\n setTimeout(() => {\n sameKeyCount = 0;\n loopBreakResetScheduled = false;\n }, 0);\n } catch {\n // Timers throw outside a request context in workerd. Nothing to reset in that case,\n // since clock reads there fall through to the real clock anyway.\n loopBreakResetScheduled = false;\n }\n }\n\n if (baseMs === lastLoopBreakBaseMs) {\n sameKeyCount++;\n } else {\n lastLoopBreakBaseMs = baseMs;\n sameKeyCount = 0;\n }\n return sameKeyCount <= BREAK_AFTER\n ? baseMs\n : baseMs + (sameKeyCount - BREAK_AFTER);\n};\n\n// ---------------------------------------------------------------------------\n// Resolver\n// ---------------------------------------------------------------------------\n\n/**\n * The virtual \"now\" for the request currently executing, or null when this is not a replayed\n * request — a recording, a deployed production worker, or a read outside any request (module\n * evaluation, background work) — in which case callers use the real clock. A replayed request\n * always gets a frozen time: its own anchor, or {@link UNANCHORED_BASE_TIME_MS} if it carries\n * none.\n */\nconst resolveVirtualNow = (): number | null => {\n const ctx = requestCaptureContext.getStore();\n if (ctx === undefined || ctx.mode !== \"replay\") {\n return null;\n }\n return applyLoopBreak(ctx.clockAnchorMs ?? UNANCHORED_BASE_TIME_MS);\n};\n\n// ---------------------------------------------------------------------------\n// Date shim\n// ---------------------------------------------------------------------------\n\n/**\n * What `Date.now()` reports. A standalone function rather than only a class static, so the\n * callable shim below can reuse it without referencing an unbound method — it touches no\n * `this`, so there is nothing to lose.\n */\nconst virtualDateNow = (): number => {\n const virtualNow = resolveVirtualNow();\n return virtualNow === null ? OriginalDate.now() : virtualNow;\n};\n\n// `Date` is heavily overloaded; capture args loosely and forward every explicit form\n// unchanged. Only the zero-arg form reads \"now\" and is virtualized.\nclass VirtualDateClass extends OriginalDate {\n constructor(...args: unknown[]) {\n if (args.length > 0) {\n super(...(args as ConstructorParameters<typeof OriginalDate>));\n return;\n }\n const virtualNow = resolveVirtualNow();\n if (virtualNow === null) {\n super();\n return;\n }\n super(virtualNow);\n }\n\n static override now(): number {\n return virtualDateNow();\n }\n}\n\n// Classes cannot be called without `new`, but native `Date()` can be (returning a string),\n// so wrap the class in a plain function supporting both.\nfunction VirtualDate(this: unknown, ...args: unknown[]): Date | string {\n if (!(this instanceof VirtualDate)) {\n return new VirtualDateClass().toString();\n }\n return new VirtualDateClass(...args);\n}\n\nVirtualDate.now = virtualDateNow;\nVirtualDate.parse = OriginalDate.parse;\nVirtualDate.UTC = OriginalDate.UTC;\n\n// Share the prototype so `new Date() instanceof Date` holds and every Date.prototype\n// method resolves on instances.\nObject.defineProperty(VirtualDate, \"prototype\", {\n value: VirtualDateClass.prototype,\n writable: false,\n configurable: false,\n});\n(VirtualDateClass.prototype as { constructor: unknown }).constructor =\n VirtualDate;\n\n// ---------------------------------------------------------------------------\n// Install\n// ---------------------------------------------------------------------------\n\nlet installed = false;\n\n/**\n * Replaces the global `Date` with the per-request virtual clock. Idempotent, and a no-op\n * failure: a worker that will not let its `Date` be replaced still replays, just without\n * clock virtualisation.\n *\n * Called lazily from the replay branch of the request wrapper rather than at module scope:\n * record mode and deployed production workers then pay nothing, and the package declares no\n * `sideEffects`, so a module-scope side effect could legitimately be tree-shaken away by a\n * customer's bundler.\n */\nexport const installVirtualClock = (): void => {\n if (installed) {\n return;\n }\n installed = true;\n try {\n globalThis.Date = VirtualDate as unknown as DateConstructor;\n } catch (error) {\n warnOnce(\n \"virtual-clock\",\n \"Could not install the Meticulous replay clock — recorded credentials may be treated as expired.\",\n error,\n );\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,eAAe,WAAW;;;;;;;;;;;;AAgBhC,MAAa,0BAA0B,aAAa,IAAI,MAAM,GAAG,GAAG;AAUpE,MAAM,cAAc;AAEpB,IAAI,sBAAsB;AAC1B,IAAI,eAAe;AACnB,IAAI,0BAA0B;AAE9B,MAAM,kBAAkB,WAA2B;AAIjD,KAAI,CAAC,yBAAyB;AAC5B,4BAA0B;AAC1B,MAAI;AACF,oBAAiB;AACf,mBAAe;AACf,8BAA0B;MACzB,EAAE;UACC;AAGN,6BAA0B;;;AAI9B,KAAI,WAAW,oBACb;MACK;AACL,wBAAsB;AACtB,iBAAe;;AAEjB,QAAO,gBAAgB,cACnB,SACA,UAAU,eAAe;;;;;;;;;AAc/B,MAAM,0BAAyC;CAC7C,MAAM,MAAM,sBAAsB,UAAU;AAC5C,KAAI,QAAQ,KAAA,KAAa,IAAI,SAAS,SACpC,QAAO;AAET,QAAO,eAAe,IAAI,iBAAiB,wBAAwB;;;;;;;AAYrE,MAAM,uBAA+B;CACnC,MAAM,aAAa,mBAAmB;AACtC,QAAO,eAAe,OAAO,aAAa,KAAK,GAAG;;AAKpD,IAAM,mBAAN,cAA+B,aAAa;CAC1C,YAAY,GAAG,MAAiB;AAC9B,MAAI,KAAK,SAAS,GAAG;AACnB,SAAM,GAAI,KAAoD;AAC9D;;EAEF,MAAM,aAAa,mBAAmB;AACtC,MAAI,eAAe,MAAM;AACvB,UAAO;AACP;;AAEF,QAAM,WAAW;;CAGnB,OAAgB,MAAc;AAC5B,SAAO,gBAAgB;;;AAM3B,SAAS,YAA2B,GAAG,MAAgC;AACrE,KAAI,EAAE,gBAAgB,aACpB,QAAO,IAAI,kBAAkB,CAAC,UAAU;AAE1C,QAAO,IAAI,iBAAiB,GAAG,KAAK;;AAGtC,YAAY,MAAM;AAClB,YAAY,QAAQ,aAAa;AACjC,YAAY,MAAM,aAAa;AAI/B,OAAO,eAAe,aAAa,aAAa;CAC9C,OAAO,iBAAiB;CACxB,UAAU;CACV,cAAc;CACf,CAAC;AACF,iBAAkB,UAAuC,cACvD;AAMF,IAAI,YAAY;;;;;;;;;;;AAYhB,MAAa,4BAAkC;AAC7C,KAAI,UACF;AAEF,aAAY;AACZ,KAAI;AACF,aAAW,OAAO;UACX,OAAO;AACd,WACE,iBACA,mGACA,MACD","debugId":"39c427c3-1a1e-58aa-9021-0bd113903895"}
|
package/dist/virtual-random.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0b356a44-c057-5a04-b105-f150b4aab2af")}catch(e){}}();
|
|
3
3
|
import { requestCaptureContext } from "./context.js";
|
|
4
4
|
import { warnOnce } from "./log.js";
|
|
5
5
|
//#region src/virtual-random.ts
|
|
6
6
|
/**
|
|
7
|
-
* Per-
|
|
7
|
+
* Per-request randomness virtualization for replay mode.
|
|
8
8
|
*
|
|
9
9
|
* Mocking every outbound `fetch` is not enough to make a replay deterministic: a Worker that
|
|
10
10
|
* mints an id (`crypto.randomUUID()` for a guest id, `getRandomValues` for a token) produces
|
|
@@ -21,8 +21,16 @@ import { warnOnce } from "./log.js";
|
|
|
21
21
|
* the browser replayer's `mockOutRandomNumberGeneration`, including its butterfly-effect
|
|
22
22
|
* containment: a separate sequence per call stack, seeded from a per-call-site counter, so a
|
|
23
23
|
* change in one part of the app does not shift the numbers another part gets, and a shared
|
|
24
|
-
* helper called from two places does not return the same value twice.
|
|
25
|
-
* the
|
|
24
|
+
* helper called from two places does not return the same value twice. Sequences are scoped
|
|
25
|
+
* to the inbound request, not the whole replay: two concurrent requests of the same session
|
|
26
|
+
* that race to the same call site would otherwise consume one shared stream in arrival
|
|
27
|
+
* order, and a Fisher-Yates shuffle (or any other draw) would then differ between replays.
|
|
28
|
+
* Each request starts its sequences over from the same session-scoped seed. Each call site
|
|
29
|
+
* on a request returns {@link UNATTRIBUTED_DRAW} for the first {@link FIXED_DRAWS_BEFORE_PRNG}
|
|
30
|
+
* draws and only then starts the PRNG, so a shuffle is identical across concurrent requests
|
|
31
|
+
* and a `while (Math.random() < 0.5)` loop still terminates.
|
|
32
|
+
*
|
|
33
|
+
* Two differences from the Node version, both forced by the runtime:
|
|
26
34
|
*
|
|
27
35
|
* - the session comes from the request context rather than a session resolver with a
|
|
28
36
|
* process-wide fallback, because workerd's AsyncLocalStorage propagates reliably from the
|
|
@@ -47,12 +55,28 @@ const nativeGetRandomValues = globalThis.crypto?.getRandomValues?.bind(globalThi
|
|
|
47
55
|
const FRAMES_TO_APP = 3;
|
|
48
56
|
/** How much of the stack identifies a sequence. Ten frames tells call paths apart cheaply. */
|
|
49
57
|
const STACK_FRAMES = 10;
|
|
50
|
-
/** Stack captures per
|
|
58
|
+
/** Stack captures per request, after which sequences are keyed by call site alone. */
|
|
51
59
|
const MAX_STACK_CAPTURES = 1e4;
|
|
52
|
-
/** Bounds the state a stream of unrecognised session ids can accumulate in one isolate. */
|
|
53
|
-
const MAX_TRACKED_SESSIONS = 50;
|
|
54
60
|
const UNKNOWN_CALL_SITE = "unknown";
|
|
55
|
-
|
|
61
|
+
/**
|
|
62
|
+
* What a draw returns before its call site's PRNG starts, and what unattributed draws
|
|
63
|
+
* return. Leading digits of pi, so the value is recognisably ours in a diff or a log.
|
|
64
|
+
*/
|
|
65
|
+
const UNATTRIBUTED_DRAW = .3142;
|
|
66
|
+
/**
|
|
67
|
+
* Draws at one call site on one request that return {@link UNATTRIBUTED_DRAW} before the
|
|
68
|
+
* seeded PRNG starts. Large enough that a shuffle stays constant, small enough that
|
|
69
|
+
* `while (Math.random() < 0.5)` still exits.
|
|
70
|
+
*/
|
|
71
|
+
const FIXED_DRAWS_BEFORE_PRNG = 1e3;
|
|
72
|
+
const drawUnattributed = () => UNATTRIBUTED_DRAW;
|
|
73
|
+
/**
|
|
74
|
+
* Held on the inbound request object, so two concurrent requests of one replay cannot share
|
|
75
|
+
* a generator. The seed below stays session-scoped: base and head are different replays of
|
|
76
|
+
* the same recording and must draw identical numbers, and two requests of that recording
|
|
77
|
+
* must draw the same first values rather than racing to consume one stream.
|
|
78
|
+
*/
|
|
79
|
+
const stateByRequest = /* @__PURE__ */ new WeakMap();
|
|
56
80
|
/**
|
|
57
81
|
* Alea, the same algorithm the browser replayer gets from `seedrandom`. Inlined because this
|
|
58
82
|
* package is published to npm and ships no runtime dependencies — a customer's Worker bundle
|
|
@@ -92,10 +116,10 @@ const createSeededRandom = (seed) => {
|
|
|
92
116
|
return s2;
|
|
93
117
|
};
|
|
94
118
|
};
|
|
95
|
-
const getCallStack = () => {
|
|
119
|
+
const getCallStack = (frameCount = STACK_FRAMES) => {
|
|
96
120
|
const originalLimit = Error.stackTraceLimit;
|
|
97
121
|
try {
|
|
98
|
-
Error.stackTraceLimit = FRAMES_TO_APP +
|
|
122
|
+
Error.stackTraceLimit = FRAMES_TO_APP + frameCount;
|
|
99
123
|
const stack = (/* @__PURE__ */ new Error()).stack;
|
|
100
124
|
if (stack == null) return {
|
|
101
125
|
stack: UNKNOWN_CALL_SITE,
|
|
@@ -115,22 +139,24 @@ const getCallStack = () => {
|
|
|
115
139
|
Error.stackTraceLimit = originalLimit;
|
|
116
140
|
}
|
|
117
141
|
};
|
|
118
|
-
const
|
|
142
|
+
const stillInFixedDrawPhase = (state, callSite) => {
|
|
143
|
+
const n = (state.drawsByCallSite.get(callSite) ?? 0) + 1;
|
|
144
|
+
state.drawsByCallSite.set(callSite, n);
|
|
145
|
+
return n <= FIXED_DRAWS_BEFORE_PRNG;
|
|
146
|
+
};
|
|
147
|
+
const getRequestState = () => {
|
|
119
148
|
const ctx = requestCaptureContext.getStore();
|
|
120
149
|
if (ctx === void 0 || ctx.mode !== "replay") return;
|
|
121
|
-
const existing =
|
|
150
|
+
const existing = stateByRequest.get(ctx);
|
|
122
151
|
if (existing !== void 0) return existing;
|
|
123
|
-
if (stateBySession.size >= MAX_TRACKED_SESSIONS) {
|
|
124
|
-
const oldest = stateBySession.keys().next();
|
|
125
|
-
if (!oldest.done) stateBySession.delete(oldest.value);
|
|
126
|
-
}
|
|
127
152
|
const created = {
|
|
128
153
|
frontendSessionId: ctx.frontendSessionId,
|
|
129
154
|
generatorBySequenceKey: /* @__PURE__ */ new Map(),
|
|
130
155
|
nextCallerIdByCallSite: /* @__PURE__ */ new Map(),
|
|
156
|
+
drawsByCallSite: /* @__PURE__ */ new Map(),
|
|
131
157
|
stackCaptures: 0
|
|
132
158
|
};
|
|
133
|
-
|
|
159
|
+
stateByRequest.set(ctx, created);
|
|
134
160
|
return created;
|
|
135
161
|
};
|
|
136
162
|
/**
|
|
@@ -153,8 +179,9 @@ const getSessionState = () => {
|
|
|
153
179
|
* avoid.
|
|
154
180
|
*/
|
|
155
181
|
const openSequence = () => {
|
|
156
|
-
const state =
|
|
182
|
+
const state = getRequestState();
|
|
157
183
|
if (state === void 0) return;
|
|
184
|
+
if (stillInFixedDrawPhase(state, getCallStack(1).site)) return drawUnattributed;
|
|
158
185
|
let sequenceKey = UNKNOWN_CALL_SITE;
|
|
159
186
|
let callSite = UNKNOWN_CALL_SITE;
|
|
160
187
|
if (state.stackCaptures < MAX_STACK_CAPTURES) {
|
|
@@ -192,7 +219,7 @@ const fillBytes = (view, draw) => {
|
|
|
192
219
|
};
|
|
193
220
|
let installed = false;
|
|
194
221
|
/**
|
|
195
|
-
* Replaces the worker's sources of randomness with per-
|
|
222
|
+
* Replaces the worker's sources of randomness with per-request seeded generators. Idempotent,
|
|
196
223
|
* and a no-op failure: a worker that will not let them be replaced still replays, just
|
|
197
224
|
* without randomness virtualisation.
|
|
198
225
|
*
|
|
@@ -235,4 +262,4 @@ const installVirtualRandom = () => {
|
|
|
235
262
|
export { installVirtualRandom };
|
|
236
263
|
|
|
237
264
|
//# sourceMappingURL=virtual-random.js.map
|
|
238
|
-
//# debugId=
|
|
265
|
+
//# debugId=0b356a44-c057-5a04-b105-f150b4aab2af
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"virtual-random.js","sources":["../src/virtual-random.ts"],"sourcesContent":["import { requestCaptureContext } from \"./context\";\nimport { warnOnce } from \"./log\";\n\n/**\n * Per-session randomness virtualization for replay mode.\n *\n * Mocking every outbound `fetch` is not enough to make a replay deterministic: a Worker that\n * mints an id (`crypto.randomUUID()` for a guest id, `getRandomValues` for a token) produces\n * a different value in the base replay than in the head replay, so the rendered HTML differs\n * and any screenshot showing that value diffs forever. This replaces the worker's sources of\n * randomness with seeded generators while serving a replayed request, so two replays of the\n * same recorded session render identically.\n *\n * Deliberately a *generator*, not a recording: like the browser replayer we do not capture\n * the numbers the original session produced, we produce fresh ones from a fixed seed. The\n * app still sees plausible random values, and two replays see the same ones.\n *\n * Ported from the Node backend recorder's `replay/virtual-random.ts`, which in turn mirrors\n * the browser replayer's `mockOutRandomNumberGeneration`, including its butterfly-effect\n * containment: a separate sequence per call stack, seeded from a per-call-site counter, so a\n * change in one part of the app does not shift the numbers another part gets, and a shared\n * helper called from two places does not return the same value twice. Two differences from\n * the Node version, both forced by the runtime:\n *\n * - the session comes from the request context rather than a session resolver with a\n * process-wide fallback, because workerd's AsyncLocalStorage propagates reliably from the\n * inbound handler;\n * - only the globals workerd actually has are patched — there is no `node:crypto` module to\n * mutate.\n *\n * Reads outside a replayed request — module evaluation, a recording, a deployed production\n * worker — fall through to the native generators untouched.\n */\n\nconst nativeMathRandom = Math.random.bind(Math);\nconst nativeRandomUUID = globalThis.crypto?.randomUUID?.bind(globalThis.crypto);\nconst nativeGetRandomValues = globalThis.crypto?.getRandomValues?.bind(\n globalThis.crypto,\n);\n\n/**\n * Frames of the stack that belong to this module and must be skipped to reach the app's call\n * site, counted from the `new Error()` inside {@link getCallStack}.\n *\n * Getting this wrong degrades gracefully rather than breaking: a call site that resolves to\n * one of our own frames merges sequences that should have been separate, which costs\n * butterfly-effect isolation but is still perfectly deterministic.\n */\nconst FRAMES_TO_APP = 3; // getCallStack ← openSequence ← patched global ← app\n\n/** How much of the stack identifies a sequence. Ten frames tells call paths apart cheaply. */\nconst STACK_FRAMES = 10;\n\n/** Stack captures per session, after which sequences are keyed by call site alone. */\nconst MAX_STACK_CAPTURES = 10_000;\n\n/** Bounds the state a stream of unrecognised session ids can accumulate in one isolate. */\nconst MAX_TRACKED_SESSIONS = 50;\n\nconst UNKNOWN_CALL_SITE = \"unknown\";\n\ninterface SessionRandomState {\n frontendSessionId: string;\n generatorBySequenceKey: Map<string, () => number>;\n nextCallerIdByCallSite: Map<string, number>;\n stackCaptures: number;\n}\n\nconst stateBySession = new Map<string, SessionRandomState>();\n\n// ---------------------------------------------------------------------------\n// Seeded PRNG (Alea)\n// ---------------------------------------------------------------------------\n\n/**\n * Alea, the same algorithm the browser replayer gets from `seedrandom`. Inlined because this\n * package is published to npm and ships no runtime dependencies — a customer's Worker bundle\n * should not grow for this.\n */\nexport const createSeededRandom = (seed: string): (() => number) => {\n let n = 0xefc8249d;\n const mash = (data: string): number => {\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000;\n }\n return (n >>> 0) * 2.3283064365386963e-10;\n };\n\n let s0 = mash(\" \");\n let s1 = mash(\" \");\n let s2 = mash(\" \");\n let c = 1;\n s0 -= mash(seed);\n if (s0 < 0) {\n s0 += 1;\n }\n s1 -= mash(seed);\n if (s1 < 0) {\n s1 += 1;\n }\n s2 -= mash(seed);\n if (s2 < 0) {\n s2 += 1;\n }\n\n return () => {\n const t = 2091639 * s0 + c * 2.3283064365386963e-10;\n s0 = s1;\n s1 = s2;\n c = t | 0;\n s2 = t - c;\n return s2;\n };\n};\n\n// ---------------------------------------------------------------------------\n// Sequence resolution\n// ---------------------------------------------------------------------------\n\nconst getCallStack = (): { stack: string; site: string } => {\n const originalLimit = Error.stackTraceLimit;\n try {\n Error.stackTraceLimit = FRAMES_TO_APP + STACK_FRAMES;\n const stack = new Error().stack;\n if (stack == null) {\n return { stack: UNKNOWN_CALL_SITE, site: UNKNOWN_CALL_SITE };\n }\n // Line 0 is the \"Error\" header; frame lines follow, innermost first, and the first\n // FRAMES_TO_APP of them are ours.\n const lines = stack.split(\"\\n\").slice(FRAMES_TO_APP + 1);\n return {\n stack: lines.join(\"\\n\") || UNKNOWN_CALL_SITE,\n site: lines[0] ?? UNKNOWN_CALL_SITE,\n };\n } catch {\n return { stack: UNKNOWN_CALL_SITE, site: UNKNOWN_CALL_SITE };\n } finally {\n Error.stackTraceLimit = originalLimit;\n }\n};\n\nconst getSessionState = (): SessionRandomState | undefined => {\n const ctx = requestCaptureContext.getStore();\n if (ctx === undefined || ctx.mode !== \"replay\") {\n return undefined;\n }\n const existing = stateBySession.get(ctx.frontendSessionId);\n if (existing !== undefined) {\n return existing;\n }\n if (stateBySession.size >= MAX_TRACKED_SESSIONS) {\n const oldest = stateBySession.keys().next();\n if (!oldest.done) {\n stateBySession.delete(oldest.value);\n }\n }\n const created: SessionRandomState = {\n frontendSessionId: ctx.frontendSessionId,\n generatorBySequenceKey: new Map(),\n nextCallerIdByCallSite: new Map(),\n stackCaptures: 0,\n };\n stateBySession.set(ctx.frontendSessionId, created);\n return created;\n};\n\n/**\n * The generator for the sequence the current call belongs to, or undefined outside a\n * replayed request.\n *\n * Sequences are keyed by the whole call stack, so a second call down the same path continues\n * the same sequence and gets a different value. The *seed* comes from a counter kept per\n * immediate call site, which is what keeps a shared id helper honest: two call paths through\n * the same `generateId()` share a call site, so they are seeded 0 and 1 and return different\n * ids.\n *\n * Note what the seed deliberately does NOT contain: any part of the stack. Base and head are\n * different builds of the app, so the same logical call site has a different string in each —\n * a seed built from it would change on every rebuild. The consequence, which the browser\n * replayer shares, is that two *distinct* call sites each seen for the first time both seed at\n * 0 and hand out the same first value. That is the accepted trade: an alternative that\n * separated them (say, an ordinal per call site) would shift every later site's values as soon\n * as a PR added one randomness call, which is the butterfly effect this whole scheme exists to\n * avoid.\n */\nconst openSequence = (): (() => number) | undefined => {\n const state = getSessionState();\n if (state === undefined) {\n return undefined;\n }\n\n let sequenceKey = UNKNOWN_CALL_SITE;\n let callSite = UNKNOWN_CALL_SITE;\n if (state.stackCaptures < MAX_STACK_CAPTURES) {\n state.stackCaptures++;\n const captured = getCallStack();\n sequenceKey = captured.stack;\n callSite = captured.site;\n }\n\n const existing = state.generatorBySequenceKey.get(sequenceKey);\n if (existing !== undefined) {\n return existing;\n }\n const callerId = state.nextCallerIdByCallSite.get(callSite) ?? 0;\n // Seeded from the counter only — never from the call-site or stack string itself. Those embed\n // bundle filenames and line numbers, which differ between the base build and the head build\n // of the very same code, so putting one in the seed would reseed every sequence on any\n // rebuild and bring back exactly the diffs this exists to remove. The strings are grouping\n // keys, nothing more.\n const generator = createSeededRandom(\n `meticulous-random-${state.frontendSessionId}-${callerId}`,\n );\n state.generatorBySequenceKey.set(sequenceKey, generator);\n state.nextCallerIdByCallSite.set(callSite, callerId + 1);\n return generator;\n};\n\n// ---------------------------------------------------------------------------\n// Derived primitives\n// ---------------------------------------------------------------------------\n\nconst HEX = \"0123456789abcdef\";\n/** The two bits of a v4 UUID's variant field are fixed, leaving these four values. */\nconst VARIANT = \"89ab\";\n\nconst buildUuid = (draw: () => number): string => {\n let uuid = \"\";\n for (let i = 0; i < 36; i++) {\n if (i === 8 || i === 13 || i === 18 || i === 23) {\n uuid += \"-\";\n } else if (i === 14) {\n uuid += \"4\";\n } else if (i === 19) {\n uuid += VARIANT[Math.floor(draw() * VARIANT.length)];\n } else {\n uuid += HEX[Math.floor(draw() * HEX.length)];\n }\n }\n return uuid;\n};\n\n/**\n * Fills the view's bytes rather than its elements, so every typed array — including the\n * BigInt ones, whose elements cannot be assigned a number — is handled by one path.\n */\nconst fillBytes = (view: ArrayBufferView, draw: () => number): void => {\n const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Math.floor(draw() * 256);\n }\n};\n\n// ---------------------------------------------------------------------------\n// Install\n// ---------------------------------------------------------------------------\n\nlet installed = false;\n\n/**\n * Replaces the worker's sources of randomness with per-session seeded generators. Idempotent,\n * and a no-op failure: a worker that will not let them be replaced still replays, just\n * without randomness virtualisation.\n *\n * Called lazily from the replay branch of the request wrapper rather than at module scope,\n * for the same reasons as the virtual clock: record mode and deployed production workers then\n * pay nothing, and the package declares no `sideEffects`, so a module-scope side effect could\n * legitimately be tree-shaken away by a customer's bundler.\n */\nexport const installVirtualRandom = (): void => {\n if (installed) {\n return;\n }\n installed = true;\n try {\n Math.random = () => openSequence()?.() ?? nativeMathRandom();\n\n if (globalThis.crypto != null) {\n Object.defineProperty(globalThis.crypto, \"randomUUID\", {\n value: (): string => {\n const draw = openSequence();\n if (draw !== undefined) {\n return buildUuid(draw);\n }\n return nativeRandomUUID?.() ?? buildUuid(nativeMathRandom);\n },\n configurable: true,\n writable: true,\n });\n\n Object.defineProperty(globalThis.crypto, \"getRandomValues\", {\n value: <T extends ArrayBufferView>(array: T): T => {\n const draw = openSequence();\n if (draw === undefined) {\n return nativeGetRandomValues?.(array) ?? array;\n }\n fillBytes(array, draw);\n return array;\n },\n configurable: true,\n writable: true,\n });\n }\n } catch (error) {\n warnOnce(\n \"virtual-random\",\n \"Could not install the Meticulous replay random-number generators — ids minted by the app will differ between replays.\",\n error,\n );\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,mBAAmB,KAAK,OAAO,KAAK,KAAK;AAC/C,MAAM,mBAAmB,WAAW,QAAQ,YAAY,KAAK,WAAW,OAAO;AAC/E,MAAM,wBAAwB,WAAW,QAAQ,iBAAiB,KAChE,WAAW,OACZ;;;;;;;;;AAUD,MAAM,gBAAgB;;AAGtB,MAAM,eAAe;;AAGrB,MAAM,qBAAqB;;AAG3B,MAAM,uBAAuB;AAE7B,MAAM,oBAAoB;AAS1B,MAAM,iCAAiB,IAAI,KAAiC;;;;;;AAW5D,MAAa,sBAAsB,SAAiC;CAClE,IAAI,IAAI;CACR,MAAM,QAAQ,SAAyB;AACrC,OAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,QAAK,KAAK,WAAW,EAAE;GACvB,IAAI,IAAI,qBAAsB;AAC9B,OAAI,MAAM;AACV,QAAK;AACL,QAAK;AACL,OAAI,MAAM;AACV,QAAK;AACL,QAAK,IAAI;;AAEX,UAAQ,MAAM,KAAK;;CAGrB,IAAI,KAAK,KAAK,IAAI;CAClB,IAAI,KAAK,KAAK,IAAI;CAClB,IAAI,KAAK,KAAK,IAAI;CAClB,IAAI,IAAI;AACR,OAAM,KAAK,KAAK;AAChB,KAAI,KAAK,EACP,OAAM;AAER,OAAM,KAAK,KAAK;AAChB,KA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,YAAO,oBAAoB,IAAI,UAAU,iBAAiB;;IAE5D,cAAc;IACd,UAAU;IACX,CAAC;AAEF,UAAO,eAAe,WAAW,QAAQ,mBAAmB;IAC1D,QAAmC,UAAgB;KACjD,MAAM,OAAO,cAAc;AAC3B,SAAI,SAAS,KAAA,EACX,QAAO,wBAAwB,MAAM,IAAI;AAE3C,eAAU,OAAO,KAAK;AACtB,YAAO;;IAET,cAAc;IACd,UAAU;IACX,CAAC;;UAEG,OAAO;AACd,WACE,kBACA,yHACA,MACD","debugId":"3821aa29-b3ba-551f-957d-45a05bdc02bf"}
|
|
1
|
+
{"version":3,"file":"virtual-random.js","sources":["../src/virtual-random.ts"],"sourcesContent":["import { requestCaptureContext, type RequestReplayContext } from \"./context\";\nimport { warnOnce } from \"./log\";\n\n/**\n * Per-request randomness virtualization for replay mode.\n *\n * Mocking every outbound `fetch` is not enough to make a replay deterministic: a Worker that\n * mints an id (`crypto.randomUUID()` for a guest id, `getRandomValues` for a token) produces\n * a different value in the base replay than in the head replay, so the rendered HTML differs\n * and any screenshot showing that value diffs forever. This replaces the worker's sources of\n * randomness with seeded generators while serving a replayed request, so two replays of the\n * same recorded session render identically.\n *\n * Deliberately a *generator*, not a recording: like the browser replayer we do not capture\n * the numbers the original session produced, we produce fresh ones from a fixed seed. The\n * app still sees plausible random values, and two replays see the same ones.\n *\n * Ported from the Node backend recorder's `replay/virtual-random.ts`, which in turn mirrors\n * the browser replayer's `mockOutRandomNumberGeneration`, including its butterfly-effect\n * containment: a separate sequence per call stack, seeded from a per-call-site counter, so a\n * change in one part of the app does not shift the numbers another part gets, and a shared\n * helper called from two places does not return the same value twice. Sequences are scoped\n * to the inbound request, not the whole replay: two concurrent requests of the same session\n * that race to the same call site would otherwise consume one shared stream in arrival\n * order, and a Fisher-Yates shuffle (or any other draw) would then differ between replays.\n * Each request starts its sequences over from the same session-scoped seed. Each call site\n * on a request returns {@link UNATTRIBUTED_DRAW} for the first {@link FIXED_DRAWS_BEFORE_PRNG}\n * draws and only then starts the PRNG, so a shuffle is identical across concurrent requests\n * and a `while (Math.random() < 0.5)` loop still terminates.\n *\n * Two differences from the Node version, both forced by the runtime:\n *\n * - the session comes from the request context rather than a session resolver with a\n * process-wide fallback, because workerd's AsyncLocalStorage propagates reliably from the\n * inbound handler;\n * - only the globals workerd actually has are patched — there is no `node:crypto` module to\n * mutate.\n *\n * Reads outside a replayed request — module evaluation, a recording, a deployed production\n * worker — fall through to the native generators untouched.\n */\n\nconst nativeMathRandom = Math.random.bind(Math);\nconst nativeRandomUUID = globalThis.crypto?.randomUUID?.bind(globalThis.crypto);\nconst nativeGetRandomValues = globalThis.crypto?.getRandomValues?.bind(\n globalThis.crypto,\n);\n\n/**\n * Frames of the stack that belong to this module and must be skipped to reach the app's call\n * site, counted from the `new Error()` inside {@link getCallStack}.\n *\n * Getting this wrong degrades gracefully rather than breaking: a call site that resolves to\n * one of our own frames merges sequences that should have been separate, which costs\n * butterfly-effect isolation but is still perfectly deterministic.\n */\nconst FRAMES_TO_APP = 3; // getCallStack ← openSequence ← patched global ← app\n\n/** How much of the stack identifies a sequence. Ten frames tells call paths apart cheaply. */\nconst STACK_FRAMES = 10;\n\n/** Stack captures per request, after which sequences are keyed by call site alone. */\nconst MAX_STACK_CAPTURES = 10_000;\n\nconst UNKNOWN_CALL_SITE = \"unknown\";\n\n/**\n * What a draw returns before its call site's PRNG starts, and what unattributed draws\n * return. Leading digits of pi, so the value is recognisably ours in a diff or a log.\n */\nexport const UNATTRIBUTED_DRAW = 0.3142;\n\n/**\n * Draws at one call site on one request that return {@link UNATTRIBUTED_DRAW} before the\n * seeded PRNG starts. Large enough that a shuffle stays constant, small enough that\n * `while (Math.random() < 0.5)` still exits.\n */\nexport const FIXED_DRAWS_BEFORE_PRNG = 1_000;\n\nconst drawUnattributed = (): number => UNATTRIBUTED_DRAW;\n\ninterface RequestRandomState {\n frontendSessionId: string;\n generatorBySequenceKey: Map<string, () => number>;\n nextCallerIdByCallSite: Map<string, number>;\n drawsByCallSite: Map<string, number>;\n stackCaptures: number;\n}\n\n/**\n * Held on the inbound request object, so two concurrent requests of one replay cannot share\n * a generator. The seed below stays session-scoped: base and head are different replays of\n * the same recording and must draw identical numbers, and two requests of that recording\n * must draw the same first values rather than racing to consume one stream.\n */\nconst stateByRequest = new WeakMap<RequestReplayContext, RequestRandomState>();\n\n// ---------------------------------------------------------------------------\n// Seeded PRNG (Alea)\n// ---------------------------------------------------------------------------\n\n/**\n * Alea, the same algorithm the browser replayer gets from `seedrandom`. Inlined because this\n * package is published to npm and ships no runtime dependencies — a customer's Worker bundle\n * should not grow for this.\n */\nexport const createSeededRandom = (seed: string): (() => number) => {\n let n = 0xefc8249d;\n const mash = (data: string): number => {\n for (let i = 0; i < data.length; i++) {\n n += data.charCodeAt(i);\n let h = 0.02519603282416938 * n;\n n = h >>> 0;\n h -= n;\n h *= n;\n n = h >>> 0;\n h -= n;\n n += h * 0x100000000;\n }\n return (n >>> 0) * 2.3283064365386963e-10;\n };\n\n let s0 = mash(\" \");\n let s1 = mash(\" \");\n let s2 = mash(\" \");\n let c = 1;\n s0 -= mash(seed);\n if (s0 < 0) {\n s0 += 1;\n }\n s1 -= mash(seed);\n if (s1 < 0) {\n s1 += 1;\n }\n s2 -= mash(seed);\n if (s2 < 0) {\n s2 += 1;\n }\n\n return () => {\n const t = 2091639 * s0 + c * 2.3283064365386963e-10;\n s0 = s1;\n s1 = s2;\n c = t | 0;\n s2 = t - c;\n return s2;\n };\n};\n\n// ---------------------------------------------------------------------------\n// Sequence resolution\n// ---------------------------------------------------------------------------\n\nconst getCallStack = (\n frameCount: number = STACK_FRAMES,\n): { stack: string; site: string } => {\n const originalLimit = Error.stackTraceLimit;\n try {\n Error.stackTraceLimit = FRAMES_TO_APP + frameCount;\n const stack = new Error().stack;\n if (stack == null) {\n return { stack: UNKNOWN_CALL_SITE, site: UNKNOWN_CALL_SITE };\n }\n // Line 0 is the \"Error\" header; frame lines follow, innermost first, and the first\n // FRAMES_TO_APP of them are ours.\n const lines = stack.split(\"\\n\").slice(FRAMES_TO_APP + 1);\n return {\n stack: lines.join(\"\\n\") || UNKNOWN_CALL_SITE,\n site: lines[0] ?? UNKNOWN_CALL_SITE,\n };\n } catch {\n return { stack: UNKNOWN_CALL_SITE, site: UNKNOWN_CALL_SITE };\n } finally {\n Error.stackTraceLimit = originalLimit;\n }\n};\n\nconst stillInFixedDrawPhase = (\n state: RequestRandomState,\n callSite: string,\n): boolean => {\n const n = (state.drawsByCallSite.get(callSite) ?? 0) + 1;\n state.drawsByCallSite.set(callSite, n);\n return n <= FIXED_DRAWS_BEFORE_PRNG;\n};\n\nconst getRequestState = (): RequestRandomState | undefined => {\n const ctx = requestCaptureContext.getStore();\n if (ctx === undefined || ctx.mode !== \"replay\") {\n return undefined;\n }\n const existing = stateByRequest.get(ctx);\n if (existing !== undefined) {\n return existing;\n }\n const created: RequestRandomState = {\n frontendSessionId: ctx.frontendSessionId,\n generatorBySequenceKey: new Map(),\n nextCallerIdByCallSite: new Map(),\n drawsByCallSite: new Map(),\n stackCaptures: 0,\n };\n stateByRequest.set(ctx, created);\n return created;\n};\n\n/**\n * The generator for the sequence the current call belongs to, or undefined outside a\n * replayed request.\n *\n * Sequences are keyed by the whole call stack, so a second call down the same path continues\n * the same sequence and gets a different value. The *seed* comes from a counter kept per\n * immediate call site, which is what keeps a shared id helper honest: two call paths through\n * the same `generateId()` share a call site, so they are seeded 0 and 1 and return different\n * ids.\n *\n * Note what the seed deliberately does NOT contain: any part of the stack. Base and head are\n * different builds of the app, so the same logical call site has a different string in each —\n * a seed built from it would change on every rebuild. The consequence, which the browser\n * replayer shares, is that two *distinct* call sites each seen for the first time both seed at\n * 0 and hand out the same first value. That is the accepted trade: an alternative that\n * separated them (say, an ordinal per call site) would shift every later site's values as soon\n * as a PR added one randomness call, which is the butterfly effect this whole scheme exists to\n * avoid.\n */\nconst openSequence = (): (() => number) | undefined => {\n const state = getRequestState();\n if (state === undefined) {\n return undefined;\n }\n\n // Called directly so FRAMES_TO_APP still lands on the app. A wrapper here would make\n // every Math.random share one call site and one fixed-draw budget.\n if (stillInFixedDrawPhase(state, getCallStack(1).site)) {\n return drawUnattributed;\n }\n\n let sequenceKey = UNKNOWN_CALL_SITE;\n let callSite = UNKNOWN_CALL_SITE;\n if (state.stackCaptures < MAX_STACK_CAPTURES) {\n state.stackCaptures++;\n const captured = getCallStack();\n sequenceKey = captured.stack;\n callSite = captured.site;\n }\n\n const existing = state.generatorBySequenceKey.get(sequenceKey);\n if (existing !== undefined) {\n return existing;\n }\n const callerId = state.nextCallerIdByCallSite.get(callSite) ?? 0;\n // Seeded from the counter only — never from the call-site or stack string itself. Those embed\n // bundle filenames and line numbers, which differ between the base build and the head build\n // of the very same code, so putting one in the seed would reseed every sequence on any\n // rebuild and bring back exactly the diffs this exists to remove. The strings are grouping\n // keys, nothing more.\n const generator = createSeededRandom(\n `meticulous-random-${state.frontendSessionId}-${callerId}`,\n );\n state.generatorBySequenceKey.set(sequenceKey, generator);\n state.nextCallerIdByCallSite.set(callSite, callerId + 1);\n return generator;\n};\n\n// ---------------------------------------------------------------------------\n// Derived primitives\n// ---------------------------------------------------------------------------\n\nconst HEX = \"0123456789abcdef\";\n/** The two bits of a v4 UUID's variant field are fixed, leaving these four values. */\nconst VARIANT = \"89ab\";\n\nconst buildUuid = (draw: () => number): string => {\n let uuid = \"\";\n for (let i = 0; i < 36; i++) {\n if (i === 8 || i === 13 || i === 18 || i === 23) {\n uuid += \"-\";\n } else if (i === 14) {\n uuid += \"4\";\n } else if (i === 19) {\n uuid += VARIANT[Math.floor(draw() * VARIANT.length)];\n } else {\n uuid += HEX[Math.floor(draw() * HEX.length)];\n }\n }\n return uuid;\n};\n\n/**\n * Fills the view's bytes rather than its elements, so every typed array — including the\n * BigInt ones, whose elements cannot be assigned a number — is handled by one path.\n */\nconst fillBytes = (view: ArrayBufferView, draw: () => number): void => {\n const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Math.floor(draw() * 256);\n }\n};\n\n// ---------------------------------------------------------------------------\n// Install\n// ---------------------------------------------------------------------------\n\nlet installed = false;\n\n/**\n * Replaces the worker's sources of randomness with per-request seeded generators. Idempotent,\n * and a no-op failure: a worker that will not let them be replaced still replays, just\n * without randomness virtualisation.\n *\n * Called lazily from the replay branch of the request wrapper rather than at module scope,\n * for the same reasons as the virtual clock: record mode and deployed production workers then\n * pay nothing, and the package declares no `sideEffects`, so a module-scope side effect could\n * legitimately be tree-shaken away by a customer's bundler.\n */\nexport const installVirtualRandom = (): void => {\n if (installed) {\n return;\n }\n installed = true;\n try {\n Math.random = () => openSequence()?.() ?? nativeMathRandom();\n\n if (globalThis.crypto != null) {\n Object.defineProperty(globalThis.crypto, \"randomUUID\", {\n value: (): string => {\n const draw = openSequence();\n if (draw !== undefined) {\n return buildUuid(draw);\n }\n return nativeRandomUUID?.() ?? buildUuid(nativeMathRandom);\n },\n configurable: true,\n writable: true,\n });\n\n Object.defineProperty(globalThis.crypto, \"getRandomValues\", {\n value: <T extends ArrayBufferView>(array: T): T => {\n const draw = openSequence();\n if (draw === undefined) {\n return nativeGetRandomValues?.(array) ?? array;\n }\n fillBytes(array, draw);\n return array;\n },\n configurable: true,\n writable: true,\n });\n }\n } catch (error) {\n warnOnce(\n \"virtual-random\",\n \"Could not install the Meticulous replay random-number generators — ids minted by the app will differ between replays.\",\n error,\n );\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAM,mBAAmB,KAAK,OAAO,KAAK,KAAK;AAC/C,MAAM,mBAAmB,WAAW,QAAQ,YAAY,KAAK,WAAW,OAAO;AAC/E,MAAM,wBAAwB,WAAW,QAAQ,iBAAiB,KAChE,WAAW,OACZ;;;;;;;;;AAUD,MAAM,gBAAgB;;AAGtB,MAAM,eAAe;;AAGrB,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB;;;;;AAM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,MAAM,MAAM,MAAM,MAAM,MAAM,GAC3C,SAAQ;UACC,MAAM,GACf,SAAQ;UACC,MAAM,GACf,SAAQ,QAAQ,KAAK,MAAM,MAAM,GAAG,EAAe;KAEnD,SAAQ,IAAI,KAAK,MAAM,MAAM,GAAG,GAAW;AAG/C,QAAO;;;;;;AAOT,MAAM,aAAa,MAAuB,SAA6B;CACrE,MAAM,QAAQ,IAAI,WAAW,KAAK,QAAQ,KAAK,YAAY,KAAK,WAAW;AAC3E,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,IAChC,OAAM,KAAK,KAAK,MAAM,MAAM,GAAG,IAAI;;AAQvC,IAAI,YAAY;;;;;;;;;;;AAYhB,MAAa,6BAAmC;AAC9C,KAAI,UACF;AAEF,aAAY;AACZ,KAAI;AACF,OAAK,eAAe,cAAc,IAAI,IAAI,kBAAkB;AAE5D,MAAI,WAAW,UAAU,MAAM;AAC7B,UAAO,eAAe,WAAW,QAAQ,cAAc;IACrD,aAAqB;KACnB,MAAM,OAAO,cAAc;AAC3B,SAAI,SAAS,KAAA,EACX,QAAO,UAAU,KAAK;AAExB,YAAO,oBAAoB,IAAI,UAAU,iBAAiB;;IAE5D,cAAc;IACd,UAAU;IACX,CAAC;AAEF,UAAO,eAAe,WAAW,QAAQ,mBAAmB;IAC1D,QAAmC,UAAgB;KACjD,MAAM,OAAO,cAAc;AAC3B,SAAI,SAAS,KAAA,EACX,QAAO,wBAAwB,MAAM,IAAI;AAE3C,eAAU,OAAO,KAAK;AACtB,YAAO;;IAET,cAAc;IACd,UAAU;IACX,CAAC;;UAEG,OAAO;AACd,WACE,kBACA,yHACA,MACD","debugId":"0b356a44-c057-5a04-b105-f150b4aab2af"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
//#region src/vite/index.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Vite plugin that instruments a Worker's server modules for Meticulous line
|
|
4
|
+
* coverage.
|
|
5
|
+
*
|
|
6
|
+
* Add it to the build you upload for testing — not the one you ship:
|
|
7
|
+
*
|
|
8
|
+
* import { meticulousCoverage } from "@alwaysmeticulous/backend-recorder-workerd/vite";
|
|
9
|
+
* export default defineConfig({ plugins: [meticulousCoverage()] });
|
|
10
|
+
*
|
|
11
|
+
* `enforce: "post"` is deliberate: by then Vite's esbuild pass has already
|
|
12
|
+
* stripped TypeScript and JSX, so the instrumenter only ever sees plain JS and
|
|
13
|
+
* needs no TS-aware parser. Anything it still cannot parse is passed through
|
|
14
|
+
* untouched — coverage is never worth failing a customer's build for.
|
|
15
|
+
*
|
|
16
|
+
* The cost of running last is that AST line numbers are lines in the re-printed
|
|
17
|
+
* module, not in the file the customer wrote — that pass drops comments and
|
|
18
|
+
* blank lines, which on a commented codebase shifts nearly every statement. So
|
|
19
|
+
* each marker's line is resolved back through `getCombinedSourcemap()`, the
|
|
20
|
+
* transform chain's accumulated map, which is only available here in the
|
|
21
|
+
* transform hook.
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* The slice of Vite's transform-hook context this uses. Optional because the
|
|
25
|
+
* plugin must still work when called without one — a bare `plugin.transform(...)`
|
|
26
|
+
* in a test, or a host that does not provide the hook.
|
|
27
|
+
*/
|
|
28
|
+
interface TransformContextLike {
|
|
29
|
+
getCombinedSourcemap?: () => unknown;
|
|
30
|
+
}
|
|
31
|
+
/** Structural subset of a Vite plugin — avoids depending on vite's types. */
|
|
32
|
+
interface VitePluginLike {
|
|
33
|
+
name: string;
|
|
34
|
+
enforce?: "pre" | "post";
|
|
35
|
+
configResolved?: (config: {
|
|
36
|
+
root?: string;
|
|
37
|
+
}) => void;
|
|
38
|
+
transform?: (this: TransformContextLike | undefined, code: string, id: string, options?: {
|
|
39
|
+
ssr?: boolean;
|
|
40
|
+
}) => {
|
|
41
|
+
code: string;
|
|
42
|
+
map: string;
|
|
43
|
+
} | null;
|
|
44
|
+
buildEnd?: () => void;
|
|
45
|
+
}
|
|
46
|
+
interface MeticulousCoverageOptions {
|
|
47
|
+
/**
|
|
48
|
+
* Instrument client modules too. Off by default: only the server build runs
|
|
49
|
+
* inside workerd, and it is the only side Meticulous replays.
|
|
50
|
+
*/
|
|
51
|
+
includeClient?: boolean;
|
|
52
|
+
/** Extra paths to leave uninstrumented, on top of node_modules and virtual modules. */
|
|
53
|
+
exclude?: RegExp[];
|
|
54
|
+
/** Overrides where the injected runtime import points (tests use this). */
|
|
55
|
+
runtimeModuleId?: string;
|
|
56
|
+
/** Receives a warning when the build produced no instrumentation at all. */
|
|
57
|
+
onWarning?: (message: string) => void;
|
|
58
|
+
}
|
|
59
|
+
declare const meticulousCoverage: (options?: MeticulousCoverageOptions) => VitePluginLike;
|
|
60
|
+
//#endregion
|
|
61
|
+
export { MeticulousCoverageOptions, TransformContextLike, VitePluginLike, meticulousCoverage };
|
|
62
|
+
//# sourceMappingURL=index.d.ts.map
|