@alwaysmeticulous/backend-recorder-workerd 2.326.0 → 2.329.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +36 -0
  2. package/dist/binding-patch.js +2 -2
  3. package/dist/binding-patch.js.map +1 -1
  4. package/dist/body-capture.js +2 -2
  5. package/dist/body-capture.js.map +1 -1
  6. package/dist/capture-buffer.js +2 -2
  7. package/dist/capture-buffer.js.map +1 -1
  8. package/dist/context.js +2 -2
  9. package/dist/context.js.map +1 -1
  10. package/dist/coverage/coverage.types.d.ts +32 -0
  11. package/dist/coverage/replay-coverage.js +84 -0
  12. package/dist/coverage/replay-coverage.js.map +1 -0
  13. package/dist/coverage/runtime.d.ts +70 -0
  14. package/dist/coverage/runtime.js +138 -0
  15. package/dist/coverage/runtime.js.map +1 -0
  16. package/dist/error-capture.js +2 -2
  17. package/dist/error-capture.js.map +1 -1
  18. package/dist/fetch-patch.js +2 -2
  19. package/dist/fetch-patch.js.map +1 -1
  20. package/dist/index.d.ts +5 -2
  21. package/dist/index.js +6 -4
  22. package/dist/index.js.map +1 -1
  23. package/dist/kv-capture.js +2 -2
  24. package/dist/kv-capture.js.map +1 -1
  25. package/dist/kv-patch.js +2 -2
  26. package/dist/kv-patch.js.map +1 -1
  27. package/dist/log.js +2 -2
  28. package/dist/log.js.map +1 -1
  29. package/dist/original-fetch.js +2 -2
  30. package/dist/original-fetch.js.map +1 -1
  31. package/dist/outbound-capture.js +2 -2
  32. package/dist/outbound-capture.js.map +1 -1
  33. package/dist/pages-function.js +2 -2
  34. package/dist/pages-function.js.map +1 -1
  35. package/dist/postgres/capture.js +2 -2
  36. package/dist/postgres/capture.js.map +1 -1
  37. package/dist/postgres/with-meticulous-postgres.js +2 -2
  38. package/dist/postgres/with-meticulous-postgres.js.map +1 -1
  39. package/dist/protocol.d.ts +48 -18
  40. package/dist/protocol.js +22 -6
  41. package/dist/protocol.js.map +1 -1
  42. package/dist/provisional-session-id.js +2 -2
  43. package/dist/provisional-session-id.js.map +1 -1
  44. package/dist/publish-session-id.js +2 -2
  45. package/dist/publish-session-id.js.map +1 -1
  46. package/dist/publish-shim-version.js +37 -0
  47. package/dist/publish-shim-version.js.map +1 -0
  48. package/dist/redact-body.js +2 -2
  49. package/dist/redact-body.js.map +1 -1
  50. package/dist/replay-fetch.js +15 -12
  51. package/dist/replay-fetch.js.map +1 -1
  52. package/dist/replay-log-tagging.js +57 -0
  53. package/dist/replay-log-tagging.js.map +1 -0
  54. package/dist/replay-sidecar-url.js +2 -2
  55. package/dist/replay-sidecar-url.js.map +1 -1
  56. package/dist/sidecar-client.js +47 -6
  57. package/dist/sidecar-client.js.map +1 -1
  58. package/dist/sidecar-transport.js +2 -2
  59. package/dist/sidecar-transport.js.map +1 -1
  60. package/dist/spans/attributes.js +2 -2
  61. package/dist/spans/attributes.js.map +1 -1
  62. package/dist/spans/readable-span.js +2 -2
  63. package/dist/spans/readable-span.js.map +1 -1
  64. package/dist/spans/serialize-span.js +2 -2
  65. package/dist/spans/serialize-span.js.map +1 -1
  66. package/dist/spans/span-builder.js +2 -2
  67. package/dist/spans/span-builder.js.map +1 -1
  68. package/dist/spans/url-redaction.js +2 -2
  69. package/dist/spans/url-redaction.js.map +1 -1
  70. package/dist/version.d.ts +14 -0
  71. package/dist/version.js +18 -0
  72. package/dist/version.js.map +1 -0
  73. package/dist/virtual-clock.js +2 -2
  74. package/dist/virtual-clock.js.map +1 -1
  75. package/dist/virtual-random.js +47 -20
  76. package/dist/virtual-random.js.map +1 -1
  77. package/dist/vite/index.d.ts +62 -0
  78. package/dist/vite/index.js +6764 -0
  79. package/dist/vite/index.js.map +1 -0
  80. package/dist/with-meticulous.js +0 -0
  81. package/dist/with-meticulous.js.map +1 -1
  82. package/package.json +5 -2
@@ -0,0 +1,57 @@
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
+ import { requestCaptureContext } from "./context.js";
4
+ //#region src/replay-log-tagging.ts
5
+ const CONSOLE_METHODS = [
6
+ "debug",
7
+ "error",
8
+ "info",
9
+ "log",
10
+ "trace",
11
+ "warn"
12
+ ];
13
+ const CONSOLE_TAGGING_INSTALLED = Symbol.for("meticulous.workerd.consoleReplayTaggingInstalled");
14
+ const REPLAY_ID_LOG_TAG_NAME = "meticulous-replay-id";
15
+ const formatReplayIdLogTag = (replayId) => `[${REPLAY_ID_LOG_TAG_NAME}:${replayId}] `;
16
+ const tagContinuationLines = (value, prefix) => value.replace(/\n(?=.)/g, `\n${prefix}`);
17
+ const prepareConsoleArgument = (value, prefix) => {
18
+ if (typeof value === "string") return tagContinuationLines(value, prefix);
19
+ if (value instanceof Error) return tagContinuationLines(value.stack ?? value.message, prefix);
20
+ return value;
21
+ };
22
+ /**
23
+ * Adds the active request's replay marker. Keeping a string first argument in
24
+ * place preserves formatting such as `console.log("user=%s", id)`. Embedded
25
+ * newlines in strings and Error stacks are tagged too, since container runtimes
26
+ * may emit their continuation lines as separate log records.
27
+ */
28
+ const createReplayTaggedConsoleMethod = (original) => (...args) => {
29
+ let outputArgs = args;
30
+ try {
31
+ const ctx = requestCaptureContext.getStore();
32
+ if (ctx?.mode === "replay") {
33
+ const prefix = formatReplayIdLogTag(ctx.replayId);
34
+ const preparedArgs = args.map((arg) => prepareConsoleArgument(arg, prefix));
35
+ outputArgs = typeof preparedArgs[0] === "string" ? [prefix + preparedArgs[0], ...preparedArgs.slice(1)] : [prefix, ...preparedArgs];
36
+ }
37
+ } catch {}
38
+ original(...outputArgs);
39
+ };
40
+ /**
41
+ * Patches Workerd's output-producing console methods once. Outside a replayed
42
+ * request the wrappers are transparent; inside one they resolve the replay id
43
+ * from Workerd's request-scoped AsyncLocalStorage, so concurrent replays cannot
44
+ * label each other's output.
45
+ */
46
+ const installReplayLogTagging = (methods = console, holder = globalThis) => {
47
+ if (holder[CONSOLE_TAGGING_INSTALLED]) return;
48
+ holder[CONSOLE_TAGGING_INSTALLED] = true;
49
+ for (const method of CONSOLE_METHODS) try {
50
+ methods[method] = createReplayTaggedConsoleMethod(methods[method].bind(methods));
51
+ } catch {}
52
+ };
53
+ //#endregion
54
+ export { installReplayLogTagging };
55
+
56
+ //# sourceMappingURL=replay-log-tagging.js.map
57
+ //# debugId=962faa5b-f3e8-548c-be10-1e341f1f56bd
@@ -0,0 +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,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="94547b8a-bd87-50d7-ac87-204a0a65c1b7")}catch(e){}}();
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
3
  import { warnOnce } from "./log.js";
4
4
  //#region src/replay-sidecar-url.ts
5
5
  /**
@@ -59,4 +59,4 @@ const isPrivateIpv4 = (hostname) => {
59
59
  export { parseReplaySidecarUrl };
60
60
 
61
61
  //# sourceMappingURL=replay-sidecar-url.js.map
62
- //# debugId=94547b8a-bd87-50d7-ac87-204a0a65c1b7
62
+ //# debugId=4f7cf8f6-3a9a-5d41-95a3-192277e578fd
@@ -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,IAA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ay-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,8 +1,8 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0d5c5735-7024-56f9-b25d-6b418c084332")}catch(e){}}();
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
3
  import { sidecarFetch } from "./sidecar-transport.js";
4
4
  import { warnOnce } from "./log.js";
5
- import { SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH } from "./protocol.js";
5
+ import { SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_COVERAGE_PATH, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH } from "./protocol.js";
6
6
  import { getOriginalFetch } from "./original-fetch.js";
7
7
  //#region src/sidecar-client.ts
8
8
  /**
@@ -34,6 +34,13 @@ const CAPTURE_POST_TIMEOUT_MS = 2e3;
34
34
  * `waitUntil` allows 30s past the response, so this stays well inside its budget.
35
35
  */
36
36
  const CAPTURE_POST_BINDING_TIMEOUT_MS = 1e4;
37
+ /**
38
+ * Coverage reports are larger than capture events — the first one of an isolate
39
+ * carries the whole id→line map — so they get more headroom than
40
+ * {@link CAPTURE_POST_TIMEOUT_MS}. Still bounded, and for the same reason: an
41
+ * unreachable sidecar must not hold the request context open.
42
+ */
43
+ const COVERAGE_POST_TIMEOUT_MS = 5e3;
37
44
  /** POSTs capture events to the sidecar. Never rejects — reporting failures only warn (once). */
38
45
  const postCaptureEvents = async (transport, events) => {
39
46
  const timeoutMs = transport.kind === "binding" ? CAPTURE_POST_BINDING_TIMEOUT_MS : CAPTURE_POST_TIMEOUT_MS;
@@ -60,8 +67,8 @@ const postCaptureEvents = async (transport, events) => {
60
67
  * Asks whether the sidecar holds mocks for a session, and at what instant to freeze the
61
68
  * clock while serving it.
62
69
  *
63
- * A 404 is how a record-only sidecar answers, so it counts as a settled `unavailable` and
64
- * the shim degrades to pass-through against an older sidecar rather than failing.
70
+ * A 404 is how a record-only sidecar answers, so it counts as a settled `unavailable`
71
+ * rather than a retryable blip.
65
72
  */
66
73
  const getReplaySessionInfo = async (fetchFn, sidecarUrl, frontendSessionId) => {
67
74
  const url = `${sidecarUrl}${SIDECAR_REPLAY_SESSION_PATH}?sessionId=${encodeURIComponent(frontendSessionId)}`;
@@ -125,6 +132,40 @@ const postOutboundFetchLookup = async (fetchFn, sidecarUrl, payload) => {
125
132
  }
126
133
  };
127
134
  /**
135
+ * Reports one request's line coverage. Runs under `ctx.waitUntil`, so it is off
136
+ * the response path like record-mode capture reporting.
137
+ *
138
+ * Returns `unsupported` when the sidecar will never accept coverage (404 — an
139
+ * older sidecar, or one started without coverage enabled), which the caller
140
+ * latches so it stops paying to serialise hits for the rest of the isolate's
141
+ * life.
142
+ */
143
+ const postCoverageReport = async (fetchFn, sidecarUrl, payload) => {
144
+ try {
145
+ return await withTimeout(COVERAGE_POST_TIMEOUT_MS, async (signal) => {
146
+ const response = await fetchFn(`${sidecarUrl}${SIDECAR_REPLAY_COVERAGE_PATH}`, {
147
+ method: "POST",
148
+ headers: {
149
+ "content-type": "application/json",
150
+ [SIDECAR_PROTOCOL_VERSION_HEADER]: "2"
151
+ },
152
+ body: JSON.stringify(payload),
153
+ signal
154
+ });
155
+ await response.arrayBuffer().catch(() => void 0);
156
+ if (response.status === 404) return "unsupported";
157
+ if (!response.ok) {
158
+ warnOnce("coverage-rejected", `Meticulous replay sidecar rejected a coverage report (HTTP ${response.status}).`);
159
+ return "failed";
160
+ }
161
+ return "accepted";
162
+ });
163
+ } catch (error) {
164
+ warnOnce("coverage-unreachable", "Could not report line coverage to the Meticulous replay sidecar.", error);
165
+ return "failed";
166
+ }
167
+ };
168
+ /**
128
169
  * Runs `send` under an abort signal that fires after `ms`, clearing the timer as soon as the
129
170
  * call settles — including the response body read, which an abort must still cut short.
130
171
  *
@@ -144,7 +185,7 @@ const withTimeout = async (ms, send) => {
144
185
  }
145
186
  };
146
187
  //#endregion
147
- export { getReplaySessionInfo, postCaptureEvents, postOutboundFetchLookup };
188
+ export { getReplaySessionInfo, postCaptureEvents, postCoverageReport, postOutboundFetchLookup };
148
189
 
149
190
  //# sourceMappingURL=sidecar-client.js.map
150
- //# debugId=0d5c5735-7024-56f9-b25d-6b418c084332
191
+ //# debugId=4d6a9c0e-a5a7-52d6-8b38-28342d0f79e3
@@ -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 OutboundFetchLookupRequest,\n type OutboundFetchLookupResponse,\n type ReplaySessionInfoResponse,\n SIDECAR_EVENTS_PATH,\n SIDECAR_PROTOCOL_VERSION,\n SIDECAR_PROTOCOL_VERSION_HEADER,\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/** 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` and\n * the shim degrades to pass-through against an older sidecar rather than failing.\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 * 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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AAS;IACT,eACE,OAAO,KAAK,kBAAkB,WAC1B,KAAK,gBACL,KAAA;IACP;IACD;UACK,OAAO;AACd,WACE,8BACA,mFACA,MACD;AACD,SAAO,EAAE,SAAS,eAAe;;;;;;;;AASrC,MAAa,0BAA0B,OACrC,SACA,YACA,YACqD;AACrD,KAAI;AACF,SAAO,MAAM,YAAY,mBAAmB,OAAO,WAAW;GAC5D,MAAM,WAAW,MAAM,QACrB,GAAG,aAAa,sCAChB;IACE,QAAQ;IACR,SAAS;KACP,gBAAgB;MACf,kCAAA;KACF;IACD,MAAM,KAAK,UAAU,QAAQ;IAC7B;IACD,CACF;AACD,OAAI,CAAC,SAAS,IAAI;AAChB,aACE,0BACA,0DAA0D,SAAS,OAAO,IAC3E;AACD,UAAM,SAAS,aAAa,CAAC,YAAY,KAAA,EAAU;AACnD;;AAEF,UAAQ,MAAM,SAAS,MAAM;IAC7B;UACK,OAAO;AACd,WACE,6BACA,yFACA,MACD;AACD;;;;;;;;;;;;;AAcJ,MAAM,cAAc,OAClB,IACA,SACe;CACf,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,QAAQ,iBAAiB,WAAW,OAAO,EAAE,GAAG;AACtD,KAAI;AACF,SAAO,MAAM,KAAK,WAAW,OAAO;WAC5B;AACR,eAAa,MAAM","debugId":"0d5c5735-7024-56f9-b25d-6b418c084332"}
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":";;;;;;;;;;;;AAyBA,MAAM,0BAA0B;AAChC,MAAM,oBAAoB;;;;;;;;;;;;;;AAe1B,MAAM,0BAA0B;;;;;;;;AAShC,MAAM,kCAAkC;;;;;;;AAQxC,MAAM,2BAA2B;;AAGjC,MAAa,oBAAoB,OAC/B,WACA,WACkB;CAClB,MAAM,YACJ,UAAU,SAAS,YACf,kCACA;AACN,KAAI;EACF,MAAM,UAAgC,EAAE,QAAQ;AAChD,QAAM,YAAY,WAAW,OAAO,WAAW;GAC7C,MAAM,WAAW,MAAM,aACrB,WACA,kBAAkB,EAClB,qBACA;IACE,QAAQ;IACR,SAAS;KACP,gBAAgB;MACf,kCAAA;KACF;IACD,MAAM,KAAK,UAAU,QAAQ;IAC7B;IACD,CACF;AACD,OAAI,CAAC,SAAS,GACZ,UACE,oBACA,oDAAoD,SAAS,OAAO,IACrE;AAEH,SAAM,SAAS,aAAa,CAAC,YAAY,KAAA,EAAU;IACnD;UACK,OAAO;AACd,WACE,uBACA,4GACA,MACD;;;;;;;;;;AA2BL,MAAa,uBAAuB,OAClC,SACA,YACA,sBACqC;CACrC,MAAM,M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,YACmC;AACnC,KAAI;AACF,SAAO,MAAM,YAAY,0BAA0B,OAAO,WAAW;GACnE,MAAM,WAAW,MAAM,QACrB,GAAG,aAAa,gCAChB;IACE,QAAQ;IACR,SAAS;KACP,gBAAgB;MACf,kCAAA;KACF;IACD,MAAM,KAAK,UAAU,QAAQ;IAC7B;IACD,CACF;AACD,SAAM,SAAS,aAAa,CAAC,YAAY,KAAA,EAAU;AACnD,OAAI,SAAS,WAAW,IACtB,QAAO;AAET,OAAI,CAAC,SAAS,IAAI;AAChB,aACE,qBACA,8DAA8D,SAAS,OAAO,IAC/E;AACD,WAAO;;AAET,UAAO;IACP;UACK,OAAO;AACd,WACE,wBACA,oEACA,MACD;AACD,SAAO;;;;;;;;;;;;;AAcX,MAAM,cAAc,OAClB,IACA,SACe;CACf,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,QAAQ,iBAAiB,WAAW,OAAO,EAAE,GAAG;AACtD,KAAI;AACF,SAAO,MAAM,KAAK,WAAW,OAAO;WAC5B;AACR,eAAa,MAAM","debugId":"4d6a9c0e-a5a7-52d6-8b38-28342d0f79e3"}
@@ -5,7 +5,7 @@
5
5
  * parse, and using a reserved-by-RFC TLD makes it obvious in a log that no DNS was involved.
6
6
  */
7
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]="e6064d0d-3dc8-51c2-a764-d4b770eb2bc6")}catch(e){}}();
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
9
  const SIDECAR_BINDING_ORIGIN = "https://meticulous-sidecar.invalid";
10
10
  /** Env key holding a service binding to the Meticulous recorder sidecar Worker. */
11
11
  const SIDECAR_BINDING_ENV_KEY = "METICULOUS_SIDECAR";
@@ -49,4 +49,4 @@ const isFetcher = (value) => value !== null && typeof value === "object" && type
49
49
  export { SIDECAR_BINDING_ENV_KEY, SIDECAR_BINDING_ORIGIN, SIDECAR_URL_ENV_KEY, resolveSidecarTransport, sidecarFetch, transportOrigin };
50
50
 
51
51
  //# sourceMappingURL=sidecar-transport.js.map
52
- //# debugId=e6064d0d-3dc8-51c2-a764-d4b770eb2bc6
52
+ //# debugId=4c3fd120-a382-55e7-8105-c6ff77ac4d6e
@@ -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":"e6064d0d-3dc8-51c2-a764-d4b770eb2bc6"}
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"}
@@ -10,7 +10,7 @@
10
10
  */
11
11
  /** Tags which client library produced a CLIENT span. Absent on native `node:http` spans. */
12
12
 
13
- !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]="80380bd0-d3af-50b2-9954-96f676528992")}catch(e){}}();
13
+ !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]="9c7bae2d-7e8a-57e2-9065-56765d8c547b")}catch(e){}}();
14
14
  const CLIENT_TECHNOLOGY_ATTR = "meticulous.client_technology";
15
15
  /** Ties a backend span to the frontend session whose request produced it. */
16
16
  const FRONTEND_SESSION_ID_ATTR = "meticulous.frontend_session_id";
@@ -85,4 +85,4 @@ const WORKERD_KV_OMITTED_ATTR = "meticulous.workerd.kv.omitted";
85
85
  export { CLIENT_TECHNOLOGY_ATTR, CLIENT_TECHNOLOGY_POSTGRES_JS, CLIENT_TECHNOLOGY_WORKERD_BINDING, CLIENT_TECHNOLOGY_WORKERD_FETCH, CLIENT_TECHNOLOGY_WORKERD_KV, FRONTEND_SESSION_ID_ATTR, SESSION_ID_ORIGIN_ATTR, SESSION_ID_ORIGIN_BACKEND, WORKERD_BINDING_NAME_ATTR, WORKERD_KV_ARGS_ATTR, WORKERD_KV_ARGS_TRUNCATED_ATTR, WORKERD_KV_KEY_ATTR, WORKERD_KV_OMITTED_ATTR, WORKERD_KV_OPERATION_ATTR, WORKERD_KV_RESULT_ATTR, WORKERD_KV_RESULT_TRUNCATED_ATTR, WORKERD_KV_VALUE_ATTR, WORKERD_KV_VALUE_TRUNCATED_ATTR };
86
86
 
87
87
  //# sourceMappingURL=attributes.js.map
88
- //# debugId=80380bd0-d3af-50b2-9954-96f676528992
88
+ //# debugId=9c7bae2d-7e8a-57e2-9065-56765d8c547b
@@ -1 +1 @@
1
- {"version":3,"file":"attributes.js","sources":["../../src/spans/attributes.ts"],"sourcesContent":["/**\n * Span attribute names and technology tags shared by the two recording surfaces.\n *\n * These live here, in the package the in-worker shim ships from, for the same reason\n * `kv-capture.ts` does: a session recorded through workerd and one recorded through the Node\n * recorder have to be attribute-for-attribute identical, or a recording made on one cannot be\n * replayed by the other. `packages/backend-recorder-js/src/constants.ts` re-exports every name\n * below, so the Node recorder keeps one import site and there is one definition.\n */\n\n/** Tags which client library produced a CLIENT span. Absent on native `node:http` spans. */\nexport const CLIENT_TECHNOLOGY_ATTR = \"meticulous.client_technology\";\n\n/** Ties a backend span to the frontend session whose request produced it. */\nexport const FRONTEND_SESSION_ID_ATTR = \"meticulous.frontend_session_id\";\n\n/**\n * Where the session id on a span came from. Absent means the browser minted it and sent it on\n * the request, which is the normal case. `\"backend\"` means we minted it ourselves for a document\n * navigation the browser could not tag (see provisional-session-id.ts), and the page may or may\n * not have gone on to adopt it.\n *\n * The distinction is load-bearing for ingestion: an unadopted backend-minted id names a session\n * that will never exist, and must be treated as *unstamped* so those spans stay eligible for\n * time-window attachment — otherwise stamping them makes attribution worse than leaving them\n * bare. See `hasAnySessionId` in lambda-upload-sessions.\n */\nexport const SESSION_ID_ORIGIN_ATTR = \"meticulous.session_id_origin\";\nexport const SESSION_ID_ORIGIN_BACKEND = \"backend\";\n\n/**\n * An outgoing `fetch` from a Worker. Served back on replay by a `MockStore(\"workerd-fetch\")`\n * living in the replay sidecar, which the in-worker shim queries over plain HTTP (workerd cannot\n * run the Node mock instrumentations).\n *\n * This value travels in recorded session data, so it is a wire contract: the replay orchestrator\n * reads it back as `WORKERD_FETCH_CLIENT_TECHNOLOGY` in `@alwaysmeticulous/api` to decide whether\n * a recording needs a workerd replay sidecar. Keep the two in step.\n */\nexport const CLIENT_TECHNOLOGY_WORKERD_FETCH = \"workerd-fetch\";\n\n/**\n * A `fetch` through a Cloudflare binding — a service binding or a Durable Object stub. Recorded\n * from two places: the in-worker shim, and `withMeticulousCloudflareEnv` in a Node process whose\n * bindings come from wrangler's `getPlatformProxy`. Kept distinct from `workerd-fetch` because a\n * binding call never leaves the isolate and its URL is caller-invented, so the two must never be\n * matched against each other.\n */\nexport const CLIENT_TECHNOLOGY_WORKERD_BINDING = \"workerd-binding\";\n\n/**\n * An operation on a Cloudflare KV namespace binding, from the same two places. Its own technology\n * because a KV operation is not Request/Response-shaped at all — there is no method, URL or status\n * to match on, only a binding, an operation and a key.\n */\nexport const CLIENT_TECHNOLOGY_WORKERD_KV = \"workerd-kv\";\n\n/**\n * A postgres.js query, whether captured in Node (by the require hook or `withMeticulousPostgres`)\n * or in a deployed Worker. Deliberately distinct from `postgres` (node-postgres) so the two stores\n * never match each other's spans even though both talk to Postgres.\n */\nexport const CLIENT_TECHNOLOGY_POSTGRES_JS = \"postgres-js\";\n\n/**\n * The `env` key a binding call went through. Absent when the binding instance was never seen on\n * `env` — most commonly a Durable Object stub, which `namespace.get()` returns. Shared by\n * `fetch`-shaped binding spans and KV spans: both identify the binding this way.\n */\nexport const WORKERD_BINDING_NAME_ATTR = \"meticulous.workerd.binding\";\n\n/** Which KV method was called: `get`, `getWithMetadata`, `put`, `delete` or `list`. */\nexport const WORKERD_KV_OPERATION_ATTR = \"meticulous.workerd.kv.operation\";\n/** The key operated on. Absent for `list` and for a bulk `get`, whose keys are in the args. */\nexport const WORKERD_KV_KEY_ATTR = \"meticulous.workerd.kv.key\";\n/** JSON of the call's arguments; a `put` value appears as null (it lives in the value attr). */\nexport const WORKERD_KV_ARGS_ATTR = \"meticulous.workerd.kv.args\";\nexport const WORKERD_KV_ARGS_TRUNCATED_ATTR =\n \"meticulous.workerd.kv.args.truncated\";\n/** JSON of the value a `put` wrote, with secret-looking fields redacted. */\nexport const WORKERD_KV_VALUE_ATTR = \"meticulous.workerd.kv.value\";\nexport const WORKERD_KV_VALUE_TRUNCATED_ATTR =\n \"meticulous.workerd.kv.value.truncated\";\n/** JSON of what the operation returned. Absent for `put`/`delete`, which return nothing. */\nexport const WORKERD_KV_RESULT_ATTR = \"meticulous.workerd.kv.result\";\nexport const WORKERD_KV_RESULT_TRUNCATED_ATTR =\n \"meticulous.workerd.kv.result.truncated\";\n/**\n * Why a value is missing: `\"stream\"` (reading it would take the bytes from the app) or `\"binary\"`\n * (skipped deliberately — KV blobs are large and not UTF-8).\n */\nexport const WORKERD_KV_OMITTED_ATTR = \"meticulous.workerd.kv.omitted\";\n"],"names":[],"mappings":";;;;;;;;;;;;;AAWA,MAAa,yBAAyB;;AAGtC,MAAa,2BAA2B;;;;;;;;;;;;AAaxC,MAAa,yBAAyB;AACtC,MAAa,4BAA4B;;;;;;;;;;AAWzC,MAAa,kCAAkC;;;;;;;;AAS/C,MAAa,oCAAoC;;;;;;AAOjD,MAAa,+BAA+B;;;;;;AAO5C,MAAa,gCAAgC;;;;;;AAO7C,MAAa,4BAA4B;;AAGzC,MAAa,4BAA4B;;AAEzC,MAAa,sBAAsB;;AAEnC,MAAa,uBAAuB;AACpC,MAAa,iCACX;;AAEF,MAAa,wBAAwB;AACrC,MAAa,kCACX;;AAEF,MAAa,yBAAyB;AACtC,MAAa,mCACX;;;;;AAKF,MAAa,0BAA0B","debugId":"80380bd0-d3af-50b2-9954-96f676528992"}
1
+ {"version":3,"file":"attributes.js","sources":["../../src/spans/attributes.ts"],"sourcesContent":["/**\n * Span attribute names and technology tags shared by the two recording surfaces.\n *\n * These live here, in the package the in-worker shim ships from, for the same reason\n * `kv-capture.ts` does: a session recorded through workerd and one recorded through the Node\n * recorder have to be attribute-for-attribute identical, or a recording made on one cannot be\n * replayed by the other. `packages/backend-recorder-js/src/constants.ts` re-exports every name\n * below, so the Node recorder keeps one import site and there is one definition.\n */\n\n/** Tags which client library produced a CLIENT span. Absent on native `node:http` spans. */\nexport const CLIENT_TECHNOLOGY_ATTR = \"meticulous.client_technology\";\n\n/** Ties a backend span to the frontend session whose request produced it. */\nexport const FRONTEND_SESSION_ID_ATTR = \"meticulous.frontend_session_id\";\n\n/**\n * Where the session id on a span came from. Absent means the browser minted it and sent it on\n * the request, which is the normal case. `\"backend\"` means we minted it ourselves for a document\n * navigation the browser could not tag (see provisional-session-id.ts), and the page may or may\n * not have gone on to adopt it.\n *\n * The distinction is load-bearing for ingestion: an unadopted backend-minted id names a session\n * that will never exist, and must be treated as *unstamped* so those spans stay eligible for\n * time-window attachment — otherwise stamping them makes attribution worse than leaving them\n * bare. See `hasAnySessionId` in lambda-upload-sessions.\n */\nexport const SESSION_ID_ORIGIN_ATTR = \"meticulous.session_id_origin\";\nexport const SESSION_ID_ORIGIN_BACKEND = \"backend\";\n\n/**\n * An outgoing `fetch` from a Worker. Served back on replay by a `MockStore(\"workerd-fetch\")`\n * living in the replay sidecar, which the in-worker shim queries over plain HTTP (workerd cannot\n * run the Node mock instrumentations).\n *\n * This value travels in recorded session data, so it is a wire contract: the replay orchestrator\n * reads it back as `WORKERD_FETCH_CLIENT_TECHNOLOGY` in `@alwaysmeticulous/api` to decide whether\n * a recording needs a workerd replay sidecar. Keep the two in step.\n */\nexport const CLIENT_TECHNOLOGY_WORKERD_FETCH = \"workerd-fetch\";\n\n/**\n * A `fetch` through a Cloudflare binding — a service binding or a Durable Object stub. Recorded\n * from two places: the in-worker shim, and `withMeticulousCloudflareEnv` in a Node process whose\n * bindings come from wrangler's `getPlatformProxy`. Kept distinct from `workerd-fetch` because a\n * binding call never leaves the isolate and its URL is caller-invented, so the two must never be\n * matched against each other.\n */\nexport const CLIENT_TECHNOLOGY_WORKERD_BINDING = \"workerd-binding\";\n\n/**\n * An operation on a Cloudflare KV namespace binding, from the same two places. Its own technology\n * because a KV operation is not Request/Response-shaped at all — there is no method, URL or status\n * to match on, only a binding, an operation and a key.\n */\nexport const CLIENT_TECHNOLOGY_WORKERD_KV = \"workerd-kv\";\n\n/**\n * A postgres.js query, whether captured in Node (by the require hook or `withMeticulousPostgres`)\n * or in a deployed Worker. Deliberately distinct from `postgres` (node-postgres) so the two stores\n * never match each other's spans even though both talk to Postgres.\n */\nexport const CLIENT_TECHNOLOGY_POSTGRES_JS = \"postgres-js\";\n\n/**\n * The `env` key a binding call went through. Absent when the binding instance was never seen on\n * `env` — most commonly a Durable Object stub, which `namespace.get()` returns. Shared by\n * `fetch`-shaped binding spans and KV spans: both identify the binding this way.\n */\nexport const WORKERD_BINDING_NAME_ATTR = \"meticulous.workerd.binding\";\n\n/** Which KV method was called: `get`, `getWithMetadata`, `put`, `delete` or `list`. */\nexport const WORKERD_KV_OPERATION_ATTR = \"meticulous.workerd.kv.operation\";\n/** The key operated on. Absent for `list` and for a bulk `get`, whose keys are in the args. */\nexport const WORKERD_KV_KEY_ATTR = \"meticulous.workerd.kv.key\";\n/** JSON of the call's arguments; a `put` value appears as null (it lives in the value attr). */\nexport const WORKERD_KV_ARGS_ATTR = \"meticulous.workerd.kv.args\";\nexport const WORKERD_KV_ARGS_TRUNCATED_ATTR =\n \"meticulous.workerd.kv.args.truncated\";\n/** JSON of the value a `put` wrote, with secret-looking fields redacted. */\nexport const WORKERD_KV_VALUE_ATTR = \"meticulous.workerd.kv.value\";\nexport const WORKERD_KV_VALUE_TRUNCATED_ATTR =\n \"meticulous.workerd.kv.value.truncated\";\n/** JSON of what the operation returned. Absent for `put`/`delete`, which return nothing. */\nexport const WORKERD_KV_RESULT_ATTR = \"meticulous.workerd.kv.result\";\nexport const WORKERD_KV_RESULT_TRUNCATED_ATTR =\n \"meticulous.workerd.kv.result.truncated\";\n/**\n * Why a value is missing: `\"stream\"` (reading it would take the bytes from the app) or `\"binary\"`\n * (skipped deliberately — KV blobs are large and not UTF-8).\n */\nexport const WORKERD_KV_OMITTED_ATTR = \"meticulous.workerd.kv.omitted\";\n"],"names":[],"mappings":";;;;;;;;;;;;;AAWA,MAAa,yBAAyB;;AAGtC,MAAa,2BAA2B;;;;;;;;;;;;AAaxC,MAAa,yBAAyB;AACtC,MAAa,4BAA4B;;;;;;;;;;AAWzC,MAAa,kCAAkC;;;;;;;;AAS/C,MAAa,oCAAoC;;;;;;AAOjD,MAAa,+BAA+B;;;;;;AAO5C,MAAa,gCAAgC;;;;;;AAO7C,MAAa,4BAA4B;;AAGzC,MAAa,4BAA4B;;AAEzC,MAAa,sBAAsB;;AAEnC,MAAa,uBAAuB;AACpC,MAAa,iCACX;;AAEF,MAAa,wBAAwB;AACrC,MAAa,kCACX;;AAEF,MAAa,yBAAyB;AACtC,MAAa,mCACX;;;;;AAKF,MAAa,0BAA0B","debugId":"9c7bae2d-7e8a-57e2-9065-56765d8c547b"}
@@ -15,7 +15,7 @@
15
15
  * `@opentelemetry/api` for two numeric enums would put it in every customer's worker bundle.
16
16
  */
17
17
 
18
- !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]="ac19293d-f05f-503b-bbe1-10eeca91129c")}catch(e){}}();
18
+ !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]="4b8da1fb-2c09-5543-acf1-a30e8b358116")}catch(e){}}();
19
19
  const SPAN_KIND_INTERNAL = 0;
20
20
  const SPAN_KIND_SERVER = 1;
21
21
  const SPAN_KIND_CLIENT = 2;
@@ -32,4 +32,4 @@ const msToHrTime = (ms) => {
32
32
  export { SPAN_KIND_CLIENT, SPAN_KIND_INTERNAL, SPAN_KIND_SERVER, SPAN_STATUS_ERROR, SPAN_STATUS_OK, SPAN_STATUS_UNSET, hrTimeToMs, msToHrTime };
33
33
 
34
34
  //# sourceMappingURL=readable-span.js.map
35
- //# debugId=ac19293d-f05f-503b-bbe1-10eeca91129c
35
+ //# debugId=4b8da1fb-2c09-5543-acf1-a30e8b358116
@@ -1 +1 @@
1
- {"version":3,"file":"readable-span.js","sources":["../../src/spans/readable-span.ts"],"sourcesContent":["/**\n * The span shape both recording surfaces produce, and the serialization that turns it into the\n * JSON a recorded session is stored as.\n *\n * Lives here rather than in the Node recorder because a Worker-hosted sidecar has to write the\n * same wire format from inside workerd, where neither `@opentelemetry/api` nor the Node\n * recorder's bundle can be loaded. `packages/backend-recorder-js/src/exporters/span-serializer.ts`\n * re-exports all of this and layers its richer, per-instrumentation attribute types on top, so\n * the *logic* has exactly one implementation while the documentation types stay where they are\n * used.\n */\n\n/**\n * OpenTelemetry's `SpanKind`, inlined. The shim has no runtime dependencies — pulling in\n * `@opentelemetry/api` for two numeric enums would put it in every customer's worker bundle.\n */\nexport const SPAN_KIND_INTERNAL = 0;\nexport const SPAN_KIND_SERVER = 1;\nexport const SPAN_KIND_CLIENT = 2;\n\n/** OpenTelemetry's `SpanStatusCode`, inlined for the same reason. */\nexport const SPAN_STATUS_UNSET = 0;\nexport const SPAN_STATUS_OK = 1;\nexport const SPAN_STATUS_ERROR = 2;\n\nexport interface SpanStatus {\n code: number;\n message?: string;\n}\n\n/** `[seconds, nanoseconds]` — OpenTelemetry's `HrTime`. */\nexport type HrTime = [number, number];\n\nexport interface ReadableSpan {\n name: string;\n /**\n * Set by the hand-built spans in `span-builder.ts`. OTel-SDK spans carry the parent in\n * {@link ReadableSpan.parentSpanContext} instead.\n */\n parentSpanId?: string;\n /**\n * How an OTel-SDK span reports its parent since `@opentelemetry/sdk-trace-base` v2, which\n * dropped the flat `parentSpanId` field.\n */\n parentSpanContext?: { spanId: string };\n kind: number;\n status: unknown;\n startTime: HrTime;\n endTime: HrTime;\n duration: HrTime;\n attributes?: Record<string, unknown>;\n spanContext(): { traceId: string; spanId: string };\n}\n\n/**\n * A serialized span, with the attribute bag left open. The Node recorder narrows `attributes`\n * to its union of per-instrumentation contracts; nothing about the wire format depends on that\n * narrowing.\n */\nexport interface SerializedSpanBase {\n name: string;\n traceId: string;\n spanId: string;\n parentSpanId: string | undefined;\n kind: number;\n status: unknown;\n startTimeMs: number;\n endTimeMs: number;\n durationMs: number;\n clientTechnology?: string;\n frontendSessionId?: string;\n attributes: Record<string, unknown>;\n}\n\nexport const hrTimeToMs = (hrTime: HrTime): number =>\n hrTime[0] * 1000 + hrTime[1] / 1e6;\n\nexport const msToHrTime = (ms: number): HrTime => {\n const seconds = Math.floor(ms / 1000);\n return [seconds, Math.round((ms - seconds * 1000) * 1e6)];\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAgBA,MAAa,qBAAqB;AAClC,MAAa,mBAAmB;AAChC,MAAa,mBAAmB;;AAGhC,MAAa,oBAAoB;AACjC,MAAa,iBAAiB;AAC9B,MAAa,oBAAoB;AAmDjC,MAAa,cAAc,WACzB,OAAO,KAAK,MAAO,OAAO,KAAK;AAEjC,MAAa,cAAc,OAAuB;CAChD,MAAM,UAAU,KAAK,MAAM,KAAK,IAAK;AACrC,QAAO,CAAC,SAAS,KAAK,OAAO,KAAK,UAAU,OAAQ,IAAI,CAAC","debugId":"ac19293d-f05f-503b-bbe1-10eeca91129c"}
1
+ {"version":3,"file":"readable-span.js","sources":["../../src/spans/readable-span.ts"],"sourcesContent":["/**\n * The span shape both recording surfaces produce, and the serialization that turns it into the\n * JSON a recorded session is stored as.\n *\n * Lives here rather than in the Node recorder because a Worker-hosted sidecar has to write the\n * same wire format from inside workerd, where neither `@opentelemetry/api` nor the Node\n * recorder's bundle can be loaded. `packages/backend-recorder-js/src/exporters/span-serializer.ts`\n * re-exports all of this and layers its richer, per-instrumentation attribute types on top, so\n * the *logic* has exactly one implementation while the documentation types stay where they are\n * used.\n */\n\n/**\n * OpenTelemetry's `SpanKind`, inlined. The shim has no runtime dependencies — pulling in\n * `@opentelemetry/api` for two numeric enums would put it in every customer's worker bundle.\n */\nexport const SPAN_KIND_INTERNAL = 0;\nexport const SPAN_KIND_SERVER = 1;\nexport const SPAN_KIND_CLIENT = 2;\n\n/** OpenTelemetry's `SpanStatusCode`, inlined for the same reason. */\nexport const SPAN_STATUS_UNSET = 0;\nexport const SPAN_STATUS_OK = 1;\nexport const SPAN_STATUS_ERROR = 2;\n\nexport interface SpanStatus {\n code: number;\n message?: string;\n}\n\n/** `[seconds, nanoseconds]` — OpenTelemetry's `HrTime`. */\nexport type HrTime = [number, number];\n\nexport interface ReadableSpan {\n name: string;\n /**\n * Set by the hand-built spans in `span-builder.ts`. OTel-SDK spans carry the parent in\n * {@link ReadableSpan.parentSpanContext} instead.\n */\n parentSpanId?: string;\n /**\n * How an OTel-SDK span reports its parent since `@opentelemetry/sdk-trace-base` v2, which\n * dropped the flat `parentSpanId` field.\n */\n parentSpanContext?: { spanId: string };\n kind: number;\n status: unknown;\n startTime: HrTime;\n endTime: HrTime;\n duration: HrTime;\n attributes?: Record<string, unknown>;\n spanContext(): { traceId: string; spanId: string };\n}\n\n/**\n * A serialized span, with the attribute bag left open. The Node recorder narrows `attributes`\n * to its union of per-instrumentation contracts; nothing about the wire format depends on that\n * narrowing.\n */\nexport interface SerializedSpanBase {\n name: string;\n traceId: string;\n spanId: string;\n parentSpanId: string | undefined;\n kind: number;\n status: unknown;\n startTimeMs: number;\n endTimeMs: number;\n durationMs: number;\n clientTechnology?: string;\n frontendSessionId?: string;\n attributes: Record<string, unknown>;\n}\n\nexport const hrTimeToMs = (hrTime: HrTime): number =>\n hrTime[0] * 1000 + hrTime[1] / 1e6;\n\nexport const msToHrTime = (ms: number): HrTime => {\n const seconds = Math.floor(ms / 1000);\n return [seconds, Math.round((ms - seconds * 1000) * 1e6)];\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAgBA,MAAa,qBAAqB;AAClC,MAAa,mBAAmB;AAChC,MAAa,mBAAmB;;AAGhC,MAAa,oBAAoB;AACjC,MAAa,iBAAiB;AAC9B,MAAa,oBAAoB;AAmDjC,MAAa,cAAc,WACzB,OAAO,KAAK,MAAO,OAAO,KAAK;AAEjC,MAAa,cAAc,OAAuB;CAChD,MAAM,UAAU,KAAK,MAAM,KAAK,IAAK;AACrC,QAAO,CAAC,SAAS,KAAK,OAAO,KAAK,UAAU,OAAQ,IAAI,CAAC","debugId":"4b8da1fb-2c09-5543-acf1-a30e8b358116"}
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cfddc971-c481-52dc-a19b-556947e13f49")}catch(e){}}();
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]="e12748a8-3496-5830-8c8f-229beae7068b")}catch(e){}}();
3
3
  import { CLIENT_TECHNOLOGY_ATTR, FRONTEND_SESSION_ID_ATTR } from "./attributes.js";
4
4
  import { hrTimeToMs } from "./readable-span.js";
5
5
  //#region src/spans/serialize-span.ts
@@ -35,4 +35,4 @@ const serializeSpan = (span) => {
35
35
  export { serializeSpan };
36
36
 
37
37
  //# sourceMappingURL=serialize-span.js.map
38
- //# debugId=cfddc971-c481-52dc-a19b-556947e13f49
38
+ //# debugId=e12748a8-3496-5830-8c8f-229beae7068b
@@ -1 +1 @@
1
- {"version":3,"file":"serialize-span.js","sources":["../../src/spans/serialize-span.ts"],"sourcesContent":["import { CLIENT_TECHNOLOGY_ATTR, FRONTEND_SESSION_ID_ATTR } from \"./attributes\";\nimport {\n hrTimeToMs,\n type ReadableSpan,\n type SerializedSpanBase,\n} from \"./readable-span\";\n\n/**\n * Turns a span into the JSON shape a recorded backend session stores.\n *\n * Shared by the Node exporter and the Worker-hosted sidecar so the two cannot drift: ingestion\n * and every replay mock store read these field names, and a sidecar writing a near-miss of\n * this shape would produce recordings that load but never match.\n */\nexport const serializeSpan = (span: ReadableSpan): SerializedSpanBase => {\n const ctx = span.spanContext();\n // Copy so we never mutate the live OTel span's attributes.\n const attributes = { ...(span.attributes ?? {}) };\n\n const clientTechnology = attributes[CLIENT_TECHNOLOGY_ATTR] as\n | string\n | undefined;\n const frontendSessionId = attributes[FRONTEND_SESSION_ID_ATTR] as\n | string\n | undefined;\n\n // client_technology moves to the top level; frontend_session_id is copied (left in place for\n // backward compatibility — see download-sessions.ts in the webapp repo).\n delete attributes[CLIENT_TECHNOLOGY_ATTR];\n\n return {\n name: span.name,\n traceId: ctx.traceId,\n spanId: ctx.spanId,\n parentSpanId: span.parentSpanId ?? span.parentSpanContext?.spanId,\n kind: span.kind,\n status: span.status,\n startTimeMs: hrTimeToMs(span.startTime),\n endTimeMs: hrTimeToMs(span.endTime),\n durationMs: hrTimeToMs(span.duration),\n // Spread conditionally so we never emit `key: undefined` (exactOptionalPropertyTypes).\n ...(clientTechnology ? { clientTechnology } : {}),\n ...(frontendSessionId ? { frontendSessionId } : {}),\n attributes,\n };\n};\n"],"names":[],"mappings":";;;;;;;;;;;;AAcA,MAAa,iBAAiB,SAA2C;CACvE,MAAM,MAAM,KAAK,aAAa;CAE9B,MAAM,aAAa,EAAE,GAAI,KAAK,cAAc,EAAE,EAAG;CAEjD,MAAM,mBAAmB,WAAW;CAGpC,MAAM,oBAAoB,WAAW;AAMrC,QAAO,WAAW;AAElB,QAAO;EACL,MAAM,KAAK;EACX,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,cAAc,KAAK,gBAAgB,KAAK,mBAAmB;EAC3D,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,aAAa,WAAW,KAAK,UAAU;EACvC,WAAW,WAAW,KAAK,QAAQ;EACnC,YAAY,WAAW,KAAK,SAAS;EAErC,GAAI,mBAAmB,EAAE,kBAAkB,GAAG,EAAE;EAChD,GAAI,oBAAoB,EAAE,mBAAmB,GAAG,EAAE;EAClD;EACD","debugId":"cfddc971-c481-52dc-a19b-556947e13f49"}
1
+ {"version":3,"file":"serialize-span.js","sources":["../../src/spans/serialize-span.ts"],"sourcesContent":["import { CLIENT_TECHNOLOGY_ATTR, FRONTEND_SESSION_ID_ATTR } from \"./attributes\";\nimport {\n hrTimeToMs,\n type ReadableSpan,\n type SerializedSpanBase,\n} from \"./readable-span\";\n\n/**\n * Turns a span into the JSON shape a recorded backend session stores.\n *\n * Shared by the Node exporter and the Worker-hosted sidecar so the two cannot drift: ingestion\n * and every replay mock store read these field names, and a sidecar writing a near-miss of\n * this shape would produce recordings that load but never match.\n */\nexport const serializeSpan = (span: ReadableSpan): SerializedSpanBase => {\n const ctx = span.spanContext();\n // Copy so we never mutate the live OTel span's attributes.\n const attributes = { ...(span.attributes ?? {}) };\n\n const clientTechnology = attributes[CLIENT_TECHNOLOGY_ATTR] as\n | string\n | undefined;\n const frontendSessionId = attributes[FRONTEND_SESSION_ID_ATTR] as\n | string\n | undefined;\n\n // client_technology moves to the top level; frontend_session_id is copied (left in place for\n // backward compatibility — see download-sessions.ts in the webapp repo).\n delete attributes[CLIENT_TECHNOLOGY_ATTR];\n\n return {\n name: span.name,\n traceId: ctx.traceId,\n spanId: ctx.spanId,\n parentSpanId: span.parentSpanId ?? span.parentSpanContext?.spanId,\n kind: span.kind,\n status: span.status,\n startTimeMs: hrTimeToMs(span.startTime),\n endTimeMs: hrTimeToMs(span.endTime),\n durationMs: hrTimeToMs(span.duration),\n // Spread conditionally so we never emit `key: undefined` (exactOptionalPropertyTypes).\n ...(clientTechnology ? { clientTechnology } : {}),\n ...(frontendSessionId ? { frontendSessionId } : {}),\n attributes,\n };\n};\n"],"names":[],"mappings":";;;;;;;;;;;;AAcA,MAAa,iBAAiB,SAA2C;CACvE,MAAM,MAAM,KAAK,aAAa;CAE9B,MAAM,aAAa,EAAE,GAAI,KAAK,cAAc,EAAE,EAAG;CAEjD,MAAM,mBAAmB,WAAW;CAGpC,MAAM,oBAAoB,WAAW;AAMrC,QAAO,WAAW;AAElB,QAAO;EACL,MAAM,KAAK;EACX,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,cAAc,KAAK,gBAAgB,KAAK,mBAAmB;EAC3D,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,aAAa,WAAW,KAAK,UAAU;EACvC,WAAW,WAAW,KAAK,QAAQ;EACnC,YAAY,WAAW,KAAK,SAAS;EAErC,GAAI,mBAAmB,EAAE,kBAAkB,GAAG,EAAE;EAChD,GAAI,oBAAoB,EAAE,mBAAmB,GAAG,EAAE;EAClD;EACD","debugId":"e12748a8-3496-5830-8c8f-229beae7068b"}
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2d36ad42-81ac-5fed-988b-7d53c46a5f5d")}catch(e){}}();
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]="680329f2-970d-5fc7-89d6-78ab2702fa27")}catch(e){}}();
3
3
  import { CAPTURED_HEADERS } from "../protocol.js";
4
4
  import { MAX_POSTGRES_JS_RESULT_SIZE, POSTGRES_JS_ERROR_ATTR, POSTGRES_JS_QUERY_PARAMS_ATTR, POSTGRES_JS_QUERY_TEXT_ATTR, POSTGRES_JS_RESULT_ATTR, POSTGRES_JS_RESULT_TRUNCATED_ATTR, POSTGRES_JS_ROW_MODE_ATTR, postgresJsCommandOf } from "../postgres/capture.js";
5
5
  import { CLIENT_TECHNOLOGY_ATTR, CLIENT_TECHNOLOGY_POSTGRES_JS, CLIENT_TECHNOLOGY_WORKERD_BINDING, CLIENT_TECHNOLOGY_WORKERD_FETCH, CLIENT_TECHNOLOGY_WORKERD_KV, FRONTEND_SESSION_ID_ATTR, SESSION_ID_ORIGIN_ATTR, WORKERD_BINDING_NAME_ATTR, WORKERD_KV_ARGS_ATTR, WORKERD_KV_ARGS_TRUNCATED_ATTR, WORKERD_KV_KEY_ATTR, WORKERD_KV_OMITTED_ATTR, WORKERD_KV_OPERATION_ATTR, WORKERD_KV_RESULT_ATTR, WORKERD_KV_RESULT_TRUNCATED_ATTR, WORKERD_KV_VALUE_ATTR, WORKERD_KV_VALUE_TRUNCATED_ATTR } from "./attributes.js";
@@ -247,4 +247,4 @@ const buildStatus = (event, kind) => {
247
247
  export { SpanBuilder, randomHex };
248
248
 
249
249
  //# sourceMappingURL=span-builder.js.map
250
- //# debugId=2d36ad42-81ac-5fed-988b-7d53c46a5f5d
250
+ //# debugId=680329f2-970d-5fc7-89d6-78ab2702fa27
@@ -1 +1 @@
1
- {"version":3,"file":"span-builder.js","sources":["../../src/spans/span-builder.ts"],"sourcesContent":["import {\n type BindingRequestEvent,\n CAPTURED_HEADERS,\n type CaptureEvent,\n type InboundRequestEvent,\n type KvOperationEvent,\n type OutboundRequestEvent,\n type PostgresQueryEvent,\n} from \"../protocol\";\nimport {\n MAX_POSTGRES_JS_RESULT_SIZE,\n POSTGRES_JS_ERROR_ATTR,\n POSTGRES_JS_QUERY_PARAMS_ATTR,\n POSTGRES_JS_QUERY_TEXT_ATTR,\n POSTGRES_JS_RESULT_ATTR,\n POSTGRES_JS_RESULT_TRUNCATED_ATTR,\n POSTGRES_JS_ROW_MODE_ATTR,\n postgresJsCommandOf,\n} from \"../postgres/capture\";\nimport {\n CLIENT_TECHNOLOGY_ATTR,\n CLIENT_TECHNOLOGY_POSTGRES_JS,\n CLIENT_TECHNOLOGY_WORKERD_BINDING,\n CLIENT_TECHNOLOGY_WORKERD_FETCH,\n CLIENT_TECHNOLOGY_WORKERD_KV,\n FRONTEND_SESSION_ID_ATTR,\n SESSION_ID_ORIGIN_ATTR,\n WORKERD_BINDING_NAME_ATTR,\n WORKERD_KV_ARGS_ATTR,\n WORKERD_KV_ARGS_TRUNCATED_ATTR,\n WORKERD_KV_KEY_ATTR,\n WORKERD_KV_OMITTED_ATTR,\n WORKERD_KV_OPERATION_ATTR,\n WORKERD_KV_RESULT_ATTR,\n WORKERD_KV_RESULT_TRUNCATED_ATTR,\n WORKERD_KV_VALUE_ATTR,\n WORKERD_KV_VALUE_TRUNCATED_ATTR,\n} from \"./attributes\";\nimport {\n msToHrTime,\n type ReadableSpan,\n SPAN_KIND_CLIENT,\n SPAN_KIND_SERVER,\n SPAN_STATUS_ERROR,\n SPAN_STATUS_UNSET,\n type SpanStatus,\n} from \"./readable-span\";\nimport { redactUrlCredentials } from \"./url-redaction\";\n\n/**\n * Builds spans from shim capture events.\n *\n * Each inbound request becomes a SERVER span and the root of its own trace; every other event of\n * that request becomes a CLIENT span parented under it. The shim supplies the trace and\n * server-span ids (see `CorrelatedEvent`), so building a span needs no memory of earlier events\n * — which is what lets a Worker-hosted sidecar be evicted between two batches of one request\n * without splitting its trace.\n *\n * The `requestId → ids` fallback below exists only for a shim that predates those fields. It is\n * the reason this is a class rather than a function.\n *\n * Shared with the Node recorder's sidecar (`packages/backend-recorder-js/src/sidecar/`), which\n * re-exports it: both sidecars must produce identical spans or a recording made through one\n * cannot be replayed by the machinery built for the other.\n */\nexport class SpanBuilder {\n /**\n * Legacy fallback ids, keyed by `requestId`. Outbound events usually arrive BEFORE their\n * inbound event (the inbound is only reported once the handler completes), so an entry is\n * created lazily on first sight from either event kind.\n */\n private readonly traceContexts = new Map<string, TraceContextEntry>();\n\n build(event: CaptureEvent): ReadableSpan | null {\n switch (event.kind) {\n case \"inbound\":\n return this.buildInboundSpan(event);\n case \"outbound\":\n return this.buildOutboundSpan(event);\n case \"binding\":\n return this.buildBindingSpan(event);\n case \"kv\":\n return this.buildKvSpan(event);\n case \"postgres\":\n return this.buildPostgresSpan(event);\n default:\n // Wire input, possibly from a newer shim — skip rather than crash.\n return null;\n }\n }\n\n private buildInboundSpan(event: InboundRequestEvent): ReadableSpan {\n const ids = this.resolveIds(event);\n const url = parseUrl(event.url);\n const attributes = buildHttpAttributes(event, url);\n\n // Only the SERVER span carries it, matching MetHttpInstrumentation on the Node path: the\n // marker describes where this request's session id came from, and the CLIENT spans under\n // it share the same trace.\n if (event.sessionIdOrigin !== undefined) {\n attributes[SESSION_ID_ORIGIN_ATTR] = event.sessionIdOrigin;\n }\n\n return {\n name: `${event.method} ${url.path}`,\n kind: SPAN_KIND_SERVER,\n status: buildStatus(event, SPAN_KIND_SERVER),\n startTime: msToHrTime(event.startTimeMs),\n endTime: msToHrTime(event.endTimeMs),\n duration: msToHrTime(Math.max(0, event.endTimeMs - event.startTimeMs)),\n attributes,\n spanContext: () => ({\n traceId: ids.traceId,\n spanId: ids.serverSpanId,\n }),\n };\n }\n\n private buildOutboundSpan(event: OutboundRequestEvent): ReadableSpan {\n return this.buildHttpClientSpan(\n event,\n CLIENT_TECHNOLOGY_WORKERD_FETCH,\n event.method,\n );\n }\n\n /**\n * A binding call. Named after the binding rather than the bare method, since the `env` key is\n * what identifies the call — the URL is whatever the app invented.\n */\n private buildBindingSpan(event: BindingRequestEvent): ReadableSpan {\n return this.buildHttpClientSpan(\n event,\n CLIENT_TECHNOLOGY_WORKERD_BINDING,\n `${event.method} ${event.bindingName ?? \"$unknown\"}`,\n event.bindingName !== undefined\n ? { [WORKERD_BINDING_NAME_ATTR]: event.bindingName }\n : undefined,\n );\n }\n\n /**\n * A KV operation. Named `kv.<binding>.<operation>` after the Prisma convention\n * (`prisma.<model>.<operation>`) rather than the `METHOD TARGET` shape the HTTP-like spans use\n * — nothing about a KV call is an HTTP method, and the dotted name keeps a `get` on a\n * namespace distinguishable from a `GET` through a service binding at a glance.\n */\n private buildKvSpan(event: KvOperationEvent): ReadableSpan {\n const attributes: Record<string, unknown> = {\n [CLIENT_TECHNOLOGY_ATTR]: CLIENT_TECHNOLOGY_WORKERD_KV,\n [WORKERD_KV_OPERATION_ATTR]: event.operation,\n ...(event.bindingName !== undefined\n ? { [WORKERD_BINDING_NAME_ATTR]: event.bindingName }\n : {}),\n ...(event.key !== undefined ? { [WORKERD_KV_KEY_ATTR]: event.key } : {}),\n ...(event.omitted !== undefined\n ? { [WORKERD_KV_OMITTED_ATTR]: event.omitted }\n : {}),\n ...(event.error !== undefined ? { \"error.type\": event.error } : {}),\n ...frontendSessionAttribute(event),\n };\n if (event.args !== undefined) {\n attributes[WORKERD_KV_ARGS_ATTR] = event.args.body;\n attributes[WORKERD_KV_ARGS_TRUNCATED_ATTR] = event.args.truncated;\n }\n if (event.value !== undefined) {\n attributes[WORKERD_KV_VALUE_ATTR] = event.value.body;\n attributes[WORKERD_KV_VALUE_TRUNCATED_ATTR] = event.value.truncated;\n }\n if (event.result !== undefined) {\n attributes[WORKERD_KV_RESULT_ATTR] = event.result.body;\n attributes[WORKERD_KV_RESULT_TRUNCATED_ATTR] = event.result.truncated;\n }\n\n return this.buildClientSpan(\n event,\n `kv.${event.bindingName ?? \"$unknown\"}.${event.operation}`,\n attributes,\n event.error !== undefined\n ? { code: SPAN_STATUS_ERROR, message: event.error }\n : { code: SPAN_STATUS_UNSET },\n );\n }\n\n /**\n * A postgres.js query. Name and attributes match what the Node instrumentation emits\n * (`postgresjs.<command>`), because the same store loads both.\n */\n private buildPostgresSpan(event: PostgresQueryEvent): ReadableSpan {\n const attributes: Record<string, unknown> = {\n [CLIENT_TECHNOLOGY_ATTR]: CLIENT_TECHNOLOGY_POSTGRES_JS,\n [POSTGRES_JS_QUERY_TEXT_ATTR]: event.queryText,\n [POSTGRES_JS_QUERY_PARAMS_ATTR]: event.params,\n [POSTGRES_JS_ROW_MODE_ATTR]: event.rowMode,\n ...frontendSessionAttribute(event),\n };\n if (event.result !== undefined) {\n // Re-cap here as well as at capture time: the attribute contract is what the store\n // reads, and a shim that capped differently must not widen it.\n const truncated =\n event.result.truncated ||\n event.result.body.length > MAX_POSTGRES_JS_RESULT_SIZE;\n attributes[POSTGRES_JS_RESULT_ATTR] = truncated\n ? event.result.body.slice(0, MAX_POSTGRES_JS_RESULT_SIZE)\n : event.result.body;\n attributes[POSTGRES_JS_RESULT_TRUNCATED_ATTR] = truncated;\n }\n if (event.errorJson !== undefined) {\n attributes[POSTGRES_JS_ERROR_ATTR] = event.errorJson;\n }\n\n return this.buildClientSpan(\n event,\n `postgresjs.${postgresJsCommandOf(event.queryText)}`,\n attributes,\n event.errorJson !== undefined\n ? { code: SPAN_STATUS_ERROR }\n : { code: SPAN_STATUS_UNSET },\n );\n }\n\n private buildHttpClientSpan(\n event: OutboundRequestEvent | BindingRequestEvent,\n technology: string,\n name: string,\n extraAttributes?: Record<string, unknown>,\n ): ReadableSpan {\n const url = parseUrl(event.url);\n const attributes = buildHttpAttributes(event, url);\n attributes[CLIENT_TECHNOLOGY_ATTR] = technology;\n Object.assign(attributes, extraAttributes);\n if (event.requestBody !== undefined) {\n attributes[\"http.request.body\"] = event.requestBody.body;\n attributes[\"http.request.body.truncated\"] = event.requestBody.truncated;\n }\n if (event.responseBody !== undefined) {\n attributes[\"http.response.body\"] = event.responseBody.body;\n attributes[\"http.response.body.truncated\"] = event.responseBody.truncated;\n }\n\n return this.buildClientSpan(\n event,\n name,\n attributes,\n buildStatus(event, SPAN_KIND_CLIENT),\n );\n }\n\n private buildClientSpan(\n event: CaptureEvent,\n name: string,\n attributes: Record<string, unknown>,\n status: SpanStatus,\n ): ReadableSpan {\n const ids = this.resolveIds(event);\n const spanId = randomHex(8);\n return {\n name,\n parentSpanId: ids.serverSpanId,\n kind: SPAN_KIND_CLIENT,\n status,\n startTime: msToHrTime(event.startTimeMs),\n endTime: msToHrTime(event.endTimeMs),\n duration: msToHrTime(Math.max(0, event.endTimeMs - event.startTimeMs)),\n attributes,\n spanContext: () => ({ traceId: ids.traceId, spanId }),\n };\n }\n\n /**\n * The trace and server-span ids for an event: the shim's, when it sent them, and otherwise a\n * pair invented per `requestId` and remembered — the pre-`traceId` behaviour.\n */\n private resolveIds(event: CaptureEvent): TraceContextEntry {\n if (event.traceId !== undefined && event.serverSpanId !== undefined) {\n return {\n traceId: event.traceId,\n serverSpanId: event.serverSpanId,\n lastSeenMs: event.endTimeMs,\n };\n }\n const existing = this.traceContexts.get(event.requestId);\n if (existing) {\n existing.lastSeenMs = event.endTimeMs;\n return existing;\n }\n this.pruneTraceContexts(event.endTimeMs);\n const entry: TraceContextEntry = {\n traceId: randomHex(16),\n serverSpanId: randomHex(8),\n lastSeenMs: event.endTimeMs,\n };\n this.traceContexts.set(event.requestId, entry);\n return entry;\n }\n\n private pruneTraceContexts(nowMs: number): void {\n if (this.traceContexts.size < TRACE_CONTEXT_PRUNE_THRESHOLD) {\n return;\n }\n for (const [requestId, entry] of this.traceContexts) {\n if (nowMs - entry.lastSeenMs > TRACE_CONTEXT_TTL_MS) {\n this.traceContexts.delete(requestId);\n }\n }\n }\n}\n\ninterface TraceContextEntry {\n traceId: string;\n serverSpanId: string;\n lastSeenMs: number;\n}\n\nconst TRACE_CONTEXT_TTL_MS = 10 * 60 * 1000;\nconst TRACE_CONTEXT_PRUNE_THRESHOLD = 1_000;\n\nconst HEX = \"0123456789abcdef\";\n\n/** WebCrypto rather than `node:crypto`, so this runs in a Worker as well as in Node. */\nexport const randomHex = (bytes: number): string => {\n const buffer = crypto.getRandomValues(new Uint8Array(bytes));\n let hex = \"\";\n for (const byte of buffer) {\n hex += HEX[byte >> 4] + HEX[byte & 0x0f];\n }\n return hex;\n};\n\nconst capturedHeaders = new Set<string>(CAPTURED_HEADERS);\n\ninterface ParsedUrl {\n full: string;\n path: string;\n query: string | undefined;\n scheme: string | undefined;\n host: string | undefined;\n port: number | undefined;\n}\n\nconst parseUrl = (raw: string): ParsedUrl => {\n try {\n const url = redactUrlCredentials(new URL(raw));\n const defaultPort = url.protocol === \"https:\" ? 443 : 80;\n return {\n full: url.toString(),\n path: url.pathname,\n query: url.search ? url.search.slice(1) : undefined,\n scheme: url.protocol.replace(/:$/, \"\"),\n host: url.hostname,\n port: url.port ? parseInt(url.port, 10) : defaultPort,\n };\n } catch {\n return {\n full: raw,\n path: raw.split(\"?\")[0] || \"/\",\n query: undefined,\n scheme: undefined,\n host: undefined,\n port: undefined,\n };\n }\n};\n\nconst frontendSessionAttribute = (\n event: CaptureEvent,\n): Record<string, string> =>\n event.frontendSessionId !== undefined\n ? { [FRONTEND_SESSION_ID_ATTR]: event.frontendSessionId }\n : {};\n\nconst buildHttpAttributes = (\n event: InboundRequestEvent | OutboundRequestEvent | BindingRequestEvent,\n url: ParsedUrl,\n): Record<string, unknown> => {\n const attributes: Record<string, unknown> = {\n \"http.request.method\": event.method,\n \"url.full\": url.full,\n \"url.path\": url.path,\n ...(url.query !== undefined ? { \"url.query\": url.query } : {}),\n ...(url.scheme !== undefined ? { \"url.scheme\": url.scheme } : {}),\n ...(url.host !== undefined ? { \"server.address\": url.host } : {}),\n ...(url.port !== undefined ? { \"server.port\": url.port } : {}),\n ...(event.statusCode !== undefined\n ? { \"http.response.status_code\": event.statusCode }\n : {}),\n ...(event.error !== undefined ? { \"error.type\": event.error } : {}),\n ...frontendSessionAttribute(event),\n };\n // The shim already filters to CAPTURED_HEADERS; re-filter here so a stale or third-party\n // shim can't persist sensitive headers via the sidecar.\n for (const [name, values] of Object.entries(event.requestHeaders)) {\n if (capturedHeaders.has(name.toLowerCase())) {\n attributes[`http.request.header.${name}`] = values;\n }\n }\n for (const [name, values] of Object.entries(event.responseHeaders ?? {})) {\n if (capturedHeaders.has(name.toLowerCase())) {\n attributes[`http.response.header.${name}`] = values;\n }\n }\n return attributes;\n};\n\nconst buildStatus = (\n event: InboundRequestEvent | OutboundRequestEvent | BindingRequestEvent,\n kind: number,\n): SpanStatus => {\n if (event.error !== undefined) {\n return { code: SPAN_STATUS_ERROR, message: event.error };\n }\n // Standard OTel HTTP semantics: client spans error on 4xx/5xx, server spans only on 5xx.\n const errorThreshold = kind === SPAN_KIND_CLIENT ? 400 : 500;\n if (event.statusCode !== undefined && event.statusCode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5B,MAAM,aAAsC;EAC1C,uBAAuB,MAAM;EAC7B,YAAY,IAAI;EAChB,YAAY,IAAI;EAChB,GAAI,IAAI,UAAU,KAAA,IAAY,EAAE,aAAa,IAAI,OAAO,GAAG,EAAE;EAC7D,GAAI,IAAI,WAAW,KAAA,IAAY,EAAE,cAAc,IAAI,QAAQ,GAAG,EAAE;EAChE,GAAI,IAAI,SAAS,KAAA,IAAY,EAAE,kBAAkB,IAAI,MAAM,GAAG,EAAE;EAChE,GAAI,IAAI,SAAS,KAAA,IAAY,EAAE,eAAe,IAAI,MAAM,GAAG,EAAE;EAC7D,GAAI,MAAM,eAAe,KAAA,IACrB,EAAE,6BAA6B,MAAM,YAAY,GACjD,EAAE;EACN,GAAI,MAAM,UAAU,KAAA,IAAY,EAAE,cAAc,MAAM,OAAO,GAAG,EAAE;EAClE,GAAG,yBAAyB,MAAM;EACnC;AAGD,MAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,MAAM,eAAe,CAC/D,KAAI,gBAAgB,IAAI,KAAK,aAAa,CAAC,CACzC,YAAW,uBAAuB,UAAU;AAGhD,MAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,MAAM,mBAAmB,EAAE,CAAC,CACtE,KAAI,gBAAgB,IAAI,KAAK,aAAa,CAAC,CACzC,YAAW,wBAAwB,UAAU;AAGjD,QAAO;;AAGT,MAAM,eACJ,OACA,SACe;AACf,KAAI,MAAM,UAAU,KAAA,EAClB,QAAO;EAAE,MAAA;EAAyB,SAAS,MAAM;EAAO;CAG1D,MAAM,iBAAiB,SAAA,IAA4B,MAAM;AACzD,KAAI,MAAM,eAAe,KAAA,KAAa,MAAM,cAAc,eACxD,QAAO,EAAE,MAAA,GAAyB;AAEpC,QAAO,EAAE,MAAA,GAAyB","debugId":"2d36ad42-81ac-5fed-988b-7d53c46a5f5d"}
1
+ {"version":3,"file":"span-builder.js","sources":["../../src/spans/span-builder.ts"],"sourcesContent":["import {\n type BindingRequestEvent,\n CAPTURED_HEADERS,\n type CaptureEvent,\n type InboundRequestEvent,\n type KvOperationEvent,\n type OutboundRequestEvent,\n type PostgresQueryEvent,\n} from \"../protocol\";\nimport {\n MAX_POSTGRES_JS_RESULT_SIZE,\n POSTGRES_JS_ERROR_ATTR,\n POSTGRES_JS_QUERY_PARAMS_ATTR,\n POSTGRES_JS_QUERY_TEXT_ATTR,\n POSTGRES_JS_RESULT_ATTR,\n POSTGRES_JS_RESULT_TRUNCATED_ATTR,\n POSTGRES_JS_ROW_MODE_ATTR,\n postgresJsCommandOf,\n} from \"../postgres/capture\";\nimport {\n CLIENT_TECHNOLOGY_ATTR,\n CLIENT_TECHNOLOGY_POSTGRES_JS,\n CLIENT_TECHNOLOGY_WORKERD_BINDING,\n CLIENT_TECHNOLOGY_WORKERD_FETCH,\n CLIENT_TECHNOLOGY_WORKERD_KV,\n FRONTEND_SESSION_ID_ATTR,\n SESSION_ID_ORIGIN_ATTR,\n WORKERD_BINDING_NAME_ATTR,\n WORKERD_KV_ARGS_ATTR,\n WORKERD_KV_ARGS_TRUNCATED_ATTR,\n WORKERD_KV_KEY_ATTR,\n WORKERD_KV_OMITTED_ATTR,\n WORKERD_KV_OPERATION_ATTR,\n WORKERD_KV_RESULT_ATTR,\n WORKERD_KV_RESULT_TRUNCATED_ATTR,\n WORKERD_KV_VALUE_ATTR,\n WORKERD_KV_VALUE_TRUNCATED_ATTR,\n} from \"./attributes\";\nimport {\n msToHrTime,\n type ReadableSpan,\n SPAN_KIND_CLIENT,\n SPAN_KIND_SERVER,\n SPAN_STATUS_ERROR,\n SPAN_STATUS_UNSET,\n type SpanStatus,\n} from \"./readable-span\";\nimport { redactUrlCredentials } from \"./url-redaction\";\n\n/**\n * Builds spans from shim capture events.\n *\n * Each inbound request becomes a SERVER span and the root of its own trace; every other event of\n * that request becomes a CLIENT span parented under it. The shim supplies the trace and\n * server-span ids (see `CorrelatedEvent`), so building a span needs no memory of earlier events\n * — which is what lets a Worker-hosted sidecar be evicted between two batches of one request\n * without splitting its trace.\n *\n * The `requestId → ids` fallback below exists only for a shim that predates those fields. It is\n * the reason this is a class rather than a function.\n *\n * Shared with the Node recorder's sidecar (`packages/backend-recorder-js/src/sidecar/`), which\n * re-exports it: both sidecars must produce identical spans or a recording made through one\n * cannot be replayed by the machinery built for the other.\n */\nexport class SpanBuilder {\n /**\n * Legacy fallback ids, keyed by `requestId`. Outbound events usually arrive BEFORE their\n * inbound event (the inbound is only reported once the handler completes), so an entry is\n * created lazily on first sight from either event kind.\n */\n private readonly traceContexts = new Map<string, TraceContextEntry>();\n\n build(event: CaptureEvent): ReadableSpan | null {\n switch (event.kind) {\n case \"inbound\":\n return this.buildInboundSpan(event);\n case \"outbound\":\n return this.buildOutboundSpan(event);\n case \"binding\":\n return this.buildBindingSpan(event);\n case \"kv\":\n return this.buildKvSpan(event);\n case \"postgres\":\n return this.buildPostgresSpan(event);\n default:\n // Wire input, possibly from a newer shim — skip rather than crash.\n return null;\n }\n }\n\n private buildInboundSpan(event: InboundRequestEvent): ReadableSpan {\n const ids = this.resolveIds(event);\n const url = parseUrl(event.url);\n const attributes = buildHttpAttributes(event, url);\n\n // Only the SERVER span carries it, matching MetHttpInstrumentation on the Node path: the\n // marker describes where this request's session id came from, and the CLIENT spans under\n // it share the same trace.\n if (event.sessionIdOrigin !== undefined) {\n attributes[SESSION_ID_ORIGIN_ATTR] = event.sessionIdOrigin;\n }\n\n return {\n name: `${event.method} ${url.path}`,\n kind: SPAN_KIND_SERVER,\n status: buildStatus(event, SPAN_KIND_SERVER),\n startTime: msToHrTime(event.startTimeMs),\n endTime: msToHrTime(event.endTimeMs),\n duration: msToHrTime(Math.max(0, event.endTimeMs - event.startTimeMs)),\n attributes,\n spanContext: () => ({\n traceId: ids.traceId,\n spanId: ids.serverSpanId,\n }),\n };\n }\n\n private buildOutboundSpan(event: OutboundRequestEvent): ReadableSpan {\n return this.buildHttpClientSpan(\n event,\n CLIENT_TECHNOLOGY_WORKERD_FETCH,\n event.method,\n );\n }\n\n /**\n * A binding call. Named after the binding rather than the bare method, since the `env` key is\n * what identifies the call — the URL is whatever the app invented.\n */\n private buildBindingSpan(event: BindingRequestEvent): ReadableSpan {\n return this.buildHttpClientSpan(\n event,\n CLIENT_TECHNOLOGY_WORKERD_BINDING,\n `${event.method} ${event.bindingName ?? \"$unknown\"}`,\n event.bindingName !== undefined\n ? { [WORKERD_BINDING_NAME_ATTR]: event.bindingName }\n : undefined,\n );\n }\n\n /**\n * A KV operation. Named `kv.<binding>.<operation>` after the Prisma convention\n * (`prisma.<model>.<operation>`) rather than the `METHOD TARGET` shape the HTTP-like spans use\n * — nothing about a KV call is an HTTP method, and the dotted name keeps a `get` on a\n * namespace distinguishable from a `GET` through a service binding at a glance.\n */\n private buildKvSpan(event: KvOperationEvent): ReadableSpan {\n const attributes: Record<string, unknown> = {\n [CLIENT_TECHNOLOGY_ATTR]: CLIENT_TECHNOLOGY_WORKERD_KV,\n [WORKERD_KV_OPERATION_ATTR]: event.operation,\n ...(event.bindingName !== undefined\n ? { [WORKERD_BINDING_NAME_ATTR]: event.bindingName }\n : {}),\n ...(event.key !== undefined ? { [WORKERD_KV_KEY_ATTR]: event.key } : {}),\n ...(event.omitted !== undefined\n ? { [WORKERD_KV_OMITTED_ATTR]: event.omitted }\n : {}),\n ...(event.error !== undefined ? { \"error.type\": event.error } : {}),\n ...frontendSessionAttribute(event),\n };\n if (event.args !== undefined) {\n attributes[WORKERD_KV_ARGS_ATTR] = event.args.body;\n attributes[WORKERD_KV_ARGS_TRUNCATED_ATTR] = event.args.truncated;\n }\n if (event.value !== undefined) {\n attributes[WORKERD_KV_VALUE_ATTR] = event.value.body;\n attributes[WORKERD_KV_VALUE_TRUNCATED_ATTR] = event.value.truncated;\n }\n if (event.result !== undefined) {\n attributes[WORKERD_KV_RESULT_ATTR] = event.result.body;\n attributes[WORKERD_KV_RESULT_TRUNCATED_ATTR] = event.result.truncated;\n }\n\n return this.buildClientSpan(\n event,\n `kv.${event.bindingName ?? \"$unknown\"}.${event.operation}`,\n attributes,\n event.error !== undefined\n ? { code: SPAN_STATUS_ERROR, message: event.error }\n : { code: SPAN_STATUS_UNSET },\n );\n }\n\n /**\n * A postgres.js query. Name and attributes match what the Node instrumentation emits\n * (`postgresjs.<command>`), because the same store loads both.\n */\n private buildPostgresSpan(event: PostgresQueryEvent): ReadableSpan {\n const attributes: Record<string, unknown> = {\n [CLIENT_TECHNOLOGY_ATTR]: CLIENT_TECHNOLOGY_POSTGRES_JS,\n [POSTGRES_JS_QUERY_TEXT_ATTR]: event.queryText,\n [POSTGRES_JS_QUERY_PARAMS_ATTR]: event.params,\n [POSTGRES_JS_ROW_MODE_ATTR]: event.rowMode,\n ...frontendSessionAttribute(event),\n };\n if (event.result !== undefined) {\n // Re-cap here as well as at capture time: the attribute contract is what the store\n // reads, and a shim that capped differently must not widen it.\n const truncated =\n event.result.truncated ||\n event.result.body.length > MAX_POSTGRES_JS_RESULT_SIZE;\n attributes[POSTGRES_JS_RESULT_ATTR] = truncated\n ? event.result.body.slice(0, MAX_POSTGRES_JS_RESULT_SIZE)\n : event.result.body;\n attributes[POSTGRES_JS_RESULT_TRUNCATED_ATTR] = truncated;\n }\n if (event.errorJson !== undefined) {\n attributes[POSTGRES_JS_ERROR_ATTR] = event.errorJson;\n }\n\n return this.buildClientSpan(\n event,\n `postgresjs.${postgresJsCommandOf(event.queryText)}`,\n attributes,\n event.errorJson !== undefined\n ? { code: SPAN_STATUS_ERROR }\n : { code: SPAN_STATUS_UNSET },\n );\n }\n\n private buildHttpClientSpan(\n event: OutboundRequestEvent | BindingRequestEvent,\n technology: string,\n name: string,\n extraAttributes?: Record<string, unknown>,\n ): ReadableSpan {\n const url = parseUrl(event.url);\n const attributes = buildHttpAttributes(event, url);\n attributes[CLIENT_TECHNOLOGY_ATTR] = technology;\n Object.assign(attributes, extraAttributes);\n if (event.requestBody !== undefined) {\n attributes[\"http.request.body\"] = event.requestBody.body;\n attributes[\"http.request.body.truncated\"] = event.requestBody.truncated;\n }\n if (event.responseBody !== undefined) {\n attributes[\"http.response.body\"] = event.responseBody.body;\n attributes[\"http.response.body.truncated\"] = event.responseBody.truncated;\n }\n\n return this.buildClientSpan(\n event,\n name,\n attributes,\n buildStatus(event, SPAN_KIND_CLIENT),\n );\n }\n\n private buildClientSpan(\n event: CaptureEvent,\n name: string,\n attributes: Record<string, unknown>,\n status: SpanStatus,\n ): ReadableSpan {\n const ids = this.resolveIds(event);\n const spanId = randomHex(8);\n return {\n name,\n parentSpanId: ids.serverSpanId,\n kind: SPAN_KIND_CLIENT,\n status,\n startTime: msToHrTime(event.startTimeMs),\n endTime: msToHrTime(event.endTimeMs),\n duration: msToHrTime(Math.max(0, event.endTimeMs - event.startTimeMs)),\n attributes,\n spanContext: () => ({ traceId: ids.traceId, spanId }),\n };\n }\n\n /**\n * The trace and server-span ids for an event: the shim's, when it sent them, and otherwise a\n * pair invented per `requestId` and remembered — the pre-`traceId` behaviour.\n */\n private resolveIds(event: CaptureEvent): TraceContextEntry {\n if (event.traceId !== undefined && event.serverSpanId !== undefined) {\n return {\n traceId: event.traceId,\n serverSpanId: event.serverSpanId,\n lastSeenMs: event.endTimeMs,\n };\n }\n const existing = this.traceContexts.get(event.requestId);\n if (existing) {\n existing.lastSeenMs = event.endTimeMs;\n return existing;\n }\n this.pruneTraceContexts(event.endTimeMs);\n const entry: TraceContextEntry = {\n traceId: randomHex(16),\n serverSpanId: randomHex(8),\n lastSeenMs: event.endTimeMs,\n };\n this.traceContexts.set(event.requestId, entry);\n return entry;\n }\n\n private pruneTraceContexts(nowMs: number): void {\n if (this.traceContexts.size < TRACE_CONTEXT_PRUNE_THRESHOLD) {\n return;\n }\n for (const [requestId, entry] of this.traceContexts) {\n if (nowMs - entry.lastSeenMs > TRACE_CONTEXT_TTL_MS) {\n this.traceContexts.delete(requestId);\n }\n }\n }\n}\n\ninterface TraceContextEntry {\n traceId: string;\n serverSpanId: string;\n lastSeenMs: number;\n}\n\nconst TRACE_CONTEXT_TTL_MS = 10 * 60 * 1000;\nconst TRACE_CONTEXT_PRUNE_THRESHOLD = 1_000;\n\nconst HEX = \"0123456789abcdef\";\n\n/** WebCrypto rather than `node:crypto`, so this runs in a Worker as well as in Node. */\nexport const randomHex = (bytes: number): string => {\n const buffer = crypto.getRandomValues(new Uint8Array(bytes));\n let hex = \"\";\n for (const byte of buffer) {\n hex += HEX[byte >> 4] + HEX[byte & 0x0f];\n }\n return hex;\n};\n\nconst capturedHeaders = new Set<string>(CAPTURED_HEADERS);\n\ninterface ParsedUrl {\n full: string;\n path: string;\n query: string | undefined;\n scheme: string | undefined;\n host: string | undefined;\n port: number | undefined;\n}\n\nconst parseUrl = (raw: string): ParsedUrl => {\n try {\n const url = redactUrlCredentials(new URL(raw));\n const defaultPort = url.protocol === \"https:\" ? 443 : 80;\n return {\n full: url.toString(),\n path: url.pathname,\n query: url.search ? url.search.slice(1) : undefined,\n scheme: url.protocol.replace(/:$/, \"\"),\n host: url.hostname,\n port: url.port ? parseInt(url.port, 10) : defaultPort,\n };\n } catch {\n return {\n full: raw,\n path: raw.split(\"?\")[0] || \"/\",\n query: undefined,\n scheme: undefined,\n host: undefined,\n port: undefined,\n };\n }\n};\n\nconst frontendSessionAttribute = (\n event: CaptureEvent,\n): Record<string, string> =>\n event.frontendSessionId !== undefined\n ? { [FRONTEND_SESSION_ID_ATTR]: event.frontendSessionId }\n : {};\n\nconst buildHttpAttributes = (\n event: InboundRequestEvent | OutboundRequestEvent | BindingRequestEvent,\n url: ParsedUrl,\n): Record<string, unknown> => {\n const attributes: Record<string, unknown> = {\n \"http.request.method\": event.method,\n \"url.full\": url.full,\n \"url.path\": url.path,\n ...(url.query !== undefined ? { \"url.query\": url.query } : {}),\n ...(url.scheme !== undefined ? { \"url.scheme\": url.scheme } : {}),\n ...(url.host !== undefined ? { \"server.address\": url.host } : {}),\n ...(url.port !== undefined ? { \"server.port\": url.port } : {}),\n ...(event.statusCode !== undefined\n ? { \"http.response.status_code\": event.statusCode }\n : {}),\n ...(event.error !== undefined ? { \"error.type\": event.error } : {}),\n ...frontendSessionAttribute(event),\n };\n // The shim already filters to CAPTURED_HEADERS; re-filter here so a stale or third-party\n // shim can't persist sensitive headers via the sidecar.\n for (const [name, values] of Object.entries(event.requestHeaders)) {\n if (capturedHeaders.has(name.toLowerCase())) {\n attributes[`http.request.header.${name}`] = values;\n }\n }\n for (const [name, values] of Object.entries(event.responseHeaders ?? {})) {\n if (capturedHeaders.has(name.toLowerCase())) {\n attributes[`http.response.header.${name}`] = values;\n }\n }\n return attributes;\n};\n\nconst buildStatus = (\n event: InboundRequestEvent | OutboundRequestEvent | BindingRequestEvent,\n kind: number,\n): SpanStatus => {\n if (event.error !== undefined) {\n return { code: SPAN_STATUS_ERROR, message: event.error };\n }\n // Standard OTel HTTP semantics: client spans error on 4xx/5xx, server spans only on 5xx.\n const errorThreshold = kind === SPAN_KIND_CLIENT ? 400 : 500;\n if (event.statusCode !== undefined && event.statusCode >= errorThreshold) {\n return { code: SPAN_STATUS_ERROR };\n }\n return { code: SPAN_STATUS_UNSET };\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiEA,IAAa,cAAb,MAAyB;;;;;;CAMvB,gCAAiC,IAAI,KAAgC;CAErE,MAAM,OAA0C;AAC9C,UAAQ,MAAM,MAAd;GACE,KAAK,UACH,QAAO,KAAK,iBAAiB,MAAM;GACrC,KAAK,WACH,QAAO,KAAK,kBAAkB,MAAM;GACtC,KAAK,UACH,QAAO,KAAK,iBAAiB,MAAM;GACrC,KAAK,KACH,QAAO,KAAK,YAAY,MAAM;GAChC,KAAK,WACH,QAAO,KAAK,kBAAkB,MAAM;GACtC,QAEE,QAAO;;;CAIb,iBAAyB,OAA0C;EACjE,MAAM,MAAM,KAAK,WAAW,MAAM;EAClC,MAAM,MAAM,SAAS,MAAM,IAAI;EAC/B,MAAM,aAAa,oBAAoB,OAAO,IAAI;AAKlD,MAAI,MAAM,oBAAoB,KAAA,EAC5B,YAAW,0BA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AK,aAAa,CAAC,CACzC,YAAW,uBAAuB,UAAU;AAGhD,MAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,MAAM,mBAAmB,EAAE,CAAC,CACtE,KAAI,gBAAgB,IAAI,KAAK,aAAa,CAAC,CACzC,YAAW,wBAAwB,UAAU;AAGjD,QAAO;;AAGT,MAAM,eACJ,OACA,SACe;AACf,KAAI,MAAM,UAAU,KAAA,EAClB,QAAO;EAAE,MAAA;EAAyB,SAAS,MAAM;EAAO;CAG1D,MAAM,iBAAiB,SAAA,IAA4B,MAAM;AACzD,KAAI,MAAM,eAAe,KAAA,KAAa,MAAM,cAAc,eACxD,QAAO,EAAE,MAAA,GAAyB;AAEpC,QAAO,EAAE,MAAA,GAAyB","debugId":"680329f2-970d-5fc7-89d6-78ab2702fa27"}
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a4ffc294-14bc-5f17-bbca-b0279e4181be")}catch(e){}}();
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]="8b13fac8-683e-5692-90a7-5cdfd2b8035d")}catch(e){}}();
3
3
  import { STR_REDACTED } from "../redact-body.js";
4
4
  //#region src/spans/url-redaction.ts
5
5
  /**
@@ -37,4 +37,4 @@ const redactUrlCredentials = (url) => {
37
37
  export { redactUrlCredentials };
38
38
 
39
39
  //# sourceMappingURL=url-redaction.js.map
40
- //# debugId=a4ffc294-14bc-5f17-bbca-b0279e4181be
40
+ //# debugId=8b13fac8-683e-5692-90a7-5cdfd2b8035d
@@ -1 +1 @@
1
- {"version":3,"file":"url-redaction.js","sources":["../../src/spans/url-redaction.ts"],"sourcesContent":["import { STR_REDACTED } from \"../redact-body\";\n\n/**\n * URL query keys that carry a credential rather than identify a resource.\n *\n * Mirrors `DEFAULT_QUERY_STRINGS_TO_REDACT` in the Node recorder's forked http\n * instrumentation. Both surfaces write URLs onto the same spans, so the two lists have to stay\n * identical or the same request records differently depending on where it was captured.\n */\nconst QUERY_STRINGS_TO_REDACT = [\n \"sig\",\n \"Signature\",\n \"AWSAccessKeyId\",\n \"X-Goog-Signature\",\n] as const;\n\n/**\n * Returns a copy of the URL with credential-bearing parts replaced: the signature-style query\n * parameters above, and any `user:password@` userinfo.\n *\n * Record side only. A replay lookup passes the live URL through unredacted, exactly as the\n * http, undici and sidecar lookup paths do, so a redacted parameter misses the exact tier and\n * is served by the drop-query tier instead — the right outcome, since a signature could not\n * have matched exactly across a record/replay boundary anyway.\n */\nexport const redactUrlCredentials = (url: URL): URL => {\n const redacted = new URL(url.href);\n for (const sensitiveParam of QUERY_STRINGS_TO_REDACT) {\n if (redacted.searchParams.get(sensitiveParam)) {\n redacted.searchParams.set(sensitiveParam, STR_REDACTED);\n }\n }\n if (redacted.username || redacted.password) {\n redacted.username = STR_REDACTED;\n redacted.password = STR_REDACTED;\n }\n return redacted;\n};\n"],"names":[],"mappings":";;;;;;;;;;;AASA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACD;;;;;;;;;;AAWD,MAAa,wBAAwB,QAAkB;CACrD,MAAM,WAAW,IAAI,IAAI,IAAI,KAAK;AAClC,MAAK,MAAM,kBAAkB,wBAC3B,KAAI,SAAS,aAAa,IAAI,eAAe,CAC3C,UAAS,aAAa,IAAI,gBAAgB,aAAa;AAG3D,KAAI,SAAS,YAAY,SAAS,UAAU;AAC1C,WAAS,WAAW;AACpB,WAAS,WAAW;;AAEtB,QAAO","debugId":"a4ffc294-14bc-5f17-bbca-b0279e4181be"}
1
+ {"version":3,"file":"url-redaction.js","sources":["../../src/spans/url-redaction.ts"],"sourcesContent":["import { STR_REDACTED } from \"../redact-body\";\n\n/**\n * URL query keys that carry a credential rather than identify a resource.\n *\n * Mirrors `DEFAULT_QUERY_STRINGS_TO_REDACT` in the Node recorder's forked http\n * instrumentation. Both surfaces write URLs onto the same spans, so the two lists have to stay\n * identical or the same request records differently depending on where it was captured.\n */\nconst QUERY_STRINGS_TO_REDACT = [\n \"sig\",\n \"Signature\",\n \"AWSAccessKeyId\",\n \"X-Goog-Signature\",\n] as const;\n\n/**\n * Returns a copy of the URL with credential-bearing parts replaced: the signature-style query\n * parameters above, and any `user:password@` userinfo.\n *\n * Record side only. A replay lookup passes the live URL through unredacted, exactly as the\n * http, undici and sidecar lookup paths do, so a redacted parameter misses the exact tier and\n * is served by the drop-query tier instead — the right outcome, since a signature could not\n * have matched exactly across a record/replay boundary anyway.\n */\nexport const redactUrlCredentials = (url: URL): URL => {\n const redacted = new URL(url.href);\n for (const sensitiveParam of QUERY_STRINGS_TO_REDACT) {\n if (redacted.searchParams.get(sensitiveParam)) {\n redacted.searchParams.set(sensitiveParam, STR_REDACTED);\n }\n }\n if (redacted.username || redacted.password) {\n redacted.username = STR_REDACTED;\n redacted.password = STR_REDACTED;\n }\n return redacted;\n};\n"],"names":[],"mappings":";;;;;;;;;;;AASA,MAAM,0BAA0B;CAC9B;CACA;CACA;CACA;CACD;;;;;;;;;;AAWD,MAAa,wBAAwB,QAAkB;CACrD,MAAM,WAAW,IAAI,IAAI,IAAI,KAAK;AAClC,MAAK,MAAM,kBAAkB,wBAC3B,KAAI,SAAS,aAAa,IAAI,eAAe,CAC3C,UAAS,aAAa,IAAI,gBAAgB,aAAa;AAG3D,KAAI,SAAS,YAAY,SAAS,UAAU;AAC1C,WAAS,WAAW;AACpB,WAAS,WAAW;;AAEtB,QAAO","debugId":"8b13fac8-683e-5692-90a7-5cdfd2b8035d"}
@@ -0,0 +1,14 @@
1
+ //#region src/version.d.ts
2
+ /**
3
+ * npm package version of this shim, baked in at build time. Customers bump
4
+ * `@alwaysmeticulous/backend-recorder-workerd` independently of our cloud
5
+ * deploy, so this is the only way a replay can tell which bundled shim
6
+ * produced its After screenshots.
7
+ *
8
+ * Replaced by tsdown's `define`. The guard keeps a direct source import
9
+ * (vitest, typecheck) working, where no bundler has substituted the value.
10
+ */
11
+ declare const WORKERD_SHIM_VERSION: string;
12
+ //#endregion
13
+ export { WORKERD_SHIM_VERSION };
14
+ //# sourceMappingURL=version.d.ts.map