@alwaysmeticulous/backend-recorder-workerd 2.333.0 → 2.334.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.
Files changed (84) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +1 -0
  3. package/dist/binding-patch.js +1 -4
  4. package/dist/binding-patch.js.map +1 -1
  5. package/dist/body-capture.js +1 -4
  6. package/dist/body-capture.js.map +1 -1
  7. package/dist/capture-buffer.js +1 -4
  8. package/dist/capture-buffer.js.map +1 -1
  9. package/dist/context.js +1 -4
  10. package/dist/context.js.map +1 -1
  11. package/dist/coverage/replay-coverage.js +1 -4
  12. package/dist/coverage/replay-coverage.js.map +1 -1
  13. package/dist/coverage/runtime.js +1 -4
  14. package/dist/coverage/runtime.js.map +1 -1
  15. package/dist/error-capture.js +1 -4
  16. package/dist/error-capture.js.map +1 -1
  17. package/dist/fetch-patch.js +1 -4
  18. package/dist/fetch-patch.js.map +1 -1
  19. package/dist/health-probe-filter.d.ts +43 -0
  20. package/dist/health-probe-filter.js +79 -0
  21. package/dist/health-probe-filter.js.map +1 -0
  22. package/dist/health-probe.d.ts +29 -0
  23. package/dist/health-probe.js +76 -0
  24. package/dist/health-probe.js.map +1 -0
  25. package/dist/index.d.ts +4 -2
  26. package/dist/index.js +4 -5
  27. package/dist/index.js.map +1 -1
  28. package/dist/kv-capture.js +1 -4
  29. package/dist/kv-capture.js.map +1 -1
  30. package/dist/kv-patch.js +1 -4
  31. package/dist/kv-patch.js.map +1 -1
  32. package/dist/log.js +1 -4
  33. package/dist/log.js.map +1 -1
  34. package/dist/original-fetch.js +1 -4
  35. package/dist/original-fetch.js.map +1 -1
  36. package/dist/outbound-capture.js +1 -4
  37. package/dist/outbound-capture.js.map +1 -1
  38. package/dist/pages-function.js +1 -4
  39. package/dist/pages-function.js.map +1 -1
  40. package/dist/postgres/capture.js +1 -4
  41. package/dist/postgres/capture.js.map +1 -1
  42. package/dist/postgres/with-meticulous-postgres.js +1 -4
  43. package/dist/postgres/with-meticulous-postgres.js.map +1 -1
  44. package/dist/protocol.js +1 -4
  45. package/dist/protocol.js.map +1 -1
  46. package/dist/provisional-session-id.js +1 -4
  47. package/dist/provisional-session-id.js.map +1 -1
  48. package/dist/publish-session-id.js +1 -4
  49. package/dist/publish-session-id.js.map +1 -1
  50. package/dist/publish-shim-version.js +1 -4
  51. package/dist/publish-shim-version.js.map +1 -1
  52. package/dist/redact-body.js +1 -4
  53. package/dist/redact-body.js.map +1 -1
  54. package/dist/replay-fetch.js +1 -4
  55. package/dist/replay-fetch.js.map +1 -1
  56. package/dist/replay-log-tagging.js +1 -4
  57. package/dist/replay-log-tagging.js.map +1 -1
  58. package/dist/replay-sidecar-url.js +1 -4
  59. package/dist/replay-sidecar-url.js.map +1 -1
  60. package/dist/sidecar-client.js +1 -4
  61. package/dist/sidecar-client.js.map +1 -1
  62. package/dist/sidecar-transport.js +1 -4
  63. package/dist/sidecar-transport.js.map +1 -1
  64. package/dist/spans/attributes.js +1 -4
  65. package/dist/spans/attributes.js.map +1 -1
  66. package/dist/spans/readable-span.js +1 -4
  67. package/dist/spans/readable-span.js.map +1 -1
  68. package/dist/spans/serialize-span.js +1 -4
  69. package/dist/spans/serialize-span.js.map +1 -1
  70. package/dist/spans/span-builder.js +1 -4
  71. package/dist/spans/span-builder.js.map +1 -1
  72. package/dist/spans/url-redaction.js +1 -4
  73. package/dist/spans/url-redaction.js.map +1 -1
  74. package/dist/version.js +2 -5
  75. package/dist/version.js.map +1 -1
  76. package/dist/virtual-clock.js +1 -4
  77. package/dist/virtual-clock.js.map +1 -1
  78. package/dist/virtual-random.js +1 -4
  79. package/dist/virtual-random.js.map +1 -1
  80. package/dist/vite/index.js +13 -14
  81. package/dist/vite/index.js.map +1 -1
  82. package/dist/with-meticulous.js +0 -0
  83. package/dist/with-meticulous.js.map +1 -1
  84. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"with-meticulous-postgres.js","sources":["../../src/postgres/with-meticulous-postgres.ts"],"sourcesContent":["import { type RequestCaptureContext, requestCaptureContext } from \"../context\";\nimport { warnOnce } from \"../log\";\nimport type { PostgresQueryEvent } from \"../protocol\";\nimport {\n isSupportedPostgresJsQuery,\n MAX_POSTGRES_JS_RESULT_SIZE,\n type PostgresJsQueryLike,\n reconstructQueryText,\n resolveRowMode,\n serializePostgresJsArgs,\n serializePostgresJsError,\n serializePostgresJsResult,\n} from \"./capture\";\n\n/**\n * Records postgres.js queries a deployed Worker makes — typically over Hyperdrive, which is the\n * only way a Worker reaches Postgres.\n *\n * There is no seam to patch automatically here. The Node recorder can hook Node's module loader\n * to patch `postgres/{src,cjs/src,cf/src}/query.js`, but a Worker is a single bundle: `postgres`\n * was inlined at build time and never passes through a loader. So the app hands us its client:\n *\n * const sql = withMeticulousPostgres(postgres(env.HYPERDRIVE.connectionString));\n *\n * Every postgres.js query funnels through one internal method, `Query.prototype.handle`, and this\n * reaches that shared prototype *through the instance* — via a throwaway query, which is free\n * because postgres.js queries are lazy and nothing executes until awaited. One call therefore also\n * covers read-replica clients and any other client in the isolate.\n *\n * Apply it **outermost** if something else also wraps the client (Sentry's\n * `instrumentPostgresJsSql`, a logging proxy): those wrappers return a proxy whose `handle` is\n * still the shared prototype's, so ordering does not change what is captured — but keeping ours\n * outermost matches the Node recorder's contract and stays correct if that ever changes.\n *\n * Record-only, deliberately. A Worker recording is replayed against the app running under Node,\n * where `@alwaysmeticulous/backend-recorder-js` serves these queries from its own mock store —\n * which is why the captured attributes here are exactly the ones that store reads. Outside a\n * recorded request this is a complete pass-through, so it is safe to leave in deployed code.\n *\n * Returns the client unchanged; the patch is on the prototype.\n */\nexport const withMeticulousPostgres = <Sql>(sql: Sql): Sql => {\n try {\n const prototype = findQueryPrototype(sql);\n if (prototype === undefined) {\n warnOnce(\n \"postgres-wrapper-unsupported\",\n \"withMeticulousPostgres could not reach postgres.js' Query prototype — queries will not be recorded.\",\n );\n return sql;\n }\n patchHandle(prototype);\n } catch (error) {\n warnOnce(\n \"postgres-wrapper-failed\",\n \"withMeticulousPostgres failed — queries will not be recorded.\",\n error,\n );\n }\n return sql;\n};\n\n// Symbol.for so a second copy of the shim (e.g. bundled twice) still detects the patch.\nconst HANDLE_PATCHED = Symbol.for(\"meticulous.workerd.postgresJsPatched\");\n\ntype HandleFn = (this: PostgresJsQueryLike) => unknown;\n\n/**\n * The `Query` prototype, reached by building a query and reading its prototype.\n *\n * `sql.unsafe` is used rather than a tagged template because it takes the text as a plain\n * argument: no interpolation, and postgres.js does not touch a connection until the query is\n * awaited, which nothing here does. The query is discarded.\n */\nconst findQueryPrototype = (sql: unknown): object | undefined => {\n const unsafe = (sql as { unsafe?: unknown } | null)?.unsafe;\n if (typeof unsafe !== \"function\") {\n return undefined;\n }\n const probe: unknown = (unsafe as (text: string) => unknown).call(\n sql,\n \"select 1\",\n );\n if (probe === null || typeof probe !== \"object\") {\n return undefined;\n }\n const prototype = Object.getPrototypeOf(probe) as object | null;\n if (prototype === null) {\n return undefined;\n }\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n return descriptor !== undefined &&\n typeof descriptor.value === \"function\" &&\n descriptor.configurable === true\n ? prototype\n : undefined;\n};\n\nconst patchHandle = (prototype: object): void => {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n const original = descriptor?.value as HandleFn | undefined;\n if (\n original === undefined ||\n (original as unknown as Record<symbol, unknown>)[HANDLE_PATCHED] === true\n ) {\n return;\n }\n\n const patched = function (this: PostgresJsQueryLike): unknown {\n // `handle` is reachable from then/catch/finally/execute, so it can be called more than once\n // for one query; postgres.js itself no-ops on the repeats via `executed`. Bail before\n // instrumenting so a query is never captured twice.\n if (this.executed || !isSupportedPostgresJsQuery(this)) {\n return original.call(this);\n }\n const ctx = requestCaptureContext.getStore();\n if (!ctx || ctx.mode !== \"record\") {\n return original.call(this);\n }\n try {\n captureQuery(ctx, this);\n } catch (error) {\n warnOnce(\n \"postgres-capture\",\n \"Failed to capture a postgres.js query.\",\n error,\n );\n }\n return original.call(this);\n };\n Object.defineProperty(patched, HANDLE_PATCHED, {\n value: true,\n enumerable: false,\n configurable: true,\n });\n Object.defineProperty(prototype, \"handle\", {\n value: patched,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n};\n\n/**\n * Wraps the query's own `resolve`/`reject` so the outcome is captured without the query being\n * awaited here — the same trick the Node instrumentation uses, and the only place a query's input\n * and its result are both visible.\n */\nconst captureQuery = (\n ctx: RequestCaptureContext,\n query: PostgresJsQueryLike,\n): void => {\n const queryText = reconstructQueryText(query.strings);\n if (queryText === undefined) {\n return;\n }\n const startTimeMs = Date.now();\n const base = {\n kind: \"postgres\" as const,\n requestId: ctx.requestId,\n ...(ctx.frontendSessionId !== undefined\n ? { frontendSessionId: ctx.frontendSessionId }\n : {}),\n traceId: ctx.traceId,\n serverSpanId: ctx.serverSpanId,\n queryText,\n params: serializePostgresJsArgs(query.args),\n rowMode: resolveRowMode(query.isRaw),\n startTimeMs,\n };\n\n const report = (outcome: Partial<PostgresQueryEvent>): void => {\n try {\n ctx.buffer.add({ ...base, ...outcome, endTimeMs: Date.now() });\n } catch (error) {\n warnOnce(\n \"postgres-report\",\n \"Failed to report a postgres.js query.\",\n error,\n );\n }\n };\n\n const originalResolve = query.resolve;\n const originalReject = query.reject;\n query.resolve = (result: unknown) => {\n // A result that cannot be serialized is simply not captured → it misses during replay and\n // errors hermetically, rather than serving something wrong.\n let json: string | undefined;\n try {\n json = serializePostgresJsResult(result);\n } catch {\n json = undefined;\n }\n report(\n json === undefined\n ? {}\n : {\n result: {\n body:\n json.length > MAX_POSTGRES_JS_RESULT_SIZE\n ? json.slice(0, MAX_POSTGRES_JS_RESULT_SIZE)\n : json,\n truncated: json.length > MAX_POSTGRES_JS_RESULT_SIZE,\n },\n },\n );\n return originalResolve.call(query, result);\n };\n query.reject = (error: unknown) => {\n let errorJson: string | undefined;\n try {\n errorJson = serializePostgresJsError(error);\n } catch {\n errorJson = undefined;\n }\n report(errorJson === undefined ? {} : { errorJson });\n return originalReject.call(query, error);\n };\n};\n"],"names":[],"mappings":"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","debugId":"bcb30e85-33e1-52b2-9e08-5dd84f66d61c"}
1
+ {"version":3,"file":"with-meticulous-postgres.js","names":[],"sources":["../../src/postgres/with-meticulous-postgres.ts"],"sourcesContent":["import { type RequestCaptureContext, requestCaptureContext } from \"../context\";\nimport { warnOnce } from \"../log\";\nimport type { PostgresQueryEvent } from \"../protocol\";\nimport {\n isSupportedPostgresJsQuery,\n MAX_POSTGRES_JS_RESULT_SIZE,\n type PostgresJsQueryLike,\n reconstructQueryText,\n resolveRowMode,\n serializePostgresJsArgs,\n serializePostgresJsError,\n serializePostgresJsResult,\n} from \"./capture\";\n\n/**\n * Records postgres.js queries a deployed Worker makes — typically over Hyperdrive, which is the\n * only way a Worker reaches Postgres.\n *\n * There is no seam to patch automatically here. The Node recorder can hook Node's module loader\n * to patch `postgres/{src,cjs/src,cf/src}/query.js`, but a Worker is a single bundle: `postgres`\n * was inlined at build time and never passes through a loader. So the app hands us its client:\n *\n * const sql = withMeticulousPostgres(postgres(env.HYPERDRIVE.connectionString));\n *\n * Every postgres.js query funnels through one internal method, `Query.prototype.handle`, and this\n * reaches that shared prototype *through the instance* — via a throwaway query, which is free\n * because postgres.js queries are lazy and nothing executes until awaited. One call therefore also\n * covers read-replica clients and any other client in the isolate.\n *\n * Apply it **outermost** if something else also wraps the client (Sentry's\n * `instrumentPostgresJsSql`, a logging proxy): those wrappers return a proxy whose `handle` is\n * still the shared prototype's, so ordering does not change what is captured — but keeping ours\n * outermost matches the Node recorder's contract and stays correct if that ever changes.\n *\n * Record-only, deliberately. A Worker recording is replayed against the app running under Node,\n * where `@alwaysmeticulous/backend-recorder-js` serves these queries from its own mock store —\n * which is why the captured attributes here are exactly the ones that store reads. Outside a\n * recorded request this is a complete pass-through, so it is safe to leave in deployed code.\n *\n * Returns the client unchanged; the patch is on the prototype.\n */\nexport const withMeticulousPostgres = <Sql>(sql: Sql): Sql => {\n try {\n const prototype = findQueryPrototype(sql);\n if (prototype === undefined) {\n warnOnce(\n \"postgres-wrapper-unsupported\",\n \"withMeticulousPostgres could not reach postgres.js' Query prototype — queries will not be recorded.\",\n );\n return sql;\n }\n patchHandle(prototype);\n } catch (error) {\n warnOnce(\n \"postgres-wrapper-failed\",\n \"withMeticulousPostgres failed — queries will not be recorded.\",\n error,\n );\n }\n return sql;\n};\n\n// Symbol.for so a second copy of the shim (e.g. bundled twice) still detects the patch.\nconst HANDLE_PATCHED = Symbol.for(\"meticulous.workerd.postgresJsPatched\");\n\ntype HandleFn = (this: PostgresJsQueryLike) => unknown;\n\n/**\n * The `Query` prototype, reached by building a query and reading its prototype.\n *\n * `sql.unsafe` is used rather than a tagged template because it takes the text as a plain\n * argument: no interpolation, and postgres.js does not touch a connection until the query is\n * awaited, which nothing here does. The query is discarded.\n */\nconst findQueryPrototype = (sql: unknown): object | undefined => {\n const unsafe = (sql as { unsafe?: unknown } | null)?.unsafe;\n if (typeof unsafe !== \"function\") {\n return undefined;\n }\n const probe: unknown = (unsafe as (text: string) => unknown).call(\n sql,\n \"select 1\",\n );\n if (probe === null || typeof probe !== \"object\") {\n return undefined;\n }\n const prototype = Object.getPrototypeOf(probe) as object | null;\n if (prototype === null) {\n return undefined;\n }\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n return descriptor !== undefined &&\n typeof descriptor.value === \"function\" &&\n descriptor.configurable === true\n ? prototype\n : undefined;\n};\n\nconst patchHandle = (prototype: object): void => {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, \"handle\");\n const original = descriptor?.value as HandleFn | undefined;\n if (\n original === undefined ||\n (original as unknown as Record<symbol, unknown>)[HANDLE_PATCHED] === true\n ) {\n return;\n }\n\n const patched = function (this: PostgresJsQueryLike): unknown {\n // `handle` is reachable from then/catch/finally/execute, so it can be called more than once\n // for one query; postgres.js itself no-ops on the repeats via `executed`. Bail before\n // instrumenting so a query is never captured twice.\n if (this.executed || !isSupportedPostgresJsQuery(this)) {\n return original.call(this);\n }\n const ctx = requestCaptureContext.getStore();\n if (!ctx || ctx.mode !== \"record\") {\n return original.call(this);\n }\n try {\n captureQuery(ctx, this);\n } catch (error) {\n warnOnce(\n \"postgres-capture\",\n \"Failed to capture a postgres.js query.\",\n error,\n );\n }\n return original.call(this);\n };\n Object.defineProperty(patched, HANDLE_PATCHED, {\n value: true,\n enumerable: false,\n configurable: true,\n });\n Object.defineProperty(prototype, \"handle\", {\n value: patched,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n};\n\n/**\n * Wraps the query's own `resolve`/`reject` so the outcome is captured without the query being\n * awaited here — the same trick the Node instrumentation uses, and the only place a query's input\n * and its result are both visible.\n */\nconst captureQuery = (\n ctx: RequestCaptureContext,\n query: PostgresJsQueryLike,\n): void => {\n const queryText = reconstructQueryText(query.strings);\n if (queryText === undefined) {\n return;\n }\n const startTimeMs = Date.now();\n const base = {\n kind: \"postgres\" as const,\n requestId: ctx.requestId,\n ...(ctx.frontendSessionId !== undefined\n ? { frontendSessionId: ctx.frontendSessionId }\n : {}),\n traceId: ctx.traceId,\n serverSpanId: ctx.serverSpanId,\n queryText,\n params: serializePostgresJsArgs(query.args),\n rowMode: resolveRowMode(query.isRaw),\n startTimeMs,\n };\n\n const report = (outcome: Partial<PostgresQueryEvent>): void => {\n try {\n ctx.buffer.add({ ...base, ...outcome, endTimeMs: Date.now() });\n } catch (error) {\n warnOnce(\n \"postgres-report\",\n \"Failed to report a postgres.js query.\",\n error,\n );\n }\n };\n\n const originalResolve = query.resolve;\n const originalReject = query.reject;\n query.resolve = (result: unknown) => {\n // A result that cannot be serialized is simply not captured → it misses during replay and\n // errors hermetically, rather than serving something wrong.\n let json: string | undefined;\n try {\n json = serializePostgresJsResult(result);\n } catch {\n json = undefined;\n }\n report(\n json === undefined\n ? {}\n : {\n result: {\n body:\n json.length > MAX_POSTGRES_JS_RESULT_SIZE\n ? json.slice(0, MAX_POSTGRES_JS_RESULT_SIZE)\n : json,\n truncated: json.length > MAX_POSTGRES_JS_RESULT_SIZE,\n },\n },\n );\n return originalResolve.call(query, result);\n };\n query.reject = (error: unknown) => {\n let errorJson: string | undefined;\n try {\n errorJson = serializePostgresJsError(error);\n } catch {\n errorJson = undefined;\n }\n report(errorJson === undefined ? {} : { errorJson });\n return originalReject.call(query, error);\n };\n};\n"],"mappings":"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"}
package/dist/protocol.js CHANGED
@@ -4,8 +4,6 @@
4
4
  * recorder sidecar. The sidecar imports these types (type-only), so this file
5
5
  * is the single source of truth for the shape of capture events.
6
6
  */
7
-
8
- !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]="7851ef28-53e0-596f-80dc-a26f37790747")}catch(e){}}();
9
7
  const SIDECAR_PROTOCOL_VERSION = "2";
10
8
  /** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */
11
9
  const SIDECAR_PROTOCOL_VERSION_HEADER = "x-meticulous-sidecar-protocol-version";
@@ -90,5 +88,4 @@ const CAPTURED_HEADERS = ["content-type", FRONTEND_SESSION_ID_HEADER];
90
88
  //#endregion
91
89
  export { CAPTURED_HEADERS, FRONTEND_SESSION_ID_HEADER, METICULOUS_PASSTHROUGH_HEADER, REPLAY_ID_HEADER, REPLAY_SIDECAR_URL_HEADER, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_COVERAGE_PATH, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH, VIRTUAL_TIME_HEADER, WORKERD_SHIM_VERSION_HEADER, parseVirtualTimeMs };
92
90
 
93
- //# sourceMappingURL=protocol.js.map
94
- //# debugId=7851ef28-53e0-596f-80dc-a26f37790747
91
+ //# sourceMappingURL=protocol.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.js","sources":["../src/protocol.ts"],"sourcesContent":["/**\n * Wire protocol between the in-worker shim and the Meticulous backend\n * recorder sidecar. The sidecar imports these types (type-only), so this file\n * is the single source of truth for the shape of capture events.\n */\n\nexport const SIDECAR_PROTOCOL_VERSION = \"2\";\n\n/** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */\nexport const SIDECAR_PROTOCOL_VERSION_HEADER =\n \"x-meticulous-sidecar-protocol-version\";\n\n/**\n * Header the Meticulous frontend recorder stamps on requests made by the app\n * under recording; its value ties backend spans to the frontend session.\n */\nexport const FRONTEND_SESSION_ID_HEADER = \"x-meticulous-session-id\";\n\n/** Header identifying one replay attempt of a recorded frontend session. */\nexport const REPLAY_ID_HEADER = \"x-meticulous-replay-id\";\n\n/**\n * Elapsed virtual time (ms from replay start) of the triggering frontend\n * request. Injected by the replay runner on app-url requests during backend\n * testing; the sidecar uses it to pick the closest recorded burst when several\n * candidates share a loosened match key.\n */\nexport const VIRTUAL_TIME_HEADER = \"x-meticulous-virtual-time\";\n\n/**\n * Parses {@link VIRTUAL_TIME_HEADER}. `0` is a valid start-of-session time;\n * anything non-finite or negative is ignored so a garbage header cannot skew matching.\n */\nexport const parseVirtualTimeMs = (\n value: string | null | undefined,\n): number | undefined => {\n if (value == null || value === \"\") {\n return undefined;\n }\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n return undefined;\n }\n return parsed;\n};\n\n/**\n * A request carrying this header set to `\"true\"` is never served from the recording and\n * never fails on a miss — it goes to the real network. Use it for a call that must be live\n * during replay (a health probe, telemetry, a resource the recording cannot cover).\n *\n * Same convention and value as the frontend network stubbing and the Node backend recorder\n * (`METICULOUS_PASSTHROUGH_HEADER` in `@alwaysmeticulous/backend-recorder-js`); the value\n * must stay in step with both.\n */\nexport const METICULOUS_PASSTHROUGH_HEADER = \"meticulous-passthrough\";\n\nexport const SIDECAR_EVENTS_PATH = \"/v1/events\";\n\n/**\n * Replay routes. A sidecar started in record mode answers 404 on both. Replay is hermetic,\n * so an unanswered outbound-fetch lookup fails the app's call rather than letting it reach\n * the real service — the same as any other failure to stub.\n */\nexport const SIDECAR_REPLAY_SESSION_PATH = \"/v1/replay/session\";\nexport const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = \"/v1/replay/outbound-fetch\";\n\n/**\n * Line-coverage reporting. Additive: an older sidecar answers 404, which the\n * shim treats as \"coverage not collected here\" and stops reporting for the life\n * of the isolate. Deliberately NOT guarded by a\n * {@link SIDECAR_PROTOCOL_VERSION} bump — that check is exact equality, so a\n * bump would stop every already-built customer image from mocking at all.\n */\nexport const SIDECAR_REPLAY_COVERAGE_PATH = \"/v1/replay/coverage\";\n\n/**\n * Header carrying the replay sidecar's origin, injected by the Meticulous replay runner\n * on requests to the app under test. Workerd cannot see container environment variables,\n * so an inbound header is the only way per-replay config can reach the shim.\n *\n * The shim validates the value before using it and only honours a loopback /\n * `host.docker.internal` / private-network `http:` origin — see `replay-sidecar-url.ts`.\n */\nexport const REPLAY_SIDECAR_URL_HEADER =\n \"x-meticulous-backend-replay-sidecar-url\";\n\n/**\n * Header the in-worker shim stamps on every app response (record and replay)\n * carrying the shim's npm package version. The replay runner reads this from\n * Puppeteer — workerd cannot see container env, and the execute pod cannot\n * reach the in-pod sidecar, so a response header is the only channel that\n * reports which bundled shim produced a replay's After screenshots.\n */\nexport const WORKERD_SHIM_VERSION_HEADER = \"x-meticulous-workerd-shim-version\";\n\n/**\n * The only headers persisted on capture events. Everything else — notably\n * authorization, cookie/set-cookie, and API-key headers — is dropped at\n * capture time, before it ever leaves the worker.\n *\n * The Node backend recorder persists the same two, plus the inbound request's\n * `Cookie` header on SERVER spans (`recorded-request-headers.ts`). This list\n * has not followed it there, so a workerd recording of an authenticated server\n * render still carries no session cookie.\n */\nexport const CAPTURED_HEADERS = [\n \"content-type\",\n FRONTEND_SESSION_ID_HEADER,\n] as const;\n\nexport interface CapturedBody {\n /** UTF-8 decoded body, truncated to the capture cap. */\n body: string;\n /** True when the body exceeded the capture cap or the read was cut short. */\n truncated: boolean;\n}\n\n/**\n * The fields every capture event carries to say which request, session and trace it belongs to.\n */\ninterface CorrelatedEvent {\n /** Correlates outbound events to the inbound request being handled. */\n requestId: string;\n /** Value of {@link FRONTEND_SESSION_ID_HEADER} on the inbound request, if any. */\n frontendSessionId?: string;\n /**\n * Trace the request's spans belong to (32 hex chars), minted by the shim.\n *\n * The shim mints it, rather than the sidecar deriving it from {@link requestId}, so span\n * assembly is stateless: a sidecar that had to remember `requestId → traceId` would give a\n * request's SERVER span and its CLIENT children different traces whenever it lost that memory\n * between two batches — which, for a Worker-hosted sidecar, an eviction can do at any moment.\n *\n * Optional so a sidecar keeps working against a shim that predates this field, in which case\n * it falls back to its own per-`requestId` map.\n */\n traceId?: string;\n /**\n * Span id of the request's SERVER span (16 hex chars), also minted by the shim: it is the\n * parent of every CLIENT span the request produced, and the inbound event's own span id.\n */\n serverSpanId?: string;\n}\n\ninterface BaseRequestEvent extends CorrelatedEvent {\n method: string;\n /** Full URL including query string. */\n url: string;\n /** Lower-cased header name → values. */\n requestHeaders: Record<string, string[]>;\n responseHeaders?: Record<string, string[]>;\n statusCode?: number;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the request failed before a response was produced. */\n error?: string;\n}\n\n/**\n * The worker's own inbound request (becomes a SERVER span). Bodies are not\n * captured, matching the Node backend recorder's SERVER-span contract.\n */\nexport interface InboundRequestEvent extends BaseRequestEvent {\n kind: \"inbound\";\n /**\n * Where {@link BaseRequestEvent.frontendSessionId} came from. Absent means the browser\n * minted it and sent it on the request, which is the normal case. `\"backend\"` means the\n * shim minted it for a document navigation the browser could not tag, and the page may or\n * may not have gone on to adopt it — a distinction ingestion needs, because an unadopted\n * backend-minted id names a session that will never exist and must be treated as unstamped.\n * The sidecar turns it into `meticulous.session_id_origin`.\n *\n * Optional, and therefore compatible with an older sidecar (which ignores it) — which is\n * why adding it does not bump {@link SIDECAR_PROTOCOL_VERSION}, a strict-equality check\n * whose bump would instead make this shim unusable against one.\n */\n sessionIdOrigin?: \"backend\";\n}\n\n/**\n * An outgoing `fetch` call made while handling an inbound request (becomes a\n * CLIENT span).\n */\nexport interface OutboundRequestEvent extends BaseRequestEvent {\n kind: \"outbound\";\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/**\n * A `fetch` through a Cloudflare binding — a service binding, an assets binding, or a\n * Durable Object stub — made while handling an inbound request (becomes a CLIENT span).\n *\n * Request/Response-shaped like {@link OutboundRequestEvent}, but a distinct kind because the\n * call never leaves the isolate and its URL is whatever the caller invented. Keeping the two\n * apart means a binding call and real egress can never be confused for one another when\n * these spans are eventually mocked.\n */\nexport interface BindingRequestEvent extends BaseRequestEvent {\n kind: \"binding\";\n /**\n * The `env` key the binding was found under. Absent when the instance was never seen on\n * `env` — most commonly a Durable Object stub, which `namespace.get()` produces rather\n * than being a binding in its own right.\n */\n bindingName?: string;\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/** KV namespace methods the shim records. */\nexport type KvOperation = \"get\" | \"getWithMetadata\" | \"put\" | \"delete\" | \"list\";\n\n/**\n * Why a KV value is absent from an event: workerd handed it over in a form that cannot be\n * persisted as text. A `\"stream\"` value must not even be read — consuming it would take the\n * bytes away from the app — and binary values are skipped deliberately, since KV blobs are\n * large and would both bloat the recording and be mangled by UTF-8 capture.\n */\nexport type KvOmittedReason = \"binary\" | \"stream\";\n\n/**\n * An operation on a Cloudflare KV namespace binding, made while handling an inbound request\n * (becomes a CLIENT span).\n *\n * KV is not HTTP: there is no method, URL or status code, so this event shares nothing with\n * {@link BaseRequestEvent} beyond correlation and timing. Values are JSON so that a single\n * `JSON.parse` reconstructs exactly what the app saw, whichever `type` the read asked for.\n */\nexport interface KvOperationEvent extends CorrelatedEvent {\n kind: \"kv\";\n /**\n * The `env` key the KV namespace was found under. Always present, unlike on a binding\n * event: a namespace has no factory equivalent to `DurableObjectNamespace.get()`, so one\n * that was never seen on `env` is not recorded at all.\n */\n bindingName: string;\n operation: KvOperation;\n /**\n * The key operated on, when it is a single string. Absent for `list` (which spans keys) and\n * for a bulk `get` (which takes an array) — both keep their arguments in {@link args}.\n */\n key?: string;\n /**\n * JSON of the call's arguments: the read `type`, the `put` options, the `list` selector.\n * A `put` value appears as `null` here — it is captured in {@link value} instead, so that\n * redaction applies to it.\n */\n args?: CapturedBody;\n /** JSON of the value a `put` wrote, with secret-looking fields redacted. */\n value?: CapturedBody;\n /**\n * JSON of what the operation returned: the value for `get`, `{value, metadata}` for\n * `getWithMetadata`, the key page for `list`. Absent for `put`/`delete`, which return\n * nothing, and for a value that could not be captured (see {@link omitted}).\n */\n result?: CapturedBody;\n /**\n * Why the operation's value is missing. Refers to the written value for `put` and to the\n * read value otherwise — a `put` has no result, so this is never ambiguous.\n */\n omitted?: KvOmittedReason;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the operation threw. */\n error?: string;\n}\n\n/**\n * One postgres.js query made while handling an inbound request (becomes a CLIENT span).\n *\n * Deliberately carries the same fields the Node recorder puts on a postgres.js span rather than\n * anything Worker-specific: `PostgresJsMockStore` builds its match key from those attributes at\n * load time, so a query recorded here replays through the existing Node mock path unchanged.\n * See `postgres/capture.ts` for the serialization, which both surfaces share.\n */\nexport interface PostgresQueryEvent extends CorrelatedEvent {\n kind: \"postgres\";\n /** SQL rebuilt from the tagged template's chunks, with `$1`, `$2`… placeholders. */\n queryText: string;\n /** JSON of the interpolated values, from `serializePostgresJsArgs`. */\n params: string;\n /** `\"\"`, `\"raw\"` or `\"values\"` — the row shape the query asked for. */\n rowMode: string;\n /** JSON of the resolved `Result`, capped at {@link MAX_POSTGRES_JS_RESULT_SIZE}. */\n result?: CapturedBody;\n /**\n * JSON of the rejection, from `serializePostgresJsError`. Set instead of {@link result}, and\n * distinct from the transport-level `error` string on the HTTP-shaped events: this one is a\n * recorded outcome the replay reproduces, not a note that capture failed.\n */\n errorJson?: string;\n startTimeMs: number;\n endTimeMs: number;\n}\n\nexport type CaptureEvent =\n | InboundRequestEvent\n | OutboundRequestEvent\n | BindingRequestEvent\n | KvOperationEvent\n | PostgresQueryEvent;\n\nexport interface CaptureEventsPayload {\n events: CaptureEvent[];\n}\n\n/**\n * Answer to `GET {SIDECAR_REPLAY_SESSION_PATH}?sessionId=<id>`: whether the sidecar holds\n * mocks for a session, and the virtual clock anchor to freeze `Date` at while serving it.\n */\nexport interface ReplaySessionInfoResponse {\n found: boolean;\n /**\n * Epoch ms of the session's last recorded activity. The worker freezes its clock here so\n * that credentials minted during the recording are already issued but not yet expired.\n */\n clockAnchorMs?: number;\n}\n\n/**\n * One request's line coverage, sent to {@link SIDECAR_REPLAY_COVERAGE_PATH}\n * after the response has been produced.\n *\n * `files` carries the build-time id→line map and is sent only on the first\n * report of an isolate: it is the same for every request the isolate serves and\n * is far larger than the hits themselves.\n */\nexport interface CoverageReportRequest {\n frontendSessionId: string;\n /** Global line ids marked during this request, ascending. */\n hitIds: number[];\n /** Present on an isolate's first report only. */\n files?: Array<{\n path: string;\n firstId: number;\n /** Inclusive 1-based line ranges, flattened as `[s1, e1, s2, e2, ...]`. */\n lineRanges: number[];\n }>;\n}\n\n/** Lookup for a single outbound `fetch`, sent to {@link SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}. */\nexport interface OutboundFetchLookupRequest {\n frontendSessionId: string;\n replayId: string;\n method: string;\n /** Full URL including query string. */\n url: string;\n /**\n * Request body as captured by `readBodyWithCap`. The sidecar hashes this itself, so the\n * hash it compares against a recording is derived from byte-identical input on both the\n * record and replay sides.\n */\n requestBody?: CapturedBody;\n /**\n * Elapsed virtual time (ms from replay start) of the inbound request that\n * dispatched this outbound call, forwarded from {@link VIRTUAL_TIME_HEADER}.\n * The sidecar clusters candidates by recorded timestamp against this value.\n *\n * Additive and non-version-bumping: an older shim omits it, and matching\n * then hashes across every candidate at the matched key.\n */\n virtualTimeMs?: number;\n}\n\n/**\n * A recorded response to serve, or a signal the caller must fail the request. Replay is\n * hermetic, so the shim never turns any of these into a real call — nor an outcome it does\n * not recognise. The only live path is the request-side `meticulous-passthrough` header,\n * handled before the lookup, not any response here.\n */\nexport type OutboundFetchLookupResponse =\n | {\n outcome: \"mock\";\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n }\n /**\n * The store holds nothing for this call — a genuine miss, or a call the sidecar could not\n * look up at all (an unparseable URL). Replay is hermetic, so the shim fails the request\n * rather than letting it reach the real service — matching the Node backend recorder's\n * http/undici mocks. There is deliberately no \"let the call through\" outcome: the only\n * live path is the request-side `meticulous-passthrough` header.\n */\n | { outcome: \"no-mock\" };\n"],"names":[],"mappings":";;;;;;;;AAMA,MAAa,2BAA2B;;AAGxC,MAAa,kCACX;;;;;AAMF,MAAa,6BAA6B;;AAG1C,MAAa,mBAAmB;;;;;;;AAQhC,MAAa,sBAAsB;;;;;AAMnC,MAAa,sBACX,UACuB;AACvB,KAAI,SAAS,QAAQ,UAAU,GAC7B;CAEF,MAAM,SAAS,OAAO,MAAM;AAC5B,KAAI,CAAC,OAAO,SAAS,OAAO,IAAI,SAAS,EACvC;AAEF,QAAO;;;;;;;;;;;AAYT,MAAa,gCAAgC;AAE7C,MAAa,sBAAsB;;;;;;AAOnC,MAAa,8BAA8B;AAC3C,MAAa,qCAAqC;;;;;;;;AASlD,MAAa,+BAA+B;;;;;;;;;AAU5C,MAAa,4BACX;;;;;;;;AASF,MAAa,8BAA8B;;;;;;;;;;;AAY3C,MAAa,mBAAmB,CAC9B,gBACA,2BACD","debugId":"7851ef28-53e0-596f-80dc-a26f37790747"}
1
+ {"version":3,"file":"protocol.js","names":[],"sources":["../src/protocol.ts"],"sourcesContent":["/**\n * Wire protocol between the in-worker shim and the Meticulous backend\n * recorder sidecar. The sidecar imports these types (type-only), so this file\n * is the single source of truth for the shape of capture events.\n */\n\nexport const SIDECAR_PROTOCOL_VERSION = \"2\";\n\n/** Header carrying {@link SIDECAR_PROTOCOL_VERSION} on every shim → sidecar request. */\nexport const SIDECAR_PROTOCOL_VERSION_HEADER =\n \"x-meticulous-sidecar-protocol-version\";\n\n/**\n * Header the Meticulous frontend recorder stamps on requests made by the app\n * under recording; its value ties backend spans to the frontend session.\n */\nexport const FRONTEND_SESSION_ID_HEADER = \"x-meticulous-session-id\";\n\n/** Header identifying one replay attempt of a recorded frontend session. */\nexport const REPLAY_ID_HEADER = \"x-meticulous-replay-id\";\n\n/**\n * Elapsed virtual time (ms from replay start) of the triggering frontend\n * request. Injected by the replay runner on app-url requests during backend\n * testing; the sidecar uses it to pick the closest recorded burst when several\n * candidates share a loosened match key.\n */\nexport const VIRTUAL_TIME_HEADER = \"x-meticulous-virtual-time\";\n\n/**\n * Parses {@link VIRTUAL_TIME_HEADER}. `0` is a valid start-of-session time;\n * anything non-finite or negative is ignored so a garbage header cannot skew matching.\n */\nexport const parseVirtualTimeMs = (\n value: string | null | undefined,\n): number | undefined => {\n if (value == null || value === \"\") {\n return undefined;\n }\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n return undefined;\n }\n return parsed;\n};\n\n/**\n * A request carrying this header set to `\"true\"` is never served from the recording and\n * never fails on a miss — it goes to the real network. Use it for a call that must be live\n * during replay (a health probe, telemetry, a resource the recording cannot cover).\n *\n * Same convention and value as the frontend network stubbing and the Node backend recorder\n * (`METICULOUS_PASSTHROUGH_HEADER` in `@alwaysmeticulous/backend-recorder-js`); the value\n * must stay in step with both.\n */\nexport const METICULOUS_PASSTHROUGH_HEADER = \"meticulous-passthrough\";\n\nexport const SIDECAR_EVENTS_PATH = \"/v1/events\";\n\n/**\n * Replay routes. A sidecar started in record mode answers 404 on both. Replay is hermetic,\n * so an unanswered outbound-fetch lookup fails the app's call rather than letting it reach\n * the real service — the same as any other failure to stub.\n */\nexport const SIDECAR_REPLAY_SESSION_PATH = \"/v1/replay/session\";\nexport const SIDECAR_REPLAY_OUTBOUND_FETCH_PATH = \"/v1/replay/outbound-fetch\";\n\n/**\n * Line-coverage reporting. Additive: an older sidecar answers 404, which the\n * shim treats as \"coverage not collected here\" and stops reporting for the life\n * of the isolate. Deliberately NOT guarded by a\n * {@link SIDECAR_PROTOCOL_VERSION} bump — that check is exact equality, so a\n * bump would stop every already-built customer image from mocking at all.\n */\nexport const SIDECAR_REPLAY_COVERAGE_PATH = \"/v1/replay/coverage\";\n\n/**\n * Header carrying the replay sidecar's origin, injected by the Meticulous replay runner\n * on requests to the app under test. Workerd cannot see container environment variables,\n * so an inbound header is the only way per-replay config can reach the shim.\n *\n * The shim validates the value before using it and only honours a loopback /\n * `host.docker.internal` / private-network `http:` origin — see `replay-sidecar-url.ts`.\n */\nexport const REPLAY_SIDECAR_URL_HEADER =\n \"x-meticulous-backend-replay-sidecar-url\";\n\n/**\n * Header the in-worker shim stamps on every app response (record and replay)\n * carrying the shim's npm package version. The replay runner reads this from\n * Puppeteer — workerd cannot see container env, and the execute pod cannot\n * reach the in-pod sidecar, so a response header is the only channel that\n * reports which bundled shim produced a replay's After screenshots.\n */\nexport const WORKERD_SHIM_VERSION_HEADER = \"x-meticulous-workerd-shim-version\";\n\n/**\n * The only headers persisted on capture events. Everything else — notably\n * authorization, cookie/set-cookie, and API-key headers — is dropped at\n * capture time, before it ever leaves the worker.\n *\n * The Node backend recorder persists the same two, plus the inbound request's\n * `Cookie` header on SERVER spans (`recorded-request-headers.ts`). This list\n * has not followed it there, so a workerd recording of an authenticated server\n * render still carries no session cookie.\n */\nexport const CAPTURED_HEADERS = [\n \"content-type\",\n FRONTEND_SESSION_ID_HEADER,\n] as const;\n\nexport interface CapturedBody {\n /** UTF-8 decoded body, truncated to the capture cap. */\n body: string;\n /** True when the body exceeded the capture cap or the read was cut short. */\n truncated: boolean;\n}\n\n/**\n * The fields every capture event carries to say which request, session and trace it belongs to.\n */\ninterface CorrelatedEvent {\n /** Correlates outbound events to the inbound request being handled. */\n requestId: string;\n /** Value of {@link FRONTEND_SESSION_ID_HEADER} on the inbound request, if any. */\n frontendSessionId?: string;\n /**\n * Trace the request's spans belong to (32 hex chars), minted by the shim.\n *\n * The shim mints it, rather than the sidecar deriving it from {@link requestId}, so span\n * assembly is stateless: a sidecar that had to remember `requestId → traceId` would give a\n * request's SERVER span and its CLIENT children different traces whenever it lost that memory\n * between two batches — which, for a Worker-hosted sidecar, an eviction can do at any moment.\n *\n * Optional so a sidecar keeps working against a shim that predates this field, in which case\n * it falls back to its own per-`requestId` map.\n */\n traceId?: string;\n /**\n * Span id of the request's SERVER span (16 hex chars), also minted by the shim: it is the\n * parent of every CLIENT span the request produced, and the inbound event's own span id.\n */\n serverSpanId?: string;\n}\n\ninterface BaseRequestEvent extends CorrelatedEvent {\n method: string;\n /** Full URL including query string. */\n url: string;\n /** Lower-cased header name → values. */\n requestHeaders: Record<string, string[]>;\n responseHeaders?: Record<string, string[]>;\n statusCode?: number;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the request failed before a response was produced. */\n error?: string;\n}\n\n/**\n * The worker's own inbound request (becomes a SERVER span). Bodies are not\n * captured, matching the Node backend recorder's SERVER-span contract.\n */\nexport interface InboundRequestEvent extends BaseRequestEvent {\n kind: \"inbound\";\n /**\n * Where {@link BaseRequestEvent.frontendSessionId} came from. Absent means the browser\n * minted it and sent it on the request, which is the normal case. `\"backend\"` means the\n * shim minted it for a document navigation the browser could not tag, and the page may or\n * may not have gone on to adopt it — a distinction ingestion needs, because an unadopted\n * backend-minted id names a session that will never exist and must be treated as unstamped.\n * The sidecar turns it into `meticulous.session_id_origin`.\n *\n * Optional, and therefore compatible with an older sidecar (which ignores it) — which is\n * why adding it does not bump {@link SIDECAR_PROTOCOL_VERSION}, a strict-equality check\n * whose bump would instead make this shim unusable against one.\n */\n sessionIdOrigin?: \"backend\";\n}\n\n/**\n * An outgoing `fetch` call made while handling an inbound request (becomes a\n * CLIENT span).\n */\nexport interface OutboundRequestEvent extends BaseRequestEvent {\n kind: \"outbound\";\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/**\n * A `fetch` through a Cloudflare binding — a service binding, an assets binding, or a\n * Durable Object stub — made while handling an inbound request (becomes a CLIENT span).\n *\n * Request/Response-shaped like {@link OutboundRequestEvent}, but a distinct kind because the\n * call never leaves the isolate and its URL is whatever the caller invented. Keeping the two\n * apart means a binding call and real egress can never be confused for one another when\n * these spans are eventually mocked.\n */\nexport interface BindingRequestEvent extends BaseRequestEvent {\n kind: \"binding\";\n /**\n * The `env` key the binding was found under. Absent when the instance was never seen on\n * `env` — most commonly a Durable Object stub, which `namespace.get()` produces rather\n * than being a binding in its own right.\n */\n bindingName?: string;\n requestBody?: CapturedBody;\n responseBody?: CapturedBody;\n}\n\n/** KV namespace methods the shim records. */\nexport type KvOperation = \"get\" | \"getWithMetadata\" | \"put\" | \"delete\" | \"list\";\n\n/**\n * Why a KV value is absent from an event: workerd handed it over in a form that cannot be\n * persisted as text. A `\"stream\"` value must not even be read — consuming it would take the\n * bytes away from the app — and binary values are skipped deliberately, since KV blobs are\n * large and would both bloat the recording and be mangled by UTF-8 capture.\n */\nexport type KvOmittedReason = \"binary\" | \"stream\";\n\n/**\n * An operation on a Cloudflare KV namespace binding, made while handling an inbound request\n * (becomes a CLIENT span).\n *\n * KV is not HTTP: there is no method, URL or status code, so this event shares nothing with\n * {@link BaseRequestEvent} beyond correlation and timing. Values are JSON so that a single\n * `JSON.parse` reconstructs exactly what the app saw, whichever `type` the read asked for.\n */\nexport interface KvOperationEvent extends CorrelatedEvent {\n kind: \"kv\";\n /**\n * The `env` key the KV namespace was found under. Always present, unlike on a binding\n * event: a namespace has no factory equivalent to `DurableObjectNamespace.get()`, so one\n * that was never seen on `env` is not recorded at all.\n */\n bindingName: string;\n operation: KvOperation;\n /**\n * The key operated on, when it is a single string. Absent for `list` (which spans keys) and\n * for a bulk `get` (which takes an array) — both keep their arguments in {@link args}.\n */\n key?: string;\n /**\n * JSON of the call's arguments: the read `type`, the `put` options, the `list` selector.\n * A `put` value appears as `null` here — it is captured in {@link value} instead, so that\n * redaction applies to it.\n */\n args?: CapturedBody;\n /** JSON of the value a `put` wrote, with secret-looking fields redacted. */\n value?: CapturedBody;\n /**\n * JSON of what the operation returned: the value for `get`, `{value, metadata}` for\n * `getWithMetadata`, the key page for `list`. Absent for `put`/`delete`, which return\n * nothing, and for a value that could not be captured (see {@link omitted}).\n */\n result?: CapturedBody;\n /**\n * Why the operation's value is missing. Refers to the written value for `put` and to the\n * read value otherwise — a `put` has no result, so this is never ambiguous.\n */\n omitted?: KvOmittedReason;\n startTimeMs: number;\n endTimeMs: number;\n /** Set when the operation threw. */\n error?: string;\n}\n\n/**\n * One postgres.js query made while handling an inbound request (becomes a CLIENT span).\n *\n * Deliberately carries the same fields the Node recorder puts on a postgres.js span rather than\n * anything Worker-specific: `PostgresJsMockStore` builds its match key from those attributes at\n * load time, so a query recorded here replays through the existing Node mock path unchanged.\n * See `postgres/capture.ts` for the serialization, which both surfaces share.\n */\nexport interface PostgresQueryEvent extends CorrelatedEvent {\n kind: \"postgres\";\n /** SQL rebuilt from the tagged template's chunks, with `$1`, `$2`… placeholders. */\n queryText: string;\n /** JSON of the interpolated values, from `serializePostgresJsArgs`. */\n params: string;\n /** `\"\"`, `\"raw\"` or `\"values\"` — the row shape the query asked for. */\n rowMode: string;\n /** JSON of the resolved `Result`, capped at {@link MAX_POSTGRES_JS_RESULT_SIZE}. */\n result?: CapturedBody;\n /**\n * JSON of the rejection, from `serializePostgresJsError`. Set instead of {@link result}, and\n * distinct from the transport-level `error` string on the HTTP-shaped events: this one is a\n * recorded outcome the replay reproduces, not a note that capture failed.\n */\n errorJson?: string;\n startTimeMs: number;\n endTimeMs: number;\n}\n\nexport type CaptureEvent =\n | InboundRequestEvent\n | OutboundRequestEvent\n | BindingRequestEvent\n | KvOperationEvent\n | PostgresQueryEvent;\n\nexport interface CaptureEventsPayload {\n events: CaptureEvent[];\n}\n\n/**\n * Answer to `GET {SIDECAR_REPLAY_SESSION_PATH}?sessionId=<id>`: whether the sidecar holds\n * mocks for a session, and the virtual clock anchor to freeze `Date` at while serving it.\n */\nexport interface ReplaySessionInfoResponse {\n found: boolean;\n /**\n * Epoch ms of the session's last recorded activity. The worker freezes its clock here so\n * that credentials minted during the recording are already issued but not yet expired.\n */\n clockAnchorMs?: number;\n}\n\n/**\n * One request's line coverage, sent to {@link SIDECAR_REPLAY_COVERAGE_PATH}\n * after the response has been produced.\n *\n * `files` carries the build-time id→line map and is sent only on the first\n * report of an isolate: it is the same for every request the isolate serves and\n * is far larger than the hits themselves.\n */\nexport interface CoverageReportRequest {\n frontendSessionId: string;\n /** Global line ids marked during this request, ascending. */\n hitIds: number[];\n /** Present on an isolate's first report only. */\n files?: Array<{\n path: string;\n firstId: number;\n /** Inclusive 1-based line ranges, flattened as `[s1, e1, s2, e2, ...]`. */\n lineRanges: number[];\n }>;\n}\n\n/** Lookup for a single outbound `fetch`, sent to {@link SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}. */\nexport interface OutboundFetchLookupRequest {\n frontendSessionId: string;\n replayId: string;\n method: string;\n /** Full URL including query string. */\n url: string;\n /**\n * Request body as captured by `readBodyWithCap`. The sidecar hashes this itself, so the\n * hash it compares against a recording is derived from byte-identical input on both the\n * record and replay sides.\n */\n requestBody?: CapturedBody;\n /**\n * Elapsed virtual time (ms from replay start) of the inbound request that\n * dispatched this outbound call, forwarded from {@link VIRTUAL_TIME_HEADER}.\n * The sidecar clusters candidates by recorded timestamp against this value.\n *\n * Additive and non-version-bumping: an older shim omits it, and matching\n * then hashes across every candidate at the matched key.\n */\n virtualTimeMs?: number;\n}\n\n/**\n * A recorded response to serve, or a signal the caller must fail the request. Replay is\n * hermetic, so the shim never turns any of these into a real call — nor an outcome it does\n * not recognise. The only live path is the request-side `meticulous-passthrough` header,\n * handled before the lookup, not any response here.\n */\nexport type OutboundFetchLookupResponse =\n | {\n outcome: \"mock\";\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n }\n /**\n * The store holds nothing for this call — a genuine miss, or a call the sidecar could not\n * look up at all (an unparseable URL). Replay is hermetic, so the shim fails the request\n * rather than letting it reach the real service — matching the Node backend recorder's\n * http/undici mocks. There is deliberately no \"let the call through\" outcome: the only\n * live path is the request-side `meticulous-passthrough` header.\n */\n | { outcome: \"no-mock\" };\n"],"mappings":";;;;;;AAMA,MAAa,2BAA2B;;AAGxC,MAAa,kCACX;;;;;AAMF,MAAa,6BAA6B;;AAG1C,MAAa,mBAAmB;;;;;;;AAQhC,MAAa,sBAAsB;;;;;AAMnC,MAAa,sBACX,UACuB;AACvB,KAAI,SAAS,QAAQ,UAAU,GAC7B;CAEF,MAAM,SAAS,OAAO,MAAM;AAC5B,KAAI,CAAC,OAAO,SAAS,OAAO,IAAI,SAAS,EACvC;AAEF,QAAO;;;;;;;;;;;AAYT,MAAa,gCAAgC;AAE7C,MAAa,sBAAsB;;;;;;AAOnC,MAAa,8BAA8B;AAC3C,MAAa,qCAAqC;;;;;;;;AASlD,MAAa,+BAA+B;;;;;;;;;AAU5C,MAAa,4BACX;;;;;;;;AASF,MAAa,8BAA8B;;;;;;;;;;;AAY3C,MAAa,mBAAmB,CAC9B,gBACA,2BACD"}
@@ -1,5 +1,3 @@
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]="08993983-84c7-52a8-95ae-69986b1ed730")}catch(e){}}();
3
1
  import "./protocol.js";
4
2
  //#region src/provisional-session-id.ts
5
3
  const SERVER_TIMING_HEADER = "server-timing";
@@ -71,5 +69,4 @@ const isDocumentNavigation = (getHeader) => {
71
69
  //#endregion
72
70
  export { SERVER_TIMING_HEADER, SERVER_TIMING_SESSION_METRIC, buildServerTimingSessionEntry, isProvisionalSessionIdCandidate, mintProvisionalSessionId };
73
71
 
74
- //# sourceMappingURL=provisional-session-id.js.map
75
- //# debugId=08993983-84c7-52a8-95ae-69986b1ed730
72
+ //# sourceMappingURL=provisional-session-id.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"provisional-session-id.js","sources":["../src/provisional-session-id.ts"],"sourcesContent":["import { FRONTEND_SESSION_ID_HEADER } from \"./protocol\";\n\n/**\n * A session id the *backend* mints, for the one request that can never carry one from the\n * browser: a top-level document navigation. Browsers cannot add custom headers to a\n * navigation, and on the session-starting navigation the frontend has not minted an id yet\n * (it does so only once the HTML has arrived and the snippet has run) — so the server-side\n * render's spans are recorded against no session and nothing about that traffic can be\n * replayed exactly.\n *\n * Everything here is runtime-agnostic on purpose. Both backend recorders mint the same ids\n * by the same rule and publish them under the same `Server-Timing` metric, and all three are\n * wire contracts with the page, so there is exactly one implementation — the same reason\n * kv-capture.ts lives here rather than being written twice. The Node recorder imports these\n * from the package entry; see `provisional-session-id.ts` in\n * `@alwaysmeticulous/backend-recorder-js` for the `http.IncomingMessage` adapter, and\n * `publish-session-id.ts` next door for the workerd one.\n */\n\n/**\n * Reads one request header by its lower-cased name. Both `IncomingMessage.headers[name]`\n * (after the caller flattens Node's `string | string[]`) and `Headers.get(name)` satisfy it,\n * which is what lets the rules below be shared.\n */\nexport type HeaderReader = (name: string) => string | null | undefined;\n\nexport const SERVER_TIMING_HEADER = \"server-timing\";\n\n/**\n * The `Server-Timing` metric name carrying a backend-minted session id to the page. A wire\n * contract with the frontend recorder, which matches on it case-insensitively when reading\n * `PerformanceNavigationTiming.serverTiming` (see `resolve-session-id.ts` in\n * packages/recorder). Must be a valid HTTP token — no `.` or `:`, which is why it is not the\n * dotted span-attribute name.\n */\nexport const SERVER_TIMING_SESSION_METRIC = \"metsession\";\n\n/**\n * `Server-Timing` is the one response header a document's own JavaScript can read back, and\n * the navigation entry persists for the document's lifetime — so unlike a header-sniffing\n * approach this works no matter how late the snippet loads.\n */\nexport const buildServerTimingSessionEntry = (sessionId: string): string =>\n `${SERVER_TIMING_SESSION_METRIC};desc=\"${sessionId}\"`;\n\n/**\n * nanoid's default alphabet and length, reproduced rather than imported: this package carries\n * no runtime dependencies, and an id that did not look like every other session id would be a\n * gratuitous difference in S3 keys and URLs. 64 characters divides 256 exactly, so masking a\n * random byte with 63 is uniform — which is how nanoid itself generates them.\n */\nconst ID_ALPHABET =\n \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\nconst ID_LENGTH = 21;\n\n/**\n * Mints an id in exactly the frontend recorder's format: `<ISO timestamp>_<nanoid>` (see\n * `createConfig` in packages/recorder). The format is a wire contract, not cosmetic —\n * ingestion parses the ISO prefix back out to anchor the inferred-attachment window\n * (`parseTimestampFromFrontendSessionId` in lambda-upload-sessions), and the page uses it to\n * reject an id stale enough to have come from a cache.\n */\nexport const mintProvisionalSessionId = (): string => {\n const bytes = new Uint8Array(ID_LENGTH);\n crypto.getRandomValues(bytes);\n let suffix = \"\";\n for (const byte of bytes) {\n suffix += ID_ALPHABET[byte & 63];\n }\n return `${new Date().toISOString()}_${suffix}`;\n};\n\n/**\n * Whether to mint for this inbound request. Deliberately narrow: an id nothing adopts is\n * worse than no id at all, because a span stamped with a session that never materialises is\n * excluded from the time-window fallback that would otherwise have caught it. So we mint only\n * for what is plausibly a browser navigating to a page.\n *\n * The caller decides separately whether minting is enabled at all.\n */\nexport const isProvisionalSessionIdCandidate = (\n method: string,\n getHeader: HeaderReader,\n): boolean => {\n // A request that already names its session needs nothing from us.\n if (getHeader(FRONTEND_SESSION_ID_HEADER) != null) {\n return false;\n }\n const normalizedMethod = method.toUpperCase();\n if (normalizedMethod !== \"GET\" && normalizedMethod !== \"HEAD\") {\n return false;\n }\n return isDocumentNavigation(getHeader);\n};\n\n/**\n * `Sec-Fetch-Dest` is the exact signal and every current browser sends it: `document` for a\n * navigation, `empty` for an in-page fetch (so a Next.js RSC navigation, which is a fetch, is\n * correctly excluded), `iframe` for a subframe — excluded too, since the top frame owns the\n * session and an iframe recorder reports into it.\n *\n * Absent, the caller is an older browser or not a browser at all (curl, a health check, a\n * crawler), and `Accept` is the only hint left.\n */\nconst isDocumentNavigation = (getHeader: HeaderReader): boolean => {\n const dest = getHeader(\"sec-fetch-dest\");\n if (typeof dest === \"string\") {\n return dest === \"document\";\n }\n const accept = getHeader(\"accept\");\n return typeof accept === \"string\" && accept.includes(\"text/html\");\n};\n"],"names":[],"mappings":";;;;AA0BA,MAAa,uBAAuB;;;;;;;;AASpC,MAAa,+BAA+B;;;;;;AAO5C,MAAa,iCAAiC,cAC5C,GAAG,6BAA6B,SAAS,UAAU;;;;;;;AAQrD,MAAM,cACJ;AACF,MAAM,YAAY;;;;;;;;AASlB,MAAa,iCAAyC;CACpD,MAAM,QAAQ,IAAI,WAAW,UAAU;AACvC,QAAO,gBAAgB,MAAM;CAC7B,IAAI,SAAS;AACb,MAAK,MAAM,QAAQ,MACjB,WAAU,YAAY,OAAO;AAE/B,QAAO,oBAAG,IAAI,MAAM,EAAC,aAAa,CAAC,GAAG;;;;;;;;;;AAWxC,MAAa,mCACX,QACA,cACY;AAEZ,KAAI,UAAA,0BAAqC,IAAI,KAC3C,QAAO;CAET,MAAM,mBAAmB,OAAO,aAAa;AAC7C,KAAI,qBAAqB,SAAS,qBAAqB,OACrD,QAAO;AAET,QAAO,qBAAqB,UAAU;;;;;;;;;;;AAYxC,MAAM,wBAAwB,cAAqC;CACjE,MAAM,OAAO,UAAU,iBAAiB;AACxC,KAAI,OAAO,SAAS,SAClB,QAAO,SAAS;CAElB,MAAM,SAAS,UAAU,SAAS;AAClC,QAAO,OAAO,WAAW,YAAY,OAAO,SAAS,YAAY","debugId":"08993983-84c7-52a8-95ae-69986b1ed730"}
1
+ {"version":3,"file":"provisional-session-id.js","names":[],"sources":["../src/provisional-session-id.ts"],"sourcesContent":["import { FRONTEND_SESSION_ID_HEADER } from \"./protocol\";\n\n/**\n * A session id the *backend* mints, for the one request that can never carry one from the\n * browser: a top-level document navigation. Browsers cannot add custom headers to a\n * navigation, and on the session-starting navigation the frontend has not minted an id yet\n * (it does so only once the HTML has arrived and the snippet has run) — so the server-side\n * render's spans are recorded against no session and nothing about that traffic can be\n * replayed exactly.\n *\n * Everything here is runtime-agnostic on purpose. Both backend recorders mint the same ids\n * by the same rule and publish them under the same `Server-Timing` metric, and all three are\n * wire contracts with the page, so there is exactly one implementation — the same reason\n * kv-capture.ts lives here rather than being written twice. The Node recorder imports these\n * from the package entry; see `provisional-session-id.ts` in\n * `@alwaysmeticulous/backend-recorder-js` for the `http.IncomingMessage` adapter, and\n * `publish-session-id.ts` next door for the workerd one.\n */\n\n/**\n * Reads one request header by its lower-cased name. Both `IncomingMessage.headers[name]`\n * (after the caller flattens Node's `string | string[]`) and `Headers.get(name)` satisfy it,\n * which is what lets the rules below be shared.\n */\nexport type HeaderReader = (name: string) => string | null | undefined;\n\nexport const SERVER_TIMING_HEADER = \"server-timing\";\n\n/**\n * The `Server-Timing` metric name carrying a backend-minted session id to the page. A wire\n * contract with the frontend recorder, which matches on it case-insensitively when reading\n * `PerformanceNavigationTiming.serverTiming` (see `resolve-session-id.ts` in\n * packages/recorder). Must be a valid HTTP token — no `.` or `:`, which is why it is not the\n * dotted span-attribute name.\n */\nexport const SERVER_TIMING_SESSION_METRIC = \"metsession\";\n\n/**\n * `Server-Timing` is the one response header a document's own JavaScript can read back, and\n * the navigation entry persists for the document's lifetime — so unlike a header-sniffing\n * approach this works no matter how late the snippet loads.\n */\nexport const buildServerTimingSessionEntry = (sessionId: string): string =>\n `${SERVER_TIMING_SESSION_METRIC};desc=\"${sessionId}\"`;\n\n/**\n * nanoid's default alphabet and length, reproduced rather than imported: this package carries\n * no runtime dependencies, and an id that did not look like every other session id would be a\n * gratuitous difference in S3 keys and URLs. 64 characters divides 256 exactly, so masking a\n * random byte with 63 is uniform — which is how nanoid itself generates them.\n */\nconst ID_ALPHABET =\n \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\nconst ID_LENGTH = 21;\n\n/**\n * Mints an id in exactly the frontend recorder's format: `<ISO timestamp>_<nanoid>` (see\n * `createConfig` in packages/recorder). The format is a wire contract, not cosmetic —\n * ingestion parses the ISO prefix back out to anchor the inferred-attachment window\n * (`parseTimestampFromFrontendSessionId` in lambda-upload-sessions), and the page uses it to\n * reject an id stale enough to have come from a cache.\n */\nexport const mintProvisionalSessionId = (): string => {\n const bytes = new Uint8Array(ID_LENGTH);\n crypto.getRandomValues(bytes);\n let suffix = \"\";\n for (const byte of bytes) {\n suffix += ID_ALPHABET[byte & 63];\n }\n return `${new Date().toISOString()}_${suffix}`;\n};\n\n/**\n * Whether to mint for this inbound request. Deliberately narrow: an id nothing adopts is\n * worse than no id at all, because a span stamped with a session that never materialises is\n * excluded from the time-window fallback that would otherwise have caught it. So we mint only\n * for what is plausibly a browser navigating to a page.\n *\n * The caller decides separately whether minting is enabled at all.\n */\nexport const isProvisionalSessionIdCandidate = (\n method: string,\n getHeader: HeaderReader,\n): boolean => {\n // A request that already names its session needs nothing from us.\n if (getHeader(FRONTEND_SESSION_ID_HEADER) != null) {\n return false;\n }\n const normalizedMethod = method.toUpperCase();\n if (normalizedMethod !== \"GET\" && normalizedMethod !== \"HEAD\") {\n return false;\n }\n return isDocumentNavigation(getHeader);\n};\n\n/**\n * `Sec-Fetch-Dest` is the exact signal and every current browser sends it: `document` for a\n * navigation, `empty` for an in-page fetch (so a Next.js RSC navigation, which is a fetch, is\n * correctly excluded), `iframe` for a subframe — excluded too, since the top frame owns the\n * session and an iframe recorder reports into it.\n *\n * Absent, the caller is an older browser or not a browser at all (curl, a health check, a\n * crawler), and `Accept` is the only hint left.\n */\nconst isDocumentNavigation = (getHeader: HeaderReader): boolean => {\n const dest = getHeader(\"sec-fetch-dest\");\n if (typeof dest === \"string\") {\n return dest === \"document\";\n }\n const accept = getHeader(\"accept\");\n return typeof accept === \"string\" && accept.includes(\"text/html\");\n};\n"],"mappings":";;AA0BA,MAAa,uBAAuB;;;;;;;;AASpC,MAAa,+BAA+B;;;;;;AAO5C,MAAa,iCAAiC,cAC5C,GAAG,6BAA6B,SAAS,UAAU;;;;;;;AAQrD,MAAM,cACJ;AACF,MAAM,YAAY;;;;;;;;AASlB,MAAa,iCAAyC;CACpD,MAAM,QAAQ,IAAI,WAAW,UAAU;AACvC,QAAO,gBAAgB,MAAM;CAC7B,IAAI,SAAS;AACb,MAAK,MAAM,QAAQ,MACjB,WAAU,YAAY,OAAO;AAE/B,QAAO,oBAAG,IAAI,MAAM,EAAC,aAAa,CAAC,GAAG;;;;;;;;;;AAWxC,MAAa,mCACX,QACA,cACY;AAEZ,KAAI,UAAA,0BAAqC,IAAI,KAC3C,QAAO;CAET,MAAM,mBAAmB,OAAO,aAAa;AAC7C,KAAI,qBAAqB,SAAS,qBAAqB,OACrD,QAAO;AAET,QAAO,qBAAqB,UAAU;;;;;;;;;;;AAYxC,MAAM,wBAAwB,cAAqC;CACjE,MAAM,OAAO,UAAU,iBAAiB;AACxC,KAAI,OAAO,SAAS,SAClB,QAAO,SAAS;CAElB,MAAM,SAAS,UAAU,SAAS;AAClC,QAAO,OAAO,WAAW,YAAY,OAAO,SAAS,YAAY"}
@@ -1,5 +1,3 @@
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]="c7b8eed0-1eb8-5c3b-9d7f-7dec5248e263")}catch(e){}}();
3
1
  import { warnOnce } from "./log.js";
4
2
  import { hasWebSocket } from "./outbound-capture.js";
5
3
  import { SERVER_TIMING_HEADER, buildServerTimingSessionEntry } from "./provisional-session-id.js";
@@ -37,5 +35,4 @@ const publishSessionIdOnResponse = (response, sessionId) => {
37
35
  //#endregion
38
36
  export { publishSessionIdOnResponse };
39
37
 
40
- //# sourceMappingURL=publish-session-id.js.map
41
- //# debugId=c7b8eed0-1eb8-5c3b-9d7f-7dec5248e263
38
+ //# sourceMappingURL=publish-session-id.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"publish-session-id.js","sources":["../src/publish-session-id.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { hasWebSocket } from \"./outbound-capture\";\nimport {\n SERVER_TIMING_HEADER,\n buildServerTimingSessionEntry,\n} from \"./provisional-session-id\";\n\n/**\n * Publishes a backend-minted session id to the page on the response it is about to receive,\n * so the frontend recorder adopts it instead of minting its own and the whole page load —\n * server-side render included — ends up under one session id.\n *\n * Returns the response to send, which is not always the one passed in: a `Response` handed\n * back by `fetch` or by an assets binding has immutable headers, and the only way to add one\n * is to rebuild around the same body. Best-effort throughout — a recorder must never break\n * the customer's app, so anything unexpected returns the original response unchanged.\n *\n * Unlike the Node recorder there is no `headersSent` race to lose: workerd flushes the\n * response only once the handler has returned it to us, so even a streaming SSR body still\n * has its headers in front of it at this point.\n */\nexport const publishSessionIdOnResponse = (\n response: Response,\n sessionId: string,\n): Response => {\n const entry = buildServerTimingSessionEntry(sessionId);\n\n try {\n // Appends rather than replaces: apps publish their own server timings, and clobbering\n // them would be a visible regression in their tooling.\n response.headers.append(SERVER_TIMING_HEADER, entry);\n return response;\n } catch {\n // Immutable headers. Fall through and rebuild.\n }\n\n try {\n // A WebSocket upgrade carries the socket rather than a body and cannot survive being\n // rebuilt; it is never a document navigation either, so there is nothing to publish to.\n if (hasWebSocket(response) || response.status === 101) {\n return response;\n }\n const rebuilt = new Response(response.body, response);\n rebuilt.headers.append(SERVER_TIMING_HEADER, entry);\n return rebuilt;\n } catch (error) {\n warnOnce(\n \"publish-session-id\",\n \"Failed to publish the backend-minted session id on the response.\",\n error,\n );\n return response;\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,8BACX,UACA,cACa;CACb,MAAM,QAAQ,8BAA8B,UAAU;AAEtD,KAAI;AAGF,WAAS,QAAQ,OAAO,sBAAsB,MAAM;AACpD,SAAO;SACD;AAIR,KAAI;AAGF,MAAI,aAAa,SAAS,IAAI,SAAS,WAAW,IAChD,QAAO;EAET,MAAM,UAAU,IAAI,SAAS,SAAS,MAAM,SAAS;AACrD,UAAQ,QAAQ,OAAO,sBAAsB,MAAM;AACnD,SAAO;UACA,OAAO;AACd,WACE,sBACA,oEACA,MACD;AACD,SAAO","debugId":"c7b8eed0-1eb8-5c3b-9d7f-7dec5248e263"}
1
+ {"version":3,"file":"publish-session-id.js","names":[],"sources":["../src/publish-session-id.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { hasWebSocket } from \"./outbound-capture\";\nimport {\n SERVER_TIMING_HEADER,\n buildServerTimingSessionEntry,\n} from \"./provisional-session-id\";\n\n/**\n * Publishes a backend-minted session id to the page on the response it is about to receive,\n * so the frontend recorder adopts it instead of minting its own and the whole page load —\n * server-side render included — ends up under one session id.\n *\n * Returns the response to send, which is not always the one passed in: a `Response` handed\n * back by `fetch` or by an assets binding has immutable headers, and the only way to add one\n * is to rebuild around the same body. Best-effort throughout — a recorder must never break\n * the customer's app, so anything unexpected returns the original response unchanged.\n *\n * Unlike the Node recorder there is no `headersSent` race to lose: workerd flushes the\n * response only once the handler has returned it to us, so even a streaming SSR body still\n * has its headers in front of it at this point.\n */\nexport const publishSessionIdOnResponse = (\n response: Response,\n sessionId: string,\n): Response => {\n const entry = buildServerTimingSessionEntry(sessionId);\n\n try {\n // Appends rather than replaces: apps publish their own server timings, and clobbering\n // them would be a visible regression in their tooling.\n response.headers.append(SERVER_TIMING_HEADER, entry);\n return response;\n } catch {\n // Immutable headers. Fall through and rebuild.\n }\n\n try {\n // A WebSocket upgrade carries the socket rather than a body and cannot survive being\n // rebuilt; it is never a document navigation either, so there is nothing to publish to.\n if (hasWebSocket(response) || response.status === 101) {\n return response;\n }\n const rebuilt = new Response(response.body, response);\n rebuilt.headers.append(SERVER_TIMING_HEADER, entry);\n return rebuilt;\n } catch (error) {\n warnOnce(\n \"publish-session-id\",\n \"Failed to publish the backend-minted session id on the response.\",\n error,\n );\n return response;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,MAAa,8BACX,UACA,cACa;CACb,MAAM,QAAQ,8BAA8B,UAAU;AAEtD,KAAI;AAGF,WAAS,QAAQ,OAAO,sBAAsB,MAAM;AACpD,SAAO;SACD;AAIR,KAAI;AAGF,MAAI,aAAa,SAAS,IAAI,SAAS,WAAW,IAChD,QAAO;EAET,MAAM,UAAU,IAAI,SAAS,SAAS,MAAM,SAAS;AACrD,UAAQ,QAAQ,OAAO,sBAAsB,MAAM;AACnD,SAAO;UACA,OAAO;AACd,WACE,sBACA,oEACA,MACD;AACD,SAAO"}
@@ -1,5 +1,3 @@
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]="1cb92f56-68e8-5791-b6c7-c8bca161b130")}catch(e){}}();
3
1
  import { warnOnce } from "./log.js";
4
2
  import { WORKERD_SHIM_VERSION_HEADER } from "./protocol.js";
5
3
  import { hasWebSocket } from "./outbound-capture.js";
@@ -33,5 +31,4 @@ const publishWorkerdShimVersionOnResponse = (response) => {
33
31
  //#endregion
34
32
  export { publishWorkerdShimVersionOnResponse };
35
33
 
36
- //# sourceMappingURL=publish-shim-version.js.map
37
- //# debugId=1cb92f56-68e8-5791-b6c7-c8bca161b130
34
+ //# sourceMappingURL=publish-shim-version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"publish-shim-version.js","sources":["../src/publish-shim-version.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { hasWebSocket } from \"./outbound-capture\";\nimport { WORKERD_SHIM_VERSION_HEADER } from \"./protocol\";\nimport { WORKERD_SHIM_VERSION } from \"./version\";\n\n/**\n * Stamps this shim's npm package version on the response the browser is about\n * to receive, so the replay runner can tell which bundled shim produced the\n * After screenshots.\n *\n * Returns the response to send, which is not always the one passed in: a\n * `Response` handed back by `fetch` or by an assets binding has immutable\n * headers, and the only way to add one is to rebuild around the same body.\n * Best-effort throughout — a recorder must never break the customer's app.\n */\nexport const publishWorkerdShimVersionOnResponse = (\n response: Response,\n): Response => {\n try {\n response.headers.set(WORKERD_SHIM_VERSION_HEADER, WORKERD_SHIM_VERSION);\n return response;\n } catch {\n // Immutable headers. Fall through and rebuild.\n }\n\n try {\n // A WebSocket upgrade carries the socket rather than a body and cannot\n // survive being rebuilt.\n if (hasWebSocket(response) || response.status === 101) {\n return response;\n }\n const rebuilt = new Response(response.body, response);\n rebuilt.headers.set(WORKERD_SHIM_VERSION_HEADER, WORKERD_SHIM_VERSION);\n return rebuilt;\n } catch (error) {\n warnOnce(\n \"publish-shim-version\",\n \"Failed to publish the workerd shim version on the response.\",\n error,\n );\n return response;\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAeA,MAAa,uCACX,aACa;AACb,KAAI;AACF,WAAS,QAAQ,IAAI,6BAA6B,qBAAqB;AACvE,SAAO;SACD;AAIR,KAAI;AAGF,MAAI,aAAa,SAAS,IAAI,SAAS,WAAW,IAChD,QAAO;EAET,MAAM,UAAU,IAAI,SAAS,SAAS,MAAM,SAAS;AACrD,UAAQ,QAAQ,IAAI,6BAA6B,qBAAqB;AACtE,SAAO;UACA,OAAO;AACd,WACE,wBACA,+DACA,MACD;AACD,SAAO","debugId":"1cb92f56-68e8-5791-b6c7-c8bca161b130"}
1
+ {"version":3,"file":"publish-shim-version.js","names":[],"sources":["../src/publish-shim-version.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { hasWebSocket } from \"./outbound-capture\";\nimport { WORKERD_SHIM_VERSION_HEADER } from \"./protocol\";\nimport { WORKERD_SHIM_VERSION } from \"./version\";\n\n/**\n * Stamps this shim's npm package version on the response the browser is about\n * to receive, so the replay runner can tell which bundled shim produced the\n * After screenshots.\n *\n * Returns the response to send, which is not always the one passed in: a\n * `Response` handed back by `fetch` or by an assets binding has immutable\n * headers, and the only way to add one is to rebuild around the same body.\n * Best-effort throughout — a recorder must never break the customer's app.\n */\nexport const publishWorkerdShimVersionOnResponse = (\n response: Response,\n): Response => {\n try {\n response.headers.set(WORKERD_SHIM_VERSION_HEADER, WORKERD_SHIM_VERSION);\n return response;\n } catch {\n // Immutable headers. Fall through and rebuild.\n }\n\n try {\n // A WebSocket upgrade carries the socket rather than a body and cannot\n // survive being rebuilt.\n if (hasWebSocket(response) || response.status === 101) {\n return response;\n }\n const rebuilt = new Response(response.body, response);\n rebuilt.headers.set(WORKERD_SHIM_VERSION_HEADER, WORKERD_SHIM_VERSION);\n return rebuilt;\n } catch (error) {\n warnOnce(\n \"publish-shim-version\",\n \"Failed to publish the workerd shim version on the response.\",\n error,\n );\n return response;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,uCACX,aACa;AACb,KAAI;AACF,WAAS,QAAQ,IAAI,6BAA6B,qBAAqB;AACvE,SAAO;SACD;AAIR,KAAI;AAGF,MAAI,aAAa,SAAS,IAAI,SAAS,WAAW,IAChD,QAAO;EAET,MAAM,UAAU,IAAI,SAAS,SAAS,MAAM,SAAS;AACrD,UAAQ,QAAQ,IAAI,6BAA6B,qBAAqB;AACtE,SAAO;UACA,OAAO;AACd,WACE,wBACA,+DACA,MACD;AACD,SAAO"}
@@ -1,7 +1,5 @@
1
1
  //#region src/redact-body.ts
2
2
  /** Replacement for a redacted value. Matches the Node recorder's redaction marker. */
3
-
4
- !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]="c9ea8914-5f33-5a57-a950-20eae083e1d7")}catch(e){}}();
5
3
  const STR_REDACTED = "REDACTED";
6
4
  const secretKeys = new Set([
7
5
  "accesstoken",
@@ -49,5 +47,4 @@ const redactValue = (value) => {
49
47
  //#endregion
50
48
  export { STR_REDACTED, redactRequestBody };
51
49
 
52
- //# sourceMappingURL=redact-body.js.map
53
- //# debugId=c9ea8914-5f33-5a57-a950-20eae083e1d7
50
+ //# sourceMappingURL=redact-body.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"redact-body.js","sources":["../src/redact-body.ts"],"sourcesContent":["/** Replacement for a redacted value. Matches the Node recorder's redaction marker. */\nexport const STR_REDACTED = \"REDACTED\";\n\n/**\n * Object keys whose values are replaced before a captured request body leaves the worker.\n *\n * Request bodies are captured verbatim, and plenty of APIs carry a credential in the body\n * rather than a header — an OAuth2 token exchange, or a feature-flag resolver that takes its\n * client secret as a JSON field. Header redaction (an allow-list of two) does nothing for\n * those, so without this the credential would be persisted in the recorded span.\n *\n * Compared case-insensitively, ignoring `_` and `-`, so `clientSecret`, `client_secret` and\n * `CLIENT-SECRET` all match one entry.\n */\nconst SECRET_KEYS = [\n \"accesstoken\",\n \"apikey\",\n \"authorization\",\n \"clientsecret\",\n \"credential\",\n \"idtoken\",\n \"password\",\n \"privatekey\",\n \"refreshtoken\",\n \"secret\",\n \"token\",\n] as const;\n\nconst secretKeys = new Set<string>(SECRET_KEYS);\n\nconst normalizeKey = (key: string): string =>\n key.toLowerCase().replace(/[_-]/g, \"\");\n\nconst isSecretKey = (key: string): boolean => secretKeys.has(normalizeKey(key));\n\n/**\n * Redacts secret-looking fields from a captured request body, returning the body unchanged\n * if it is not JSON.\n *\n * Applied to request bodies only. Response bodies must stay byte-exact: replay serves them\n * back to the app, so redacting one would corrupt what the app receives. Request bodies are\n * only ever used to key a lookup, and because the same function runs on both the record and\n * the replay side the keys still agree.\n *\n * Never throws — a body that cannot be parsed or re-serialized is returned as-is, which is\n * no worse than today's behaviour.\n */\nexport const redactRequestBody = (body: string): string => {\n if (body.length === 0) {\n return body;\n }\n try {\n const parsed: unknown = JSON.parse(body);\n const redacted = redactValue(parsed);\n const serialized = JSON.stringify(redacted);\n return serialized ?? body;\n } catch {\n // Not JSON (form-encoded, protobuf, plain text) — left alone rather than mangled.\n return body;\n }\n};\n\nconst redactValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n result[key] = isSecretKey(key) ? STR_REDACTED : redactValue(nested);\n }\n return result;\n};\n"],"names":[],"mappings":";;;;AACA,MAAa,eAAe;AA2B5B,MAAM,aAAa,IAAI,IAAY;CAbjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAG4C,CAAC;AAE/C,MAAM,gBAAgB,QACpB,IAAI,aAAa,CAAC,QAAQ,SAAS,GAAG;AAExC,MAAM,eAAe,QAAyB,WAAW,IAAI,aAAa,IAAI,CAAC;;;;;;;;;;;;;AAc/E,MAAa,qBAAqB,SAAyB;AACzD,KAAI,KAAK,WAAW,EAClB,QAAO;AAET,KAAI;EAEF,MAAM,WAAW,YADO,KAAK,MAAM,KACA,CAAC;AAEpC,SADmB,KAAK,UAAU,SACjB,IAAI;SACf;AAEN,SAAO;;;AAIX,MAAM,eAAe,UAA4B;AAC/C,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,IAAI,YAAY;AAE/B,KAAI,UAAU,QAAQ,OAAO,UAAU,SACrC,QAAO;CAET,MAAM,SAAkC,EAAE;AAC1C,MAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,MAAM,CAC/C,QAAO,OAAO,YAAY,IAAI,GAAG,eAAe,YAAY,OAAO;AAErE,QAAO","debugId":"c9ea8914-5f33-5a57-a950-20eae083e1d7"}
1
+ {"version":3,"file":"redact-body.js","names":[],"sources":["../src/redact-body.ts"],"sourcesContent":["/** Replacement for a redacted value. Matches the Node recorder's redaction marker. */\nexport const STR_REDACTED = \"REDACTED\";\n\n/**\n * Object keys whose values are replaced before a captured request body leaves the worker.\n *\n * Request bodies are captured verbatim, and plenty of APIs carry a credential in the body\n * rather than a header — an OAuth2 token exchange, or a feature-flag resolver that takes its\n * client secret as a JSON field. Header redaction (an allow-list of two) does nothing for\n * those, so without this the credential would be persisted in the recorded span.\n *\n * Compared case-insensitively, ignoring `_` and `-`, so `clientSecret`, `client_secret` and\n * `CLIENT-SECRET` all match one entry.\n */\nconst SECRET_KEYS = [\n \"accesstoken\",\n \"apikey\",\n \"authorization\",\n \"clientsecret\",\n \"credential\",\n \"idtoken\",\n \"password\",\n \"privatekey\",\n \"refreshtoken\",\n \"secret\",\n \"token\",\n] as const;\n\nconst secretKeys = new Set<string>(SECRET_KEYS);\n\nconst normalizeKey = (key: string): string =>\n key.toLowerCase().replace(/[_-]/g, \"\");\n\nconst isSecretKey = (key: string): boolean => secretKeys.has(normalizeKey(key));\n\n/**\n * Redacts secret-looking fields from a captured request body, returning the body unchanged\n * if it is not JSON.\n *\n * Applied to request bodies only. Response bodies must stay byte-exact: replay serves them\n * back to the app, so redacting one would corrupt what the app receives. Request bodies are\n * only ever used to key a lookup, and because the same function runs on both the record and\n * the replay side the keys still agree.\n *\n * Never throws — a body that cannot be parsed or re-serialized is returned as-is, which is\n * no worse than today's behaviour.\n */\nexport const redactRequestBody = (body: string): string => {\n if (body.length === 0) {\n return body;\n }\n try {\n const parsed: unknown = JSON.parse(body);\n const redacted = redactValue(parsed);\n const serialized = JSON.stringify(redacted);\n return serialized ?? body;\n } catch {\n // Not JSON (form-encoded, protobuf, plain text) — left alone rather than mangled.\n return body;\n }\n};\n\nconst redactValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n result[key] = isSecretKey(key) ? STR_REDACTED : redactValue(nested);\n }\n return result;\n};\n"],"mappings":";;AACA,MAAa,eAAe;AA2B5B,MAAM,aAAa,IAAI,IAAY;CAbjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAG4C,CAAC;AAE/C,MAAM,gBAAgB,QACpB,IAAI,aAAa,CAAC,QAAQ,SAAS,GAAG;AAExC,MAAM,eAAe,QAAyB,WAAW,IAAI,aAAa,IAAI,CAAC;;;;;;;;;;;;;AAc/E,MAAa,qBAAqB,SAAyB;AACzD,KAAI,KAAK,WAAW,EAClB,QAAO;AAET,KAAI;EAEF,MAAM,WAAW,YADO,KAAK,MAAM,KACA,CAAC;AAEpC,SADmB,KAAK,UAAU,SACjB,IAAI;SACf;AAEN,SAAO;;;AAIX,MAAM,eAAe,UAA4B;AAC/C,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,IAAI,YAAY;AAE/B,KAAI,UAAU,QAAQ,OAAO,UAAU,SACrC,QAAO;CAET,MAAM,SAAkC,EAAE;AAC1C,MAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,MAAM,CAC/C,QAAO,OAAO,YAAY,IAAI,GAAG,eAAe,YAAY,OAAO;AAErE,QAAO"}
@@ -1,5 +1,3 @@
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]="db9354dc-05d0-51c9-a548-f693044b9cc5")}catch(e){}}();
3
1
  import { warn, warnOnce } from "./log.js";
4
2
  import { readRequestBodyWithCap } from "./body-capture.js";
5
3
  import { METICULOUS_PASSTHROUGH_HEADER } from "./protocol.js";
@@ -130,5 +128,4 @@ const buildMockResponse = (mock) => {
130
128
  //#endregion
131
129
  export { replayOutboundCall };
132
130
 
133
- //# sourceMappingURL=replay-fetch.js.map
134
- //# debugId=db9354dc-05d0-51c9-a548-f693044b9cc5
131
+ //# sourceMappingURL=replay-fetch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"replay-fetch.js","sources":["../src/replay-fetch.ts"],"sourcesContent":["import { readRequestBodyWithCap } from \"./body-capture\";\nimport type { RequestReplayContext } from \"./context\";\nimport { warn, warnOnce } from \"./log\";\nimport { getOriginalFetch } from \"./original-fetch\";\nimport {\n METICULOUS_PASSTHROUGH_HEADER,\n type OutboundFetchLookupRequest,\n} from \"./protocol\";\nimport { postOutboundFetchLookup } from \"./sidecar-client\";\n\n/**\n * Serves a recorded response for an outbound call, or fails it.\n *\n * The mirror image of `captureOutboundCall`: recording tees a call that happens anyway,\n * whereas replay decides first and only then calls — so the sidecar sits in the request\n * path here.\n *\n * Replay is hermetic: a call the recording does not cover must not silently reach the real\n * service, since that turns a replay into live traffic against real credentials and hides\n * the gap in the recording behind a response no base replay will reproduce. So anything we\n * cannot serve from the recording — a miss, a call the sidecar cannot look up, an\n * unreachable sidecar, a mock that cannot be represented, or an outcome this shim does not\n * recognise — throws, matching the Node recorder's http/undici mocks.\n *\n * The only way out is an explicit `meticulous-passthrough: true` header on the request: a\n * call the customer has marked as one that must reach the real service. A failure to stub is\n * never treated as such a mark.\n */\nexport const replayOutboundCall = async (\n ctx: RequestReplayContext,\n request: Request,\n invoke: (request: Request) => Promise<Response>,\n): Promise<Response> => {\n if (hasPassthroughHeader(request)) {\n return invoke(request);\n }\n\n let lookup: OutboundFetchLookupRequest;\n try {\n // Read the clone and pass the original through untouched, mirroring the record path.\n // The sidecar hashes what we send here, and it was captured by the same\n // readRequestBodyWithCap the recorder used (redaction included), so the hashes on both\n // sides derive from byte-identical input.\n const requestBody = request.body\n ? await readRequestBodyWithCap(request.clone().body).catch(\n () => undefined,\n )\n : undefined;\n lookup = {\n frontendSessionId: ctx.frontendSessionId,\n replayId: ctx.replayId,\n method: request.method,\n url: request.url,\n ...(ctx.virtualTimeMs !== undefined\n ? { virtualTimeMs: ctx.virtualTimeMs }\n : {}),\n ...(requestBody !== undefined ? { requestBody } : {}),\n };\n } catch (error) {\n // Without a lookup there is nothing to serve, and passing through would be exactly the\n // silent real call this path exists to prevent.\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n \"could not prepare a mock lookup\",\n error,\n );\n }\n\n const result = await postOutboundFetchLookup(\n getOriginalFetch(),\n ctx.sidecarUrl,\n lookup,\n );\n if (result === undefined) {\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n \"the replay sidecar did not answer a mock lookup\",\n );\n }\n if (result.outcome === \"mock\") {\n const mocked = buildMockResponse(result);\n if (mocked === undefined) {\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n `the recorded response (status ${result.statusCode}) cannot be represented`,\n );\n }\n return mocked;\n }\n // Every other outcome is a failure to stub — a miss (`no-mock`) or an outcome this shim\n // does not recognise (e.g. a legacy `passthrough`). None may reach the real service, so we\n // fail the request; the only path to a live call is the explicit passthrough header\n // handled above.\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n describeUnservedOutcome(result.outcome),\n );\n};\n\nconst describeUnservedOutcome = (outcome: string): string =>\n outcome === \"no-mock\"\n ? \"no recorded response\"\n : `an unrecognised sidecar outcome (${outcome})`;\n\nconst hasPassthroughHeader = (request: Request): boolean => {\n try {\n return request.headers.get(METICULOUS_PASSTHROUGH_HEADER) === \"true\";\n } catch {\n return false;\n }\n};\n\n/**\n * Builds — and logs — the error the app sees for a call replay cannot serve. Deliberately\n * names the shim and the session so an app-side stack trace is enough to tell a replay gap\n * from a real bug, and logs as well because an app that catches its own fetch errors would\n * otherwise swallow the only signal.\n *\n * The query string is left out on purpose — it routinely carries API keys, and the sidecar\n * logs the full path anyway.\n */\nconst buildReplayError = (\n request: Request,\n frontendSessionId: string,\n reason: string,\n cause?: unknown,\n): Error => {\n const error = new Error(\n `[backend-recorder] workerd replay: ${reason} for ${describeRequest(request)} (session ${frontendSessionId}). Set the \"${METICULOUS_PASSTHROUGH_HEADER}: true\" header on this request if it must reach the real service during replay.`,\n );\n if (cause !== undefined) {\n // `cause` in the constructor options is not universally available in workerd builds.\n (error as { cause?: unknown }).cause = cause;\n }\n warn(error.message);\n return error;\n};\n\nconst describeRequest = (request: Request): string => {\n let method = \"GET\";\n let url = \"\";\n try {\n method = request.method;\n url = request.url;\n } catch {\n return method;\n }\n try {\n const parsed = new URL(url);\n return `${method} ${parsed.origin}${parsed.pathname}`;\n } catch {\n return `${method} ${url}`;\n }\n};\n\n// Recorded bodies are already decoded and may have been truncated, so the recorded framing\n// headers no longer describe them; the Response constructor recomputes what it needs.\nconst HEADERS_TO_DROP = new Set([\n \"content-encoding\",\n \"content-length\",\n \"transfer-encoding\",\n]);\n\n// Statuses the Response constructor refuses to pair with a body.\nconst NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);\n\n/**\n * Turns a recorded response into a real one, or undefined if it cannot be represented (the\n * constructor throws a RangeError on an out-of-range status, or a body on a null-body\n * status), in which case the caller fails the request.\n *\n * Note recorded headers are limited to CAPTURED_HEADERS, so a mocked response carries\n * essentially just content-type. In particular it can never set cookies — fine for the API\n * calls this path serves, but a real limitation for a backend that authenticates that way.\n */\nconst buildMockResponse = (mock: {\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n}): Response | undefined => {\n try {\n const headers = new Headers();\n for (const [name, value] of Object.entries(mock.headers)) {\n if (HEADERS_TO_DROP.has(name.toLowerCase())) {\n continue;\n }\n try {\n headers.set(name, value);\n } catch {\n // Skip a header name/value the runtime rejects rather than losing the whole mock.\n }\n }\n const body = NULL_BODY_STATUSES.has(mock.statusCode) ? null : mock.body;\n return new Response(body, { status: mock.statusCode, headers });\n } catch (error) {\n warnOnce(\n \"replay-mock-response\",\n \"Could not construct a mocked response.\",\n error,\n );\n return undefined;\n }\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,qBAAqB,OAChC,KACA,SACA,WACsB;AACtB,KAAI,qBAAqB,QAAQ,CAC/B,QAAO,OAAO,QAAQ;CAGxB,IAAI;AACJ,KAAI;EAKF,MAAM,cAAc,QAAQ,OACxB,MAAM,uBAAuB,QAAQ,OAAO,CAAC,KAAK,CAAC,YAC3C,KAAA,EACP,GACD,KAAA;AACJ,WAAS;GACP,mBAAmB,IAAI;GACvB,UAAU,IAAI;GACd,QAAQ,QAAQ;GAChB,KAAK,QAAQ;GACb,GAAI,IAAI,kBAAkB,KAAA,IACtB,EAAE,eAAe,IAAI,eAAe,GACpC,EAAE;GACN,GAAI,gBAAgB,KAAA,IAAY,EAAE,aAAa,GAAG,EAAE;GACrD;UACM,OAAO;AAGd,QAAM,iBACJ,SACA,IAAI,mBACJ,mCACA,MACD;;CAGH,MAAM,SAAS,MAAM,wBACnB,kBAAkB,EAClB,IAAI,YACJ,OACD;AACD,KAAI,WAAW,KAAA,EACb,OAAM,iBACJ,SACA,IAAI,mBACJ,kDACD;AAEH,KAAI,OAAO,YAAY,QAAQ;EAC7B,MAAM,SAAS,kBAAkB,OAAO;AACxC,MAAI,WAAW,KAAA,EACb,OAAM,iBACJ,SACA,IAAI,mBACJ,iCAAiC,OAAO,WAAW,yBACpD;AAEH,SAAO;;AAMT,OAAM,iBACJ,SACA,IAAI,mBACJ,wBAAwB,OAAO,QAAQ,CACxC;;AAGH,MAAM,2BAA2B,YAC/B,YAAY,YACR,yBACA,oCAAoC,QAAQ;AAElD,MAAM,wBAAwB,YAA8B;AAC1D,KAAI;AACF,SAAO,QAAQ,QAAQ,IAAI,8BAA8B,KAAK;SACxD;AACN,SAAO;;;;;;;;;;;;AAaX,MAAM,oBACJ,SACA,mBACA,QACA,UACU;CACV,MAAM,wBAAQ,IAAI,MAChB,sCAAsC,OAAO,OAAO,gBAAgB,QAAQ,CAAC,YAAY,kBAAkB,cAAc,8BAA8B,iFACxJ;AACD,KAAI,UAAU,KAAA,EAEX,OAA8B,QAAQ;AAEzC,MAAK,MAAM,QAAQ;AACnB,QAAO;;AAGT,MAAM,mBAAmB,YAA6B;CACpD,IAAI,SAAS;CACb,IAAI,MAAM;AACV,KAAI;AACF,WAAS,QAAQ;AACjB,QAAM,QAAQ;SACR;AACN,SAAO;;AAET,KAAI;EACF,MAAM,SAAS,IAAI,IAAI,IAAI;AAC3B,SAAO,GAAG,OAAO,GAAG,OAAO,SAAS,OAAO;SACrC;AACN,SAAO,GAAG,OAAO,GAAG;;;AAMxB,MAAM,kBAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACD,CAAC;AAGF,MAAM,qBAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAI,CAAC;;;;;;;;;;AAWxD,MAAM,qBAAqB,SAIC;AAC1B,KAAI;EACF,MAAM,UAAU,IAAI,SAAS;AAC7B,OAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,QAAQ,EAAE;AACxD,OAAI,gBAAgB,IAAI,KAAK,aAAa,CAAC,CACzC;AAEF,OAAI;AACF,YAAQ,IAAI,MAAM,MAAM;WAClB;;EAIV,MAAM,OAAO,mBAAmB,IAAI,KAAK,WAAW,GAAG,OAAO,KAAK;AACnE,SAAO,IAAI,SAAS,MAAM;GAAE,QAAQ,KAAK;GAAY;GAAS,CAAC;UACxD,OAAO;AACd,WACE,wBACA,0CACA,MACD;AACD","debugId":"db9354dc-05d0-51c9-a548-f693044b9cc5"}
1
+ {"version":3,"file":"replay-fetch.js","names":[],"sources":["../src/replay-fetch.ts"],"sourcesContent":["import { readRequestBodyWithCap } from \"./body-capture\";\nimport type { RequestReplayContext } from \"./context\";\nimport { warn, warnOnce } from \"./log\";\nimport { getOriginalFetch } from \"./original-fetch\";\nimport {\n METICULOUS_PASSTHROUGH_HEADER,\n type OutboundFetchLookupRequest,\n} from \"./protocol\";\nimport { postOutboundFetchLookup } from \"./sidecar-client\";\n\n/**\n * Serves a recorded response for an outbound call, or fails it.\n *\n * The mirror image of `captureOutboundCall`: recording tees a call that happens anyway,\n * whereas replay decides first and only then calls — so the sidecar sits in the request\n * path here.\n *\n * Replay is hermetic: a call the recording does not cover must not silently reach the real\n * service, since that turns a replay into live traffic against real credentials and hides\n * the gap in the recording behind a response no base replay will reproduce. So anything we\n * cannot serve from the recording — a miss, a call the sidecar cannot look up, an\n * unreachable sidecar, a mock that cannot be represented, or an outcome this shim does not\n * recognise — throws, matching the Node recorder's http/undici mocks.\n *\n * The only way out is an explicit `meticulous-passthrough: true` header on the request: a\n * call the customer has marked as one that must reach the real service. A failure to stub is\n * never treated as such a mark.\n */\nexport const replayOutboundCall = async (\n ctx: RequestReplayContext,\n request: Request,\n invoke: (request: Request) => Promise<Response>,\n): Promise<Response> => {\n if (hasPassthroughHeader(request)) {\n return invoke(request);\n }\n\n let lookup: OutboundFetchLookupRequest;\n try {\n // Read the clone and pass the original through untouched, mirroring the record path.\n // The sidecar hashes what we send here, and it was captured by the same\n // readRequestBodyWithCap the recorder used (redaction included), so the hashes on both\n // sides derive from byte-identical input.\n const requestBody = request.body\n ? await readRequestBodyWithCap(request.clone().body).catch(\n () => undefined,\n )\n : undefined;\n lookup = {\n frontendSessionId: ctx.frontendSessionId,\n replayId: ctx.replayId,\n method: request.method,\n url: request.url,\n ...(ctx.virtualTimeMs !== undefined\n ? { virtualTimeMs: ctx.virtualTimeMs }\n : {}),\n ...(requestBody !== undefined ? { requestBody } : {}),\n };\n } catch (error) {\n // Without a lookup there is nothing to serve, and passing through would be exactly the\n // silent real call this path exists to prevent.\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n \"could not prepare a mock lookup\",\n error,\n );\n }\n\n const result = await postOutboundFetchLookup(\n getOriginalFetch(),\n ctx.sidecarUrl,\n lookup,\n );\n if (result === undefined) {\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n \"the replay sidecar did not answer a mock lookup\",\n );\n }\n if (result.outcome === \"mock\") {\n const mocked = buildMockResponse(result);\n if (mocked === undefined) {\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n `the recorded response (status ${result.statusCode}) cannot be represented`,\n );\n }\n return mocked;\n }\n // Every other outcome is a failure to stub — a miss (`no-mock`) or an outcome this shim\n // does not recognise (e.g. a legacy `passthrough`). None may reach the real service, so we\n // fail the request; the only path to a live call is the explicit passthrough header\n // handled above.\n throw buildReplayError(\n request,\n ctx.frontendSessionId,\n describeUnservedOutcome(result.outcome),\n );\n};\n\nconst describeUnservedOutcome = (outcome: string): string =>\n outcome === \"no-mock\"\n ? \"no recorded response\"\n : `an unrecognised sidecar outcome (${outcome})`;\n\nconst hasPassthroughHeader = (request: Request): boolean => {\n try {\n return request.headers.get(METICULOUS_PASSTHROUGH_HEADER) === \"true\";\n } catch {\n return false;\n }\n};\n\n/**\n * Builds — and logs — the error the app sees for a call replay cannot serve. Deliberately\n * names the shim and the session so an app-side stack trace is enough to tell a replay gap\n * from a real bug, and logs as well because an app that catches its own fetch errors would\n * otherwise swallow the only signal.\n *\n * The query string is left out on purpose — it routinely carries API keys, and the sidecar\n * logs the full path anyway.\n */\nconst buildReplayError = (\n request: Request,\n frontendSessionId: string,\n reason: string,\n cause?: unknown,\n): Error => {\n const error = new Error(\n `[backend-recorder] workerd replay: ${reason} for ${describeRequest(request)} (session ${frontendSessionId}). Set the \"${METICULOUS_PASSTHROUGH_HEADER}: true\" header on this request if it must reach the real service during replay.`,\n );\n if (cause !== undefined) {\n // `cause` in the constructor options is not universally available in workerd builds.\n (error as { cause?: unknown }).cause = cause;\n }\n warn(error.message);\n return error;\n};\n\nconst describeRequest = (request: Request): string => {\n let method = \"GET\";\n let url = \"\";\n try {\n method = request.method;\n url = request.url;\n } catch {\n return method;\n }\n try {\n const parsed = new URL(url);\n return `${method} ${parsed.origin}${parsed.pathname}`;\n } catch {\n return `${method} ${url}`;\n }\n};\n\n// Recorded bodies are already decoded and may have been truncated, so the recorded framing\n// headers no longer describe them; the Response constructor recomputes what it needs.\nconst HEADERS_TO_DROP = new Set([\n \"content-encoding\",\n \"content-length\",\n \"transfer-encoding\",\n]);\n\n// Statuses the Response constructor refuses to pair with a body.\nconst NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);\n\n/**\n * Turns a recorded response into a real one, or undefined if it cannot be represented (the\n * constructor throws a RangeError on an out-of-range status, or a body on a null-body\n * status), in which case the caller fails the request.\n *\n * Note recorded headers are limited to CAPTURED_HEADERS, so a mocked response carries\n * essentially just content-type. In particular it can never set cookies — fine for the API\n * calls this path serves, but a real limitation for a backend that authenticates that way.\n */\nconst buildMockResponse = (mock: {\n statusCode: number;\n body: string;\n headers: Record<string, string>;\n}): Response | undefined => {\n try {\n const headers = new Headers();\n for (const [name, value] of Object.entries(mock.headers)) {\n if (HEADERS_TO_DROP.has(name.toLowerCase())) {\n continue;\n }\n try {\n headers.set(name, value);\n } catch {\n // Skip a header name/value the runtime rejects rather than losing the whole mock.\n }\n }\n const body = NULL_BODY_STATUSES.has(mock.statusCode) ? null : mock.body;\n return new Response(body, { status: mock.statusCode, headers });\n } catch (error) {\n warnOnce(\n \"replay-mock-response\",\n \"Could not construct a mocked response.\",\n error,\n );\n return undefined;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,qBAAqB,OAChC,KACA,SACA,WACsB;AACtB,KAAI,qBAAqB,QAAQ,CAC/B,QAAO,OAAO,QAAQ;CAGxB,IAAI;AACJ,KAAI;EAKF,MAAM,cAAc,QAAQ,OACxB,MAAM,uBAAuB,QAAQ,OAAO,CAAC,KAAK,CAAC,YAC3C,KAAA,EACP,GACD,KAAA;AACJ,WAAS;GACP,mBAAmB,IAAI;GACvB,UAAU,IAAI;GACd,QAAQ,QAAQ;GAChB,KAAK,QAAQ;GACb,GAAI,IAAI,kBAAkB,KAAA,IACtB,EAAE,eAAe,IAAI,eAAe,GACpC,EAAE;GACN,GAAI,gBAAgB,KAAA,IAAY,EAAE,aAAa,GAAG,EAAE;GACrD;UACM,OAAO;AAGd,QAAM,iBACJ,SACA,IAAI,mBACJ,mCACA,MACD;;CAGH,MAAM,SAAS,MAAM,wBACnB,kBAAkB,EAClB,IAAI,YACJ,OACD;AACD,KAAI,WAAW,KAAA,EACb,OAAM,iBACJ,SACA,IAAI,mBACJ,kDACD;AAEH,KAAI,OAAO,YAAY,QAAQ;EAC7B,MAAM,SAAS,kBAAkB,OAAO;AACxC,MAAI,WAAW,KAAA,EACb,OAAM,iBACJ,SACA,IAAI,mBACJ,iCAAiC,OAAO,WAAW,yBACpD;AAEH,SAAO;;AAMT,OAAM,iBACJ,SACA,IAAI,mBACJ,wBAAwB,OAAO,QAAQ,CACxC;;AAGH,MAAM,2BAA2B,YAC/B,YAAY,YACR,yBACA,oCAAoC,QAAQ;AAElD,MAAM,wBAAwB,YAA8B;AAC1D,KAAI;AACF,SAAO,QAAQ,QAAQ,IAAI,8BAA8B,KAAK;SACxD;AACN,SAAO;;;;;;;;;;;;AAaX,MAAM,oBACJ,SACA,mBACA,QACA,UACU;CACV,MAAM,wBAAQ,IAAI,MAChB,sCAAsC,OAAO,OAAO,gBAAgB,QAAQ,CAAC,YAAY,kBAAkB,cAAc,8BAA8B,iFACxJ;AACD,KAAI,UAAU,KAAA,EAEX,OAA8B,QAAQ;AAEzC,MAAK,MAAM,QAAQ;AACnB,QAAO;;AAGT,MAAM,mBAAmB,YAA6B;CACpD,IAAI,SAAS;CACb,IAAI,MAAM;AACV,KAAI;AACF,WAAS,QAAQ;AACjB,QAAM,QAAQ;SACR;AACN,SAAO;;AAET,KAAI;EACF,MAAM,SAAS,IAAI,IAAI,IAAI;AAC3B,SAAO,GAAG,OAAO,GAAG,OAAO,SAAS,OAAO;SACrC;AACN,SAAO,GAAG,OAAO,GAAG;;;AAMxB,MAAM,kBAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACD,CAAC;AAGF,MAAM,qBAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAI,CAAC;;;;;;;;;;AAWxD,MAAM,qBAAqB,SAIC;AAC1B,KAAI;EACF,MAAM,UAAU,IAAI,SAAS;AAC7B,OAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,QAAQ,EAAE;AACxD,OAAI,gBAAgB,IAAI,KAAK,aAAa,CAAC,CACzC;AAEF,OAAI;AACF,YAAQ,IAAI,MAAM,MAAM;WAClB;;EAIV,MAAM,OAAO,mBAAmB,IAAI,KAAK,WAAW,GAAG,OAAO,KAAK;AACnE,SAAO,IAAI,SAAS,MAAM;GAAE,QAAQ,KAAK;GAAY;GAAS,CAAC;UACxD,OAAO;AACd,WACE,wBACA,0CACA,MACD;AACD"}
@@ -1,5 +1,3 @@
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]="962faa5b-f3e8-548c-be10-1e341f1f56bd")}catch(e){}}();
3
1
  import { requestCaptureContext } from "./context.js";
4
2
  //#region src/replay-log-tagging.ts
5
3
  const CONSOLE_METHODS = [
@@ -53,5 +51,4 @@ const installReplayLogTagging = (methods = console, holder = globalThis) => {
53
51
  //#endregion
54
52
  export { installReplayLogTagging };
55
53
 
56
- //# sourceMappingURL=replay-log-tagging.js.map
57
- //# debugId=962faa5b-f3e8-548c-be10-1e341f1f56bd
54
+ //# sourceMappingURL=replay-log-tagging.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"replay-log-tagging.js","sources":["../src/replay-log-tagging.ts"],"sourcesContent":["import { requestCaptureContext } from \"./context\";\n\ntype ConsoleLogMethod = (...args: unknown[]) => void;\n\nconst CONSOLE_METHODS = [\n \"debug\",\n \"error\",\n \"info\",\n \"log\",\n \"trace\",\n \"warn\",\n] as const;\n\ntype ConsoleMethodName = (typeof CONSOLE_METHODS)[number];\n\nconst CONSOLE_TAGGING_INSTALLED = Symbol.for(\n \"meticulous.workerd.consoleReplayTaggingInstalled\",\n);\n\n// This literal is part of the persisted log wire format. Keep it pinned here\n// rather than deriving it from the HTTP header, whose name can change\n// independently of logs that have already been written to S3.\nconst REPLAY_ID_LOG_TAG_NAME = \"meticulous-replay-id\";\n\nconst formatReplayIdLogTag = (replayId: string): string =>\n `[${REPLAY_ID_LOG_TAG_NAME}:${replayId}] `;\n\nconst tagContinuationLines = (value: string, prefix: string): string =>\n value.replace(/\\n(?=.)/g, `\\n${prefix}`);\n\nconst prepareConsoleArgument = (value: unknown, prefix: string): unknown => {\n if (typeof value === \"string\") {\n return tagContinuationLines(value, prefix);\n }\n if (value instanceof Error) {\n return tagContinuationLines(value.stack ?? value.message, prefix);\n }\n return value;\n};\n\n/**\n * Adds the active request's replay marker. Keeping a string first argument in\n * place preserves formatting such as `console.log(\"user=%s\", id)`. Embedded\n * newlines in strings and Error stacks are tagged too, since container runtimes\n * may emit their continuation lines as separate log records.\n */\nexport const createReplayTaggedConsoleMethod =\n (original: ConsoleLogMethod): ConsoleLogMethod =>\n (...args: unknown[]): void => {\n let outputArgs = args;\n try {\n const ctx = requestCaptureContext.getStore();\n if (ctx?.mode === \"replay\") {\n const prefix = formatReplayIdLogTag(ctx.replayId);\n const preparedArgs = args.map((arg) =>\n prepareConsoleArgument(arg, prefix),\n );\n outputArgs =\n typeof preparedArgs[0] === \"string\"\n ? [prefix + preparedArgs[0], ...preparedArgs.slice(1)]\n : [prefix, ...preparedArgs];\n }\n } catch {\n // Log tagging must never interfere with the customer's logger. The\n // original call below still receives its untouched arguments.\n }\n original(...outputArgs);\n };\n\n/**\n * Patches Workerd's output-producing console methods once. Outside a replayed\n * request the wrappers are transparent; inside one they resolve the replay id\n * from Workerd's request-scoped AsyncLocalStorage, so concurrent replays cannot\n * label each other's output.\n */\nexport const installReplayLogTagging = (\n methods = console as unknown as Record<ConsoleMethodName, ConsoleLogMethod>,\n holder = globalThis as typeof globalThis & {\n [CONSOLE_TAGGING_INSTALLED]?: boolean;\n },\n): void => {\n if (holder[CONSOLE_TAGGING_INSTALLED]) {\n return;\n }\n holder[CONSOLE_TAGGING_INSTALLED] = true;\n\n for (const method of CONSOLE_METHODS) {\n try {\n methods[method] = createReplayTaggedConsoleMethod(\n methods[method].bind(methods),\n );\n } catch {\n // A runtime may expose a non-writable console method. Keep the remaining\n // methods useful rather than making replay initialization fail.\n }\n }\n};\n"],"names":[],"mappings":";;;;AAIA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACD;AAID,MAAM,4BAA4B,OAAO,IACvC,mDACD;AAKD,MAAM,yBAAyB;AAE/B,MAAM,wBAAwB,aAC5B,IAAI,uBAAuB,GAAG,SAAS;AAEzC,MAAM,wBAAwB,OAAe,WAC3C,MAAM,QAAQ,YAAY,KAAK,SAAS;AAE1C,MAAM,0BAA0B,OAAgB,WAA4B;AAC1E,KAAI,OAAO,UAAU,SACnB,QAAO,qBAAqB,OAAO,OAAO;AAE5C,KAAI,iBAAiB,MACnB,QAAO,qBAAqB,MAAM,SAAS,MAAM,SAAS,OAAO;AAEnE,QAAO;;;;;;;;AAST,MAAa,mCACV,cACA,GAAG,SAA0B;CAC5B,IAAI,aAAa;AACjB,KAAI;EACF,MAAM,MAAM,sBAAsB,UAAU;AAC5C,MAAI,KAAK,SAAS,UAAU;GAC1B,MAAM,SAAS,qBAAqB,IAAI,SAAS;GACjD,MAAM,eAAe,KAAK,KAAK,QAC7B,uBAAuB,KAAK,OAAO,CACpC;AACD,gBACE,OAAO,aAAa,OAAO,WACvB,CAAC,SAAS,aAAa,IAAI,GAAG,aAAa,MAAM,EAAE,CAAC,GACpD,CAAC,QAAQ,GAAG,aAAa;;SAE3B;AAIR,UAAS,GAAG,WAAW;;;;;;;;AAS3B,MAAa,2BACX,UAAU,SACV,SAAS,eAGA;AACT,KAAI,OAAO,2BACT;AAEF,QAAO,6BAA6B;AAEpC,MAAK,MAAM,UAAU,gBACnB,KAAI;AACF,UAAQ,UAAU,gCAChB,QAAQ,QAAQ,KAAK,QAAQ,CAC9B;SACK","debugId":"962faa5b-f3e8-548c-be10-1e341f1f56bd"}
1
+ {"version":3,"file":"replay-log-tagging.js","names":[],"sources":["../src/replay-log-tagging.ts"],"sourcesContent":["import { requestCaptureContext } from \"./context\";\n\ntype ConsoleLogMethod = (...args: unknown[]) => void;\n\nconst CONSOLE_METHODS = [\n \"debug\",\n \"error\",\n \"info\",\n \"log\",\n \"trace\",\n \"warn\",\n] as const;\n\ntype ConsoleMethodName = (typeof CONSOLE_METHODS)[number];\n\nconst CONSOLE_TAGGING_INSTALLED = Symbol.for(\n \"meticulous.workerd.consoleReplayTaggingInstalled\",\n);\n\n// This literal is part of the persisted log wire format. Keep it pinned here\n// rather than deriving it from the HTTP header, whose name can change\n// independently of logs that have already been written to S3.\nconst REPLAY_ID_LOG_TAG_NAME = \"meticulous-replay-id\";\n\nconst formatReplayIdLogTag = (replayId: string): string =>\n `[${REPLAY_ID_LOG_TAG_NAME}:${replayId}] `;\n\nconst tagContinuationLines = (value: string, prefix: string): string =>\n value.replace(/\\n(?=.)/g, `\\n${prefix}`);\n\nconst prepareConsoleArgument = (value: unknown, prefix: string): unknown => {\n if (typeof value === \"string\") {\n return tagContinuationLines(value, prefix);\n }\n if (value instanceof Error) {\n return tagContinuationLines(value.stack ?? value.message, prefix);\n }\n return value;\n};\n\n/**\n * Adds the active request's replay marker. Keeping a string first argument in\n * place preserves formatting such as `console.log(\"user=%s\", id)`. Embedded\n * newlines in strings and Error stacks are tagged too, since container runtimes\n * may emit their continuation lines as separate log records.\n */\nexport const createReplayTaggedConsoleMethod =\n (original: ConsoleLogMethod): ConsoleLogMethod =>\n (...args: unknown[]): void => {\n let outputArgs = args;\n try {\n const ctx = requestCaptureContext.getStore();\n if (ctx?.mode === \"replay\") {\n const prefix = formatReplayIdLogTag(ctx.replayId);\n const preparedArgs = args.map((arg) =>\n prepareConsoleArgument(arg, prefix),\n );\n outputArgs =\n typeof preparedArgs[0] === \"string\"\n ? [prefix + preparedArgs[0], ...preparedArgs.slice(1)]\n : [prefix, ...preparedArgs];\n }\n } catch {\n // Log tagging must never interfere with the customer's logger. The\n // original call below still receives its untouched arguments.\n }\n original(...outputArgs);\n };\n\n/**\n * Patches Workerd's output-producing console methods once. Outside a replayed\n * request the wrappers are transparent; inside one they resolve the replay id\n * from Workerd's request-scoped AsyncLocalStorage, so concurrent replays cannot\n * label each other's output.\n */\nexport const installReplayLogTagging = (\n methods = console as unknown as Record<ConsoleMethodName, ConsoleLogMethod>,\n holder = globalThis as typeof globalThis & {\n [CONSOLE_TAGGING_INSTALLED]?: boolean;\n },\n): void => {\n if (holder[CONSOLE_TAGGING_INSTALLED]) {\n return;\n }\n holder[CONSOLE_TAGGING_INSTALLED] = true;\n\n for (const method of CONSOLE_METHODS) {\n try {\n methods[method] = createReplayTaggedConsoleMethod(\n methods[method].bind(methods),\n );\n } catch {\n // A runtime may expose a non-writable console method. Keep the remaining\n // methods useful rather than making replay initialization fail.\n }\n }\n};\n"],"mappings":";;AAIA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACD;AAID,MAAM,4BAA4B,OAAO,IACvC,mDACD;AAKD,MAAM,yBAAyB;AAE/B,MAAM,wBAAwB,aAC5B,IAAI,uBAAuB,GAAG,SAAS;AAEzC,MAAM,wBAAwB,OAAe,WAC3C,MAAM,QAAQ,YAAY,KAAK,SAAS;AAE1C,MAAM,0BAA0B,OAAgB,WAA4B;AAC1E,KAAI,OAAO,UAAU,SACnB,QAAO,qBAAqB,OAAO,OAAO;AAE5C,KAAI,iBAAiB,MACnB,QAAO,qBAAqB,MAAM,SAAS,MAAM,SAAS,OAAO;AAEnE,QAAO;;;;;;;;AAST,MAAa,mCACV,cACA,GAAG,SAA0B;CAC5B,IAAI,aAAa;AACjB,KAAI;EACF,MAAM,MAAM,sBAAsB,UAAU;AAC5C,MAAI,KAAK,SAAS,UAAU;GAC1B,MAAM,SAAS,qBAAqB,IAAI,SAAS;GACjD,MAAM,eAAe,KAAK,KAAK,QAC7B,uBAAuB,KAAK,OAAO,CACpC;AACD,gBACE,OAAO,aAAa,OAAO,WACvB,CAAC,SAAS,aAAa,IAAI,GAAG,aAAa,MAAM,EAAE,CAAC,GACpD,CAAC,QAAQ,GAAG,aAAa;;SAE3B;AAIR,UAAS,GAAG,WAAW;;;;;;;;AAS3B,MAAa,2BACX,UAAU,SACV,SAAS,eAGA;AACT,KAAI,OAAO,2BACT;AAEF,QAAO,6BAA6B;AAEpC,MAAK,MAAM,UAAU,gBACnB,KAAI;AACF,UAAQ,UAAU,gCAChB,QAAQ,QAAQ,KAAK,QAAQ,CAC9B;SACK"}
@@ -1,5 +1,3 @@
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]="4f7cf8f6-3a9a-5d41-95a3-192277e578fd")}catch(e){}}();
3
1
  import { warnOnce } from "./log.js";
4
2
  //#region src/replay-sidecar-url.ts
5
3
  /**
@@ -58,5 +56,4 @@ const isPrivateIpv4 = (hostname) => {
58
56
  //#endregion
59
57
  export { parseReplaySidecarUrl };
60
58
 
61
- //# sourceMappingURL=replay-sidecar-url.js.map
62
- //# debugId=4f7cf8f6-3a9a-5d41-95a3-192277e578fd
59
+ //# sourceMappingURL=replay-sidecar-url.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"replay-sidecar-url.js","sources":["../src/replay-sidecar-url.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\n\n/**\n * Validation for the replay sidecar origin carried on inbound requests.\n *\n * The value arrives in a request header, so in principle anything that can reach the worker\n * can propose one — and the shim POSTs outbound request bodies to whatever it accepts. The\n * guard therefore only honours an origin that could plausibly be a Meticulous replay\n * sidecar running alongside the app: plaintext HTTP on a loopback, docker-gateway or\n * private-network host.\n *\n * `https:` is rejected deliberately. A sidecar reachable over loopback or a pod network has\n * no TLS to offer, so permitting `https:` would buy nothing except a way for a forged header\n * to exfiltrate request bodies to an arbitrary internet host.\n */\n\nconst MAX_URL_LENGTH = 2048;\n\nconst ALLOWED_HOSTNAMES = new Set([\n \"localhost\",\n // Docker Desktop and Podman expose the host to containers under these names.\n \"host.docker.internal\",\n \"host.containers.internal\",\n]);\n\nexport const parseReplaySidecarUrl = (\n raw: string | null | undefined,\n): string | undefined => {\n if (typeof raw !== \"string\" || raw.length === 0) {\n return undefined;\n }\n if (raw.length > MAX_URL_LENGTH) {\n warnOnce(\n \"replay-sidecar-url\",\n \"Ignoring an implausibly long Meticulous replay sidecar URL.\",\n );\n return undefined;\n }\n\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n warnOnce(\n \"replay-sidecar-url\",\n \"Ignoring an unparseable Meticulous replay sidecar URL.\",\n );\n return undefined;\n }\n\n const isAcceptable =\n url.protocol === \"http:\" &&\n url.username === \"\" &&\n url.password === \"\" &&\n (url.pathname === \"\" || url.pathname === \"/\") &&\n url.search === \"\" &&\n url.hash === \"\" &&\n isLocalHostname(url.hostname);\n\n if (!isAcceptable) {\n warnOnce(\n \"replay-sidecar-url\",\n `Ignoring the Meticulous replay sidecar URL \"${raw}\" — only a plain http:// origin on a loopback, docker-gateway or private-network host is honoured.`,\n );\n return undefined;\n }\n\n // Return the parsed origin rather than the raw string: it is what `fetch` would resolve\n // the value to anyway, so the host that was validated is exactly the host that gets\n // called (alternative IPv4 spellings like \"0177.0.0.1\" normalize here, rather than being\n // checked in one form and dialled in another). Carries no trailing slash, matching\n // resolveSidecarUrl's normalization so the self-capture prefix check lines up.\n return url.origin;\n};\n\nconst isLocalHostname = (hostname: string): boolean => {\n const lower = hostname.toLowerCase();\n if (ALLOWED_HOSTNAMES.has(lower)) {\n return true;\n }\n // URL keeps IPv6 literals bracketed.\n const unbracketed =\n lower.startsWith(\"[\") && lower.endsWith(\"]\")\n ? lower.slice(1, -1)\n : undefined;\n if (unbracketed !== undefined) {\n return unbracketed === \"::1\";\n }\n return isPrivateIpv4(lower);\n};\n\nconst isPrivateIpv4 = (hostname: string): boolean => {\n const parts = hostname.split(\".\");\n if (parts.length !== 4) {\n return false;\n }\n const octets = parts.map((part) =>\n // Reject anything that is not a plain decimal octet: \"010\" and \"0x7f\" are parsed\n // inconsistently across resolvers, and \"1e2\" would pass a bare Number() check.\n /^\\d{1,3}$/.test(part) ? Number(part) : Number.NaN,\n );\n if (octets.some((octet) => Number.isNaN(octet) || octet > 255)) {\n return false;\n }\n const [first, second] = octets;\n // Deliberately excludes link-local (169.254.0.0/16): no sidecar is ever reachable there,\n // but the cloud metadata endpoints are (169.254.169.254), so allowing it would only widen\n // the SSRF surface. The rest of the codebase blocks that range for the same reason — see\n // `staging-backend-url.ts` and `assets-app-server.ts`.\n return (\n first === 127 || // loopback\n first === 10 || // RFC1918\n (first === 172 && second >= 16 && second <= 31) || // RFC1918\n (first === 192 && second === 168) // RFC1918\n );\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAgBA,MAAM,iBAAiB;AAEvB,MAAM,oBAAoB,IAAI,IAAI;CAChC;CAEA;CACA;CACD,CAAC;AAEF,MAAa,yBACX,QACuB;AACvB,KAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,EAC5C;AAEF,KAAI,IAAI,SAAS,gBAAgB;AAC/B,WACE,sBACA,8DACD;AACD;;CAGF,IAAI;AACJ,KAAI;AACF,QAAM,IAAI,IAAI,IAAI;SACZ;AACN,WACE,sBACA,yDACD;AACD;;AAYF,KAAI,EARF,IAAI,aAAa,WACjB,IAAI,aAAa,MACjB,IAAI,aAAa,OAChB,IAAI,aAAa,MAAM,IAAI,aAAa,QACzC,IAAI,WAAW,MACf,IAAI,SAAS,MACb,gBAAgB,IAAI,SAAS,GAEZ;AACjB,WACE,sBACA,+CAA+C,IAAI,oGACpD;AACD;;AAQF,QAAO,IAAI;;AAGb,MAAM,mBAAmB,aAA8B;CACrD,MAAM,QAAQ,SAAS,aAAa;AACpC,KAAI,kBAAkB,IAAI,MAAM,CAC9B,QAAO;CAGT,MAAM,cACJ,MAAM,WAAW,IAAI,IAAI,MAAM,SAAS,IAAI,GACxC,MAAM,MAAM,GAAG,GAAG,GAClB,KAAA;AACN,KAAI,gBAAgB,KAAA,EAClB,QAAO,gBAAgB;AAEzB,QAAO,cAAc,MAAM;;AAG7B,MAAM,iBAAiB,aAA8B;CACnD,MAAM,QAAQ,SAAS,MAAM,IAAI;AACjC,KAAI,MAAM,WAAW,EACnB,QAAO;CAET,MAAM,SAAS,MAAM,KAAK,SAGxB,YAAY,KAAK,KAAK,GAAG,OAAO,KAAK,GAAG,IACzC;AACD,KAAI,OAAO,MAAM,UAAU,OAAO,MAAM,MAAM,IAAI,QAAQ,IAAI,CAC5D,QAAO;CAET,MAAM,CAAC,OAAO,UAAU;AAKxB,QACE,UAAU,OACV,UAAU,MACT,UAAU,OAAO,UAAU,MAAM,UAAU,MAC3C,UAAU,OAAO,WAAW","debugId":"4f7cf8f6-3a9a-5d41-95a3-192277e578fd"}
1
+ {"version":3,"file":"replay-sidecar-url.js","names":[],"sources":["../src/replay-sidecar-url.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\n\n/**\n * Validation for the replay sidecar origin carried on inbound requests.\n *\n * The value arrives in a request header, so in principle anything that can reach the worker\n * can propose one — and the shim POSTs outbound request bodies to whatever it accepts. The\n * guard therefore only honours an origin that could plausibly be a Meticulous replay\n * sidecar running alongside the app: plaintext HTTP on a loopback, docker-gateway or\n * private-network host.\n *\n * `https:` is rejected deliberately. A sidecar reachable over loopback or a pod network has\n * no TLS to offer, so permitting `https:` would buy nothing except a way for a forged header\n * to exfiltrate request bodies to an arbitrary internet host.\n */\n\nconst MAX_URL_LENGTH = 2048;\n\nconst ALLOWED_HOSTNAMES = new Set([\n \"localhost\",\n // Docker Desktop and Podman expose the host to containers under these names.\n \"host.docker.internal\",\n \"host.containers.internal\",\n]);\n\nexport const parseReplaySidecarUrl = (\n raw: string | null | undefined,\n): string | undefined => {\n if (typeof raw !== \"string\" || raw.length === 0) {\n return undefined;\n }\n if (raw.length > MAX_URL_LENGTH) {\n warnOnce(\n \"replay-sidecar-url\",\n \"Ignoring an implausibly long Meticulous replay sidecar URL.\",\n );\n return undefined;\n }\n\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n warnOnce(\n \"replay-sidecar-url\",\n \"Ignoring an unparseable Meticulous replay sidecar URL.\",\n );\n return undefined;\n }\n\n const isAcceptable =\n url.protocol === \"http:\" &&\n url.username === \"\" &&\n url.password === \"\" &&\n (url.pathname === \"\" || url.pathname === \"/\") &&\n url.search === \"\" &&\n url.hash === \"\" &&\n isLocalHostname(url.hostname);\n\n if (!isAcceptable) {\n warnOnce(\n \"replay-sidecar-url\",\n `Ignoring the Meticulous replay sidecar URL \"${raw}\" — only a plain http:// origin on a loopback, docker-gateway or private-network host is honoured.`,\n );\n return undefined;\n }\n\n // Return the parsed origin rather than the raw string: it is what `fetch` would resolve\n // the value to anyway, so the host that was validated is exactly the host that gets\n // called (alternative IPv4 spellings like \"0177.0.0.1\" normalize here, rather than being\n // checked in one form and dialled in another). Carries no trailing slash, matching\n // resolveSidecarUrl's normalization so the self-capture prefix check lines up.\n return url.origin;\n};\n\nconst isLocalHostname = (hostname: string): boolean => {\n const lower = hostname.toLowerCase();\n if (ALLOWED_HOSTNAMES.has(lower)) {\n return true;\n }\n // URL keeps IPv6 literals bracketed.\n const unbracketed =\n lower.startsWith(\"[\") && lower.endsWith(\"]\")\n ? lower.slice(1, -1)\n : undefined;\n if (unbracketed !== undefined) {\n return unbracketed === \"::1\";\n }\n return isPrivateIpv4(lower);\n};\n\nconst isPrivateIpv4 = (hostname: string): boolean => {\n const parts = hostname.split(\".\");\n if (parts.length !== 4) {\n return false;\n }\n const octets = parts.map((part) =>\n // Reject anything that is not a plain decimal octet: \"010\" and \"0x7f\" are parsed\n // inconsistently across resolvers, and \"1e2\" would pass a bare Number() check.\n /^\\d{1,3}$/.test(part) ? Number(part) : Number.NaN,\n );\n if (octets.some((octet) => Number.isNaN(octet) || octet > 255)) {\n return false;\n }\n const [first, second] = octets;\n // Deliberately excludes link-local (169.254.0.0/16): no sidecar is ever reachable there,\n // but the cloud metadata endpoints are (169.254.169.254), so allowing it would only widen\n // the SSRF surface. The rest of the codebase blocks that range for the same reason — see\n // `staging-backend-url.ts` and `assets-app-server.ts`.\n return (\n first === 127 || // loopback\n first === 10 || // RFC1918\n (first === 172 && second >= 16 && second <= 31) || // RFC1918\n (first === 192 && second === 168) // RFC1918\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAM,iBAAiB;AAEvB,MAAM,oBAAoB,IAAI,IAAI;CAChC;CAEA;CACA;CACD,CAAC;AAEF,MAAa,yBACX,QACuB;AACvB,KAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,EAC5C;AAEF,KAAI,IAAI,SAAS,gBAAgB;AAC/B,WACE,sBACA,8DACD;AACD;;CAGF,IAAI;AACJ,KAAI;AACF,QAAM,IAAI,IAAI,IAAI;SACZ;AACN,WACE,sBACA,yDACD;AACD;;AAYF,KAAI,EARF,IAAI,aAAa,WACjB,IAAI,aAAa,MACjB,IAAI,aAAa,OAChB,IAAI,aAAa,MAAM,IAAI,aAAa,QACzC,IAAI,WAAW,MACf,IAAI,SAAS,MACb,gBAAgB,IAAI,SAAS,GAEZ;AACjB,WACE,sBACA,+CAA+C,IAAI,oGACpD;AACD;;AAQF,QAAO,IAAI;;AAGb,MAAM,mBAAmB,aAA8B;CACrD,MAAM,QAAQ,SAAS,aAAa;AACpC,KAAI,kBAAkB,IAAI,MAAM,CAC9B,QAAO;CAGT,MAAM,cACJ,MAAM,WAAW,IAAI,IAAI,MAAM,SAAS,IAAI,GACxC,MAAM,MAAM,GAAG,GAAG,GAClB,KAAA;AACN,KAAI,gBAAgB,KAAA,EAClB,QAAO,gBAAgB;AAEzB,QAAO,cAAc,MAAM;;AAG7B,MAAM,iBAAiB,aAA8B;CACnD,MAAM,QAAQ,SAAS,MAAM,IAAI;AACjC,KAAI,MAAM,WAAW,EACnB,QAAO;CAET,MAAM,SAAS,MAAM,KAAK,SAGxB,YAAY,KAAK,KAAK,GAAG,OAAO,KAAK,GAAG,IACzC;AACD,KAAI,OAAO,MAAM,UAAU,OAAO,MAAM,MAAM,IAAI,QAAQ,IAAI,CAC5D,QAAO;CAET,MAAM,CAAC,OAAO,UAAU;AAKxB,QACE,UAAU,OACV,UAAU,MACT,UAAU,OAAO,UAAU,MAAM,UAAU,MAC3C,UAAU,OAAO,WAAW"}
@@ -1,5 +1,3 @@
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]="4d6a9c0e-a5a7-52d6-8b38-28342d0f79e3")}catch(e){}}();
3
1
  import { sidecarFetch } from "./sidecar-transport.js";
4
2
  import { warnOnce } from "./log.js";
5
3
  import { SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_COVERAGE_PATH, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH } from "./protocol.js";
@@ -187,5 +185,4 @@ const withTimeout = async (ms, send) => {
187
185
  //#endregion
188
186
  export { getReplaySessionInfo, postCaptureEvents, postCoverageReport, postOutboundFetchLookup };
189
187
 
190
- //# sourceMappingURL=sidecar-client.js.map
191
- //# debugId=4d6a9c0e-a5a7-52d6-8b38-28342d0f79e3
188
+ //# sourceMappingURL=sidecar-client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sidecar-client.js","sources":["../src/sidecar-client.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { getOriginalFetch } from \"./original-fetch\";\nimport {\n type CaptureEvent,\n type CaptureEventsPayload,\n type CoverageReportRequest,\n type OutboundFetchLookupRequest,\n type OutboundFetchLookupResponse,\n type ReplaySessionInfoResponse,\n SIDECAR_EVENTS_PATH,\n SIDECAR_PROTOCOL_VERSION,\n SIDECAR_PROTOCOL_VERSION_HEADER,\n SIDECAR_REPLAY_COVERAGE_PATH,\n SIDECAR_REPLAY_OUTBOUND_FETCH_PATH,\n SIDECAR_REPLAY_SESSION_PATH,\n} from \"./protocol\";\nimport { sidecarFetch, type SidecarTransport } from \"./sidecar-transport\";\n\ntype FetchFn = typeof globalThis.fetch;\n\n/**\n * Replay calls sit in the request path, unlike record mode's fire-and-forget reporting, so\n * they must be bounded: without a timeout a wedged sidecar would hang every outbound fetch\n * the app makes, and therefore the whole replay, with nothing to look at.\n */\nconst SESSION_INFO_TIMEOUT_MS = 10_000;\nconst LOOKUP_TIMEOUT_MS = 5_000;\n\n/**\n * Capture reporting is off the response path (it runs under `ctx.waitUntil`), so a timeout here\n * is not about latency the app can see — it is about not holding the request context open on a\n * sidecar that will never answer. A refused connection rejects immediately, but a sidecar URL\n * pointing at a host that drops packets rather than refusing them (a firewalled container or LAN\n * address instead of loopback) would otherwise leave the POST pending until the runtime tears the\n * context down, on every captured call.\n *\n * Generous relative to what it bounds: a local sidecar answers a small batch in single-digit\n * milliseconds, so this only ever fires on one that is wedged or unreachable — never on one that\n * is merely busy. Being generous costs nothing because {@link withTimeout} clears the timer the\n * moment the POST settles.\n */\nconst CAPTURE_POST_TIMEOUT_MS = 2_000;\n\n/**\n * The same bound for a service-binding transport, where the sidecar is a Worker that hands the\n * batch to a Durable Object before answering. That object may live in another region and is\n * single-threaded, so a busy one can legitimately take far longer than a loopback process — and\n * failing the report early would drop spans a slightly longer wait would have recorded.\n * `waitUntil` allows 30s past the response, so this stays well inside its budget.\n */\nconst CAPTURE_POST_BINDING_TIMEOUT_MS = 10_000;\n\n/**\n * Coverage reports are larger than capture events — the first one of an isolate\n * carries the whole id→line map — so they get more headroom than\n * {@link CAPTURE_POST_TIMEOUT_MS}. Still bounded, and for the same reason: an\n * unreachable sidecar must not hold the request context open.\n */\nconst COVERAGE_POST_TIMEOUT_MS = 5_000;\n\n/** POSTs capture events to the sidecar. Never rejects — reporting failures only warn (once). */\nexport const postCaptureEvents = async (\n transport: SidecarTransport,\n events: CaptureEvent[],\n): Promise<void> => {\n const timeoutMs =\n transport.kind === \"binding\"\n ? CAPTURE_POST_BINDING_TIMEOUT_MS\n : CAPTURE_POST_TIMEOUT_MS;\n try {\n const payload: CaptureEventsPayload = { events };\n await withTimeout(timeoutMs, async (signal) => {\n const response = await sidecarFetch(\n transport,\n getOriginalFetch(),\n SIDECAR_EVENTS_PATH,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n [SIDECAR_PROTOCOL_VERSION_HEADER]: SIDECAR_PROTOCOL_VERSION,\n },\n body: JSON.stringify(payload),\n signal,\n },\n );\n if (!response.ok) {\n warnOnce(\n \"sidecar-rejected\",\n `Meticulous sidecar rejected capture events (HTTP ${response.status}).`,\n );\n }\n await response.arrayBuffer().catch(() => undefined);\n });\n } catch (error) {\n warnOnce(\n \"sidecar-unreachable\",\n \"Could not reach the Meticulous backend recorder sidecar — backend session events are not being recorded.\",\n error,\n );\n }\n};\n\n/**\n * Outcome of the session handshake.\n *\n * `unavailable` and `unreachable` both mean \"do not replay\", but they are kept apart\n * because only the first is a settled answer. The caller caches per isolate, and caching a\n * one-off network blip would disable mocking for the rest of the session — silently sending\n * every later outbound call to the real service.\n */\nexport type ReplaySessionInfoResult =\n /** The sidecar holds mocks for this session. */\n | { outcome: \"found\"; clockAnchorMs: number | undefined }\n /** The sidecar answered and will never serve this session: no mocks, or no such route. */\n | { outcome: \"unavailable\" }\n /** Could not get an answer — timeout, transport error, 5xx. May succeed later. */\n | { outcome: \"unreachable\" };\n\n/**\n * Asks whether the sidecar holds mocks for a session, and at what instant to freeze the\n * clock while serving it.\n *\n * A 404 is how a record-only sidecar answers, so it counts as a settled `unavailable`\n * rather than a retryable blip.\n */\nexport const getReplaySessionInfo = async (\n fetchFn: FetchFn,\n sidecarUrl: string,\n frontendSessionId: string,\n): Promise<ReplaySessionInfoResult> => {\n const url = `${sidecarUrl}${SIDECAR_REPLAY_SESSION_PATH}?sessionId=${encodeURIComponent(\n frontendSessionId,\n )}`;\n try {\n return await withTimeout(SESSION_INFO_TIMEOUT_MS, async (signal) => {\n const response = await fetchFn(url, {\n headers: {\n [SIDECAR_PROTOCOL_VERSION_HEADER]: SIDECAR_PROTOCOL_VERSION,\n },\n signal,\n });\n if (!response.ok) {\n await response.arrayBuffer().catch(() => undefined);\n // 4xx is the sidecar telling us something definitive — no such route (a record-only\n // sidecar), or a protocol version it will not speak. Retrying cannot change either.\n // 5xx may well be a sidecar still finding its feet, so leave it retryable.\n if (response.status >= 500) {\n warnOnce(\n \"replay-session-unreachable\",\n `Meticulous replay sidecar failed the replay session handshake (HTTP ${response.status}) — will retry on the next request.`,\n );\n return { outcome: \"unreachable\" };\n }\n warnOnce(\n \"replay-session-unavailable\",\n `Meticulous replay sidecar did not recognise the replay session route (HTTP ${response.status}) — outbound calls will not be mocked.`,\n );\n return { outcome: \"unavailable\" };\n }\n const info = (await response.json()) as ReplaySessionInfoResponse;\n if (info.found !== true) {\n warnOnce(\n \"replay-session-unknown\",\n \"Meticulous replay sidecar holds no mocks for this session — outbound calls will not be mocked.\",\n );\n return { outcome: \"unavailable\" };\n }\n return {\n outcome: \"found\",\n clockAnchorMs:\n typeof info.clockAnchorMs === \"number\"\n ? info.clockAnchorMs\n : undefined,\n };\n });\n } catch (error) {\n warnOnce(\n \"replay-session-unreachable\",\n \"Could not reach the Meticulous replay sidecar — will retry on the next request.\",\n error,\n );\n return { outcome: \"unreachable\" };\n }\n};\n\n/**\n * Looks up a recorded response for one outbound call. Never rejects; returns undefined when\n * the sidecar could not be consulted, which the caller fails the request on — an unanswered\n * lookup is not evidence that a real call is safe.\n */\nexport const postOutboundFetchLookup = async (\n fetchFn: FetchFn,\n sidecarUrl: string,\n payload: OutboundFetchLookupRequest,\n): Promise<OutboundFetchLookupResponse | undefined> => {\n try {\n return await withTimeout(LOOKUP_TIMEOUT_MS, async (signal) => {\n const response = await fetchFn(\n `${sidecarUrl}${SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n [SIDECAR_PROTOCOL_VERSION_HEADER]: SIDECAR_PROTOCOL_VERSION,\n },\n body: JSON.stringify(payload),\n signal,\n },\n );\n if (!response.ok) {\n warnOnce(\n \"replay-lookup-rejected\",\n `Meticulous replay sidecar rejected a mock lookup (HTTP ${response.status}).`,\n );\n await response.arrayBuffer().catch(() => undefined);\n return undefined;\n }\n return (await response.json()) as OutboundFetchLookupResponse;\n });\n } catch (error) {\n warnOnce(\n \"replay-lookup-unreachable\",\n \"Could not reach the Meticulous replay sidecar for a mock lookup — the call will fail.\",\n error,\n );\n return undefined;\n }\n};\n\n/**\n * Outcome of a coverage report.\n *\n * `unsupported` and `failed` both mean the report did not land, but only the\n * first is settled: the caller latches `unsupported` and stops collecting, while\n * `failed` leaves the id→line map queued for the next report. Conflating them\n * would either disable coverage on one blip or lose a map permanently.\n */\nexport type CoverageReportOutcome = \"accepted\" | \"unsupported\" | \"failed\";\n\n/**\n * Reports one request's line coverage. Runs under `ctx.waitUntil`, so it is off\n * the response path like record-mode capture reporting.\n *\n * Returns `unsupported` when the sidecar will never accept coverage (404 — an\n * older sidecar, or one started without coverage enabled), which the caller\n * latches so it stops paying to serialise hits for the rest of the isolate's\n * life.\n */\nexport const postCoverageReport = async (\n fetchFn: FetchFn,\n sidecarUrl: string,\n payload: CoverageReportRequest,\n): Promise<CoverageReportOutcome> => {\n try {\n return await withTimeout(COVERAGE_POST_TIMEOUT_MS, async (signal) => {\n const response = await fetchFn(\n `${sidecarUrl}${SIDECAR_REPLAY_COVERAGE_PATH}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n [SIDECAR_PROTOCOL_VERSION_HEADER]: SIDECAR_PROTOCOL_VERSION,\n },\n body: JSON.stringify(payload),\n signal,\n },\n );\n await response.arrayBuffer().catch(() => undefined);\n if (response.status === 404) {\n return \"unsupported\";\n }\n if (!response.ok) {\n warnOnce(\n \"coverage-rejected\",\n `Meticulous replay sidecar rejected a coverage report (HTTP ${response.status}).`,\n );\n return \"failed\";\n }\n return \"accepted\";\n });\n } catch (error) {\n warnOnce(\n \"coverage-unreachable\",\n \"Could not report line coverage to the Meticulous replay sidecar.\",\n error,\n );\n return \"failed\";\n }\n};\n\n/**\n * Runs `send` under an abort signal that fires after `ms`, clearing the timer as soon as the\n * call settles — including the response body read, which an abort must still cut short.\n *\n * Deliberately not `AbortSignal.timeout`: its timer cannot be cancelled, and a pending timer\n * keeps workerd's request context alive. Bounding a 5ms POST at 2s would then pin the context\n * for the remaining ~2s on every captured call — worse than the unbounded wait it exists to\n * prevent, and on the healthy path rather than the broken one. `body-capture.ts` uses this\n * same clearable shape, for the same reason.\n */\nconst withTimeout = async <T>(\n ms: number,\n send: (signal: AbortSignal) => Promise<T>,\n): Promise<T> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), ms);\n try {\n return await send(controller.signal);\n } finally {\n clearTimeout(timer);\n }\n};\n"],"names":[],"mappings":"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","debugId":"4d6a9c0e-a5a7-52d6-8b38-28342d0f79e3"}
1
+ {"version":3,"file":"sidecar-client.js","names":[],"sources":["../src/sidecar-client.ts"],"sourcesContent":["import { warnOnce } from \"./log\";\nimport { getOriginalFetch } from \"./original-fetch\";\nimport {\n type CaptureEvent,\n type CaptureEventsPayload,\n type CoverageReportRequest,\n type OutboundFetchLookupRequest,\n type OutboundFetchLookupResponse,\n type ReplaySessionInfoResponse,\n SIDECAR_EVENTS_PATH,\n SIDECAR_PROTOCOL_VERSION,\n SIDECAR_PROTOCOL_VERSION_HEADER,\n SIDECAR_REPLAY_COVERAGE_PATH,\n SIDECAR_REPLAY_OUTBOUND_FETCH_PATH,\n SIDECAR_REPLAY_SESSION_PATH,\n} from \"./protocol\";\nimport { sidecarFetch, type SidecarTransport } from \"./sidecar-transport\";\n\ntype FetchFn = typeof globalThis.fetch;\n\n/**\n * Replay calls sit in the request path, unlike record mode's fire-and-forget reporting, so\n * they must be bounded: without a timeout a wedged sidecar would hang every outbound fetch\n * the app makes, and therefore the whole replay, with nothing to look at.\n */\nconst SESSION_INFO_TIMEOUT_MS = 10_000;\nconst LOOKUP_TIMEOUT_MS = 5_000;\n\n/**\n * Capture reporting is off the response path (it runs under `ctx.waitUntil`), so a timeout here\n * is not about latency the app can see — it is about not holding the request context open on a\n * sidecar that will never answer. A refused connection rejects immediately, but a sidecar URL\n * pointing at a host that drops packets rather than refusing them (a firewalled container or LAN\n * address instead of loopback) would otherwise leave the POST pending until the runtime tears the\n * context down, on every captured call.\n *\n * Generous relative to what it bounds: a local sidecar answers a small batch in single-digit\n * milliseconds, so this only ever fires on one that is wedged or unreachable — never on one that\n * is merely busy. Being generous costs nothing because {@link withTimeout} clears the timer the\n * moment the POST settles.\n */\nconst CAPTURE_POST_TIMEOUT_MS = 2_000;\n\n/**\n * The same bound for a service-binding transport, where the sidecar is a Worker that hands the\n * batch to a Durable Object before answering. That object may live in another region and is\n * single-threaded, so a busy one can legitimately take far longer than a loopback process — and\n * failing the report early would drop spans a slightly longer wait would have recorded.\n * `waitUntil` allows 30s past the response, so this stays well inside its budget.\n */\nconst CAPTURE_POST_BINDING_TIMEOUT_MS = 10_000;\n\n/**\n * Coverage reports are larger than capture events — the first one of an isolate\n * carries the whole id→line map — so they get more headroom than\n * {@link CAPTURE_POST_TIMEOUT_MS}. Still bounded, and for the same reason: an\n * unreachable sidecar must not hold the request context open.\n */\nconst COVERAGE_POST_TIMEOUT_MS = 5_000;\n\n/** POSTs capture events to the sidecar. Never rejects — reporting failures only warn (once). */\nexport const postCaptureEvents = async (\n transport: SidecarTransport,\n events: CaptureEvent[],\n): Promise<void> => {\n const timeoutMs =\n transport.kind === \"binding\"\n ? CAPTURE_POST_BINDING_TIMEOUT_MS\n : CAPTURE_POST_TIMEOUT_MS;\n try {\n const payload: CaptureEventsPayload = { events };\n await withTimeout(timeoutMs, async (signal) => {\n const response = await sidecarFetch(\n transport,\n getOriginalFetch(),\n SIDECAR_EVENTS_PATH,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n [SIDECAR_PROTOCOL_VERSION_HEADER]: SIDECAR_PROTOCOL_VERSION,\n },\n body: JSON.stringify(payload),\n signal,\n },\n );\n if (!response.ok) {\n warnOnce(\n \"sidecar-rejected\",\n `Meticulous sidecar rejected capture events (HTTP ${response.status}).`,\n );\n }\n await response.arrayBuffer().catch(() => undefined);\n });\n } catch (error) {\n warnOnce(\n \"sidecar-unreachable\",\n \"Could not reach the Meticulous backend recorder sidecar — backend session events are not being recorded.\",\n error,\n );\n }\n};\n\n/**\n * Outcome of the session handshake.\n *\n * `unavailable` and `unreachable` both mean \"do not replay\", but they are kept apart\n * because only the first is a settled answer. The caller caches per isolate, and caching a\n * one-off network blip would disable mocking for the rest of the session — silently sending\n * every later outbound call to the real service.\n */\nexport type ReplaySessionInfoResult =\n /** The sidecar holds mocks for this session. */\n | { outcome: \"found\"; clockAnchorMs: number | undefined }\n /** The sidecar answered and will never serve this session: no mocks, or no such route. */\n | { outcome: \"unavailable\" }\n /** Could not get an answer — timeout, transport error, 5xx. May succeed later. */\n | { outcome: \"unreachable\" };\n\n/**\n * Asks whether the sidecar holds mocks for a session, and at what instant to freeze the\n * clock while serving it.\n *\n * A 404 is how a record-only sidecar answers, so it counts as a settled `unavailable`\n * rather than a retryable blip.\n */\nexport const getReplaySessionInfo = async (\n fetchFn: FetchFn,\n sidecarUrl: string,\n frontendSessionId: string,\n): Promise<ReplaySessionInfoResult> => {\n const url = `${sidecarUrl}${SIDECAR_REPLAY_SESSION_PATH}?sessionId=${encodeURIComponent(\n frontendSessionId,\n )}`;\n try {\n return await withTimeout(SESSION_INFO_TIMEOUT_MS, async (signal) => {\n const response = await fetchFn(url, {\n headers: {\n [SIDECAR_PROTOCOL_VERSION_HEADER]: SIDECAR_PROTOCOL_VERSION,\n },\n signal,\n });\n if (!response.ok) {\n await response.arrayBuffer().catch(() => undefined);\n // 4xx is the sidecar telling us something definitive — no such route (a record-only\n // sidecar), or a protocol version it will not speak. Retrying cannot change either.\n // 5xx may well be a sidecar still finding its feet, so leave it retryable.\n if (response.status >= 500) {\n warnOnce(\n \"replay-session-unreachable\",\n `Meticulous replay sidecar failed the replay session handshake (HTTP ${response.status}) — will retry on the next request.`,\n );\n return { outcome: \"unreachable\" };\n }\n warnOnce(\n \"replay-session-unavailable\",\n `Meticulous replay sidecar did not recognise the replay session route (HTTP ${response.status}) — outbound calls will not be mocked.`,\n );\n return { outcome: \"unavailable\" };\n }\n const info = (await response.json()) as ReplaySessionInfoResponse;\n if (info.found !== true) {\n warnOnce(\n \"replay-session-unknown\",\n \"Meticulous replay sidecar holds no mocks for this session — outbound calls will not be mocked.\",\n );\n return { outcome: \"unavailable\" };\n }\n return {\n outcome: \"found\",\n clockAnchorMs:\n typeof info.clockAnchorMs === \"number\"\n ? info.clockAnchorMs\n : undefined,\n };\n });\n } catch (error) {\n warnOnce(\n \"replay-session-unreachable\",\n \"Could not reach the Meticulous replay sidecar — will retry on the next request.\",\n error,\n );\n return { outcome: \"unreachable\" };\n }\n};\n\n/**\n * Looks up a recorded response for one outbound call. Never rejects; returns undefined when\n * the sidecar could not be consulted, which the caller fails the request on — an unanswered\n * lookup is not evidence that a real call is safe.\n */\nexport const postOutboundFetchLookup = async (\n fetchFn: FetchFn,\n sidecarUrl: string,\n payload: OutboundFetchLookupRequest,\n): Promise<OutboundFetchLookupResponse | undefined> => {\n try {\n return await withTimeout(LOOKUP_TIMEOUT_MS, async (signal) => {\n const response = await fetchFn(\n `${sidecarUrl}${SIDECAR_REPLAY_OUTBOUND_FETCH_PATH}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n [SIDECAR_PROTOCOL_VERSION_HEADER]: SIDECAR_PROTOCOL_VERSION,\n },\n body: JSON.stringify(payload),\n signal,\n },\n );\n if (!response.ok) {\n warnOnce(\n \"replay-lookup-rejected\",\n `Meticulous replay sidecar rejected a mock lookup (HTTP ${response.status}).`,\n );\n await response.arrayBuffer().catch(() => undefined);\n return undefined;\n }\n return (await response.json()) as OutboundFetchLookupResponse;\n });\n } catch (error) {\n warnOnce(\n \"replay-lookup-unreachable\",\n \"Could not reach the Meticulous replay sidecar for a mock lookup — the call will fail.\",\n error,\n );\n return undefined;\n }\n};\n\n/**\n * Outcome of a coverage report.\n *\n * `unsupported` and `failed` both mean the report did not land, but only the\n * first is settled: the caller latches `unsupported` and stops collecting, while\n * `failed` leaves the id→line map queued for the next report. Conflating them\n * would either disable coverage on one blip or lose a map permanently.\n */\nexport type CoverageReportOutcome = \"accepted\" | \"unsupported\" | \"failed\";\n\n/**\n * Reports one request's line coverage. Runs under `ctx.waitUntil`, so it is off\n * the response path like record-mode capture reporting.\n *\n * Returns `unsupported` when the sidecar will never accept coverage (404 — an\n * older sidecar, or one started without coverage enabled), which the caller\n * latches so it stops paying to serialise hits for the rest of the isolate's\n * life.\n */\nexport const postCoverageReport = async (\n fetchFn: FetchFn,\n sidecarUrl: string,\n payload: CoverageReportRequest,\n): Promise<CoverageReportOutcome> => {\n try {\n return await withTimeout(COVERAGE_POST_TIMEOUT_MS, async (signal) => {\n const response = await fetchFn(\n `${sidecarUrl}${SIDECAR_REPLAY_COVERAGE_PATH}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n [SIDECAR_PROTOCOL_VERSION_HEADER]: SIDECAR_PROTOCOL_VERSION,\n },\n body: JSON.stringify(payload),\n signal,\n },\n );\n await response.arrayBuffer().catch(() => undefined);\n if (response.status === 404) {\n return \"unsupported\";\n }\n if (!response.ok) {\n warnOnce(\n \"coverage-rejected\",\n `Meticulous replay sidecar rejected a coverage report (HTTP ${response.status}).`,\n );\n return \"failed\";\n }\n return \"accepted\";\n });\n } catch (error) {\n warnOnce(\n \"coverage-unreachable\",\n \"Could not report line coverage to the Meticulous replay sidecar.\",\n error,\n );\n return \"failed\";\n }\n};\n\n/**\n * Runs `send` under an abort signal that fires after `ms`, clearing the timer as soon as the\n * call settles — including the response body read, which an abort must still cut short.\n *\n * Deliberately not `AbortSignal.timeout`: its timer cannot be cancelled, and a pending timer\n * keeps workerd's request context alive. Bounding a 5ms POST at 2s would then pin the context\n * for the remaining ~2s on every captured call — worse than the unbounded wait it exists to\n * prevent, and on the healthy path rather than the broken one. `body-capture.ts` uses this\n * same clearable shape, for the same reason.\n */\nconst withTimeout = async <T>(\n ms: number,\n send: (signal: AbortSignal) => Promise<T>,\n): Promise<T> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), ms);\n try {\n return await send(controller.signal);\n } finally {\n clearTimeout(timer);\n }\n};\n"],"mappings":"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"}
@@ -4,8 +4,6 @@
4
4
  * bound Worker whatever the host is, so only the path is load-bearing — but the URL still has to
5
5
  * parse, and using a reserved-by-RFC TLD makes it obvious in a log that no DNS was involved.
6
6
  */
7
-
8
- !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]="4c3fd120-a382-55e7-8105-c6ff77ac4d6e")}catch(e){}}();
9
7
  const SIDECAR_BINDING_ORIGIN = "https://meticulous-sidecar.invalid";
10
8
  /** Env key holding a service binding to the Meticulous recorder sidecar Worker. */
11
9
  const SIDECAR_BINDING_ENV_KEY = "METICULOUS_SIDECAR";
@@ -48,5 +46,4 @@ const isFetcher = (value) => value !== null && typeof value === "object" && type
48
46
  //#endregion
49
47
  export { SIDECAR_BINDING_ENV_KEY, SIDECAR_BINDING_ORIGIN, SIDECAR_URL_ENV_KEY, resolveSidecarTransport, sidecarFetch, transportOrigin };
50
48
 
51
- //# sourceMappingURL=sidecar-transport.js.map
52
- //# debugId=4c3fd120-a382-55e7-8105-c6ff77ac4d6e
49
+ //# sourceMappingURL=sidecar-transport.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sidecar-transport.js","sources":["../src/sidecar-transport.ts"],"sourcesContent":["/**\n * Anything with a `fetch` — a Cloudflare service binding (`Fetcher`), or a Durable Object stub.\n * Structural so the shim needs no `@cloudflare/workers-types` dependency.\n */\nexport interface SidecarFetcher {\n fetch: (...args: unknown[]) => Promise<Response>;\n}\n\n/**\n * How capture events reach the sidecar.\n *\n * A local `wrangler dev` recording posts to a loopback URL. A deployed Worker cannot: there is\n * no sidecar process at the edge, and one HTTPS round trip per event to a distant host would be\n * both slow and a subrequest per captured call. So a deployed Worker instead talks to a\n * Meticulous sidecar Worker in the same account through a **service binding**, which stays\n * inside the colo and needs neither DNS nor TLS.\n */\nexport type SidecarTransport =\n | { kind: \"url\"; url: string }\n | { kind: \"binding\"; fetcher: SidecarFetcher; instance: object };\n\n/**\n * Origin the shim addresses a service-binding request to. A service binding delivers to the\n * bound Worker whatever the host is, so only the path is load-bearing — but the URL still has to\n * parse, and using a reserved-by-RFC TLD makes it obvious in a log that no DNS was involved.\n */\nexport const SIDECAR_BINDING_ORIGIN = \"https://meticulous-sidecar.invalid\";\n\n/** Env key holding a service binding to the Meticulous recorder sidecar Worker. */\nexport const SIDECAR_BINDING_ENV_KEY = \"METICULOUS_SIDECAR\";\n\n/** Env key holding the URL of a local recorder sidecar process. */\nexport const SIDECAR_URL_ENV_KEY = \"METICULOUS_SIDECAR_URL\";\n\n/** The origin the shim's own sidecar requests go to, for the self-capture guards. */\nexport const transportOrigin = (transport: SidecarTransport): string =>\n transport.kind === \"url\" ? transport.url : SIDECAR_BINDING_ORIGIN;\n\n/**\n * Sends one request to the sidecar, whichever transport is in use.\n *\n * `fetchFn` is the unpatched global fetch, passed in rather than imported so this module stays\n * free of the patch machinery; it is unused for a binding, whose `fetch` is its own method.\n */\nexport const sidecarFetch = (\n transport: SidecarTransport,\n fetchFn: typeof globalThis.fetch,\n path: string,\n init: RequestInit,\n): Promise<Response> => {\n const url = `${transportOrigin(transport)}${path}`;\n return transport.kind === \"url\"\n ? fetchFn(url, init)\n : transport.fetcher.fetch(new Request(url, init));\n};\n\nexport interface ResolveSidecarOptions {\n /** Explicit binding, taking precedence over anything found on `env`. */\n sidecarBinding?: SidecarFetcher;\n /** Explicit URL, taking precedence over the env var. */\n sidecarUrl?: string;\n}\n\n/**\n * Picks the transport for a recording, or undefined when recording is not configured.\n *\n * A binding wins over a URL. The two are only ever both present by accident — a `.dev.vars`\n * left in an image, say — and the binding is the deliberate one: it can only exist because\n * someone added it to the wrangler configuration of this deployment.\n */\nexport const resolveSidecarTransport = (\n options: ResolveSidecarOptions | undefined,\n env: unknown,\n): SidecarTransport | undefined => {\n const envRecord =\n env !== null && typeof env === \"object\"\n ? (env as Record<string, unknown>)\n : {};\n\n const binding = options?.sidecarBinding ?? envRecord[SIDECAR_BINDING_ENV_KEY];\n if (isFetcher(binding)) {\n return { kind: \"binding\", fetcher: binding, instance: binding };\n }\n\n const rawUrl = options?.sidecarUrl ?? envRecord[SIDECAR_URL_ENV_KEY];\n if (typeof rawUrl === \"string\" && rawUrl.length > 0) {\n return { kind: \"url\", url: rawUrl.replace(/\\/+$/, \"\") };\n }\n return undefined;\n};\n\nconst isFetcher = (value: unknown): value is SidecarFetcher & object =>\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as Partial<SidecarFetcher>).fetch === \"function\";\n"],"names":[],"mappings":";;;;;;;;AA0BA,MAAa,yBAAyB;;AAGtC,MAAa,0BAA0B;;AAGvC,MAAa,sBAAsB;;AAGnC,MAAa,mBAAmB,cAC9B,UAAU,SAAS,QAAQ,UAAU,MAAM;;;;;;;AAQ7C,MAAa,gBACX,WACA,SACA,MACA,SACsB;CACtB,MAAM,MAAM,GAAG,gBAAgB,UAAU,GAAG;AAC5C,QAAO,UAAU,SAAS,QACtB,QAAQ,KAAK,KAAK,GAClB,UAAU,QAAQ,MAAM,IAAI,QAAQ,KAAK,KAAK,CAAC;;;;;;;;;AAiBrD,MAAa,2BACX,SACA,QACiC;CACjC,MAAM,YACJ,QAAQ,QAAQ,OAAO,QAAQ,WAC1B,MACD,EAAE;CAER,MAAM,UAAU,SAAS,kBAAkB,UAAA;AAC3C,KAAI,UAAU,QAAQ,CACpB,QAAO;EAAE,MAAM;EAAW,SAAS;EAAS,UAAU;EAAS;CAGjE,MAAM,SAAS,SAAS,cAAc,UAAA;AACtC,KAAI,OAAO,WAAW,YAAY,OAAO,SAAS,EAChD,QAAO;EAAE,MAAM;EAAO,KAAK,OAAO,QAAQ,QAAQ,GAAG;EAAE;;AAK3D,MAAM,aAAa,UACjB,UAAU,QACV,OAAO,UAAU,YACjB,OAAQ,MAAkC,UAAU","debugId":"4c3fd120-a382-55e7-8105-c6ff77ac4d6e"}
1
+ {"version":3,"file":"sidecar-transport.js","names":[],"sources":["../src/sidecar-transport.ts"],"sourcesContent":["/**\n * Anything with a `fetch` — a Cloudflare service binding (`Fetcher`), or a Durable Object stub.\n * Structural so the shim needs no `@cloudflare/workers-types` dependency.\n */\nexport interface SidecarFetcher {\n fetch: (...args: unknown[]) => Promise<Response>;\n}\n\n/**\n * How capture events reach the sidecar.\n *\n * A local `wrangler dev` recording posts to a loopback URL. A deployed Worker cannot: there is\n * no sidecar process at the edge, and one HTTPS round trip per event to a distant host would be\n * both slow and a subrequest per captured call. So a deployed Worker instead talks to a\n * Meticulous sidecar Worker in the same account through a **service binding**, which stays\n * inside the colo and needs neither DNS nor TLS.\n */\nexport type SidecarTransport =\n | { kind: \"url\"; url: string }\n | { kind: \"binding\"; fetcher: SidecarFetcher; instance: object };\n\n/**\n * Origin the shim addresses a service-binding request to. A service binding delivers to the\n * bound Worker whatever the host is, so only the path is load-bearing — but the URL still has to\n * parse, and using a reserved-by-RFC TLD makes it obvious in a log that no DNS was involved.\n */\nexport const SIDECAR_BINDING_ORIGIN = \"https://meticulous-sidecar.invalid\";\n\n/** Env key holding a service binding to the Meticulous recorder sidecar Worker. */\nexport const SIDECAR_BINDING_ENV_KEY = \"METICULOUS_SIDECAR\";\n\n/** Env key holding the URL of a local recorder sidecar process. */\nexport const SIDECAR_URL_ENV_KEY = \"METICULOUS_SIDECAR_URL\";\n\n/** The origin the shim's own sidecar requests go to, for the self-capture guards. */\nexport const transportOrigin = (transport: SidecarTransport): string =>\n transport.kind === \"url\" ? transport.url : SIDECAR_BINDING_ORIGIN;\n\n/**\n * Sends one request to the sidecar, whichever transport is in use.\n *\n * `fetchFn` is the unpatched global fetch, passed in rather than imported so this module stays\n * free of the patch machinery; it is unused for a binding, whose `fetch` is its own method.\n */\nexport const sidecarFetch = (\n transport: SidecarTransport,\n fetchFn: typeof globalThis.fetch,\n path: string,\n init: RequestInit,\n): Promise<Response> => {\n const url = `${transportOrigin(transport)}${path}`;\n return transport.kind === \"url\"\n ? fetchFn(url, init)\n : transport.fetcher.fetch(new Request(url, init));\n};\n\nexport interface ResolveSidecarOptions {\n /** Explicit binding, taking precedence over anything found on `env`. */\n sidecarBinding?: SidecarFetcher;\n /** Explicit URL, taking precedence over the env var. */\n sidecarUrl?: string;\n}\n\n/**\n * Picks the transport for a recording, or undefined when recording is not configured.\n *\n * A binding wins over a URL. The two are only ever both present by accident — a `.dev.vars`\n * left in an image, say — and the binding is the deliberate one: it can only exist because\n * someone added it to the wrangler configuration of this deployment.\n */\nexport const resolveSidecarTransport = (\n options: ResolveSidecarOptions | undefined,\n env: unknown,\n): SidecarTransport | undefined => {\n const envRecord =\n env !== null && typeof env === \"object\"\n ? (env as Record<string, unknown>)\n : {};\n\n const binding = options?.sidecarBinding ?? envRecord[SIDECAR_BINDING_ENV_KEY];\n if (isFetcher(binding)) {\n return { kind: \"binding\", fetcher: binding, instance: binding };\n }\n\n const rawUrl = options?.sidecarUrl ?? envRecord[SIDECAR_URL_ENV_KEY];\n if (typeof rawUrl === \"string\" && rawUrl.length > 0) {\n return { kind: \"url\", url: rawUrl.replace(/\\/+$/, \"\") };\n }\n return undefined;\n};\n\nconst isFetcher = (value: unknown): value is SidecarFetcher & object =>\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as Partial<SidecarFetcher>).fetch === \"function\";\n"],"mappings":";;;;;;AA0BA,MAAa,yBAAyB;;AAGtC,MAAa,0BAA0B;;AAGvC,MAAa,sBAAsB;;AAGnC,MAAa,mBAAmB,cAC9B,UAAU,SAAS,QAAQ,UAAU,MAAM;;;;;;;AAQ7C,MAAa,gBACX,WACA,SACA,MACA,SACsB;CACtB,MAAM,MAAM,GAAG,gBAAgB,UAAU,GAAG;AAC5C,QAAO,UAAU,SAAS,QACtB,QAAQ,KAAK,KAAK,GAClB,UAAU,QAAQ,MAAM,IAAI,QAAQ,KAAK,KAAK,CAAC;;;;;;;;;AAiBrD,MAAa,2BACX,SACA,QACiC;CACjC,MAAM,YACJ,QAAQ,QAAQ,OAAO,QAAQ,WAC1B,MACD,EAAE;CAER,MAAM,UAAU,SAAS,kBAAkB,UAAA;AAC3C,KAAI,UAAU,QAAQ,CACpB,QAAO;EAAE,MAAM;EAAW,SAAS;EAAS,UAAU;EAAS;CAGjE,MAAM,SAAS,SAAS,cAAc,UAAA;AACtC,KAAI,OAAO,WAAW,YAAY,OAAO,SAAS,EAChD,QAAO;EAAE,MAAM;EAAO,KAAK,OAAO,QAAQ,QAAQ,GAAG;EAAE;;AAK3D,MAAM,aAAa,UACjB,UAAU,QACV,OAAO,UAAU,YACjB,OAAQ,MAAkC,UAAU"}