@alwaysmeticulous/backend-recorder-workerd 2.319.0 → 2.323.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -2
- package/dist/fetch-patch.js +4 -3
- package/dist/fetch-patch.js.map +1 -1
- package/dist/index.d.ts +12 -6
- package/dist/index.js +0 -0
- package/dist/index.js.map +1 -1
- package/dist/kv-patch.js +261 -0
- package/dist/kv-patch.js.map +1 -0
- package/dist/log.js +11 -3
- package/dist/log.js.map +1 -1
- package/dist/protocol.d.ts +88 -6
- package/dist/protocol.js +13 -3
- package/dist/protocol.js.map +1 -1
- package/dist/replay-fetch.js +63 -15
- package/dist/replay-fetch.js.map +1 -1
- package/dist/sidecar-client.js +86 -54
- package/dist/sidecar-client.js.map +1 -1
- package/dist/virtual-random.js +238 -0
- package/dist/virtual-random.js.map +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,6 +36,8 @@ The shim is passive: outgoing requests go straight to their real destination; th
|
|
|
36
36
|
npx @alwaysmeticulous/cli record backend -- npx wrangler dev
|
|
37
37
|
```
|
|
38
38
|
|
|
39
|
+
If the recorder cannot start — no credentials, no network to fetch the sidecar bundle, an unusable port — the CLI warns and runs your dev command unrecorded rather than failing, so this is safe to leave in a `dev` script.
|
|
40
|
+
|
|
39
41
|
Or run the sidecar standalone with `npx @alwaysmeticulous/cli record backend` and point the shim at it yourself — the value must be a worker var/binding (host environment variables are not visible inside workerd), e.g. in `.dev.vars`:
|
|
40
42
|
|
|
41
43
|
```
|
|
@@ -51,12 +53,26 @@ Without `METICULOUS_SIDECAR_URL` (or `options.sidecarUrl`) the wrapper is a comp
|
|
|
51
53
|
- **Inbound requests** (method, URL, headers, status; no bodies), correlated to the frontend session via the `x-meticulous-session-id` header stamped by the Meticulous frontend recorder.
|
|
52
54
|
- **Outgoing `fetch` calls** made while handling an inbound request: method, URL, headers, status, and request/response bodies (UTF-8, capped at 256 KB; long-lived streams such as SSE are captured truncated).
|
|
53
55
|
- **Calls through `fetch`-shaped bindings** — service bindings and Durable Object stubs — recorded like outgoing fetches, plus the `env` key the call went through. No code change is needed: the binding's `fetch` is instrumented wherever the app reads it from, including via `cloudflare:workers` rather than the handler's `env` argument.
|
|
56
|
+
- **KV namespace operations** — `get`, `getWithMetadata`, `put`, `delete` and `list` on a namespace found on `env`, recorded with the binding name, the key, the call's arguments and the value as JSON (so one `JSON.parse` reconstructs exactly what the app saw, whichever `type` the read asked for). Also no code change needed. A value read as a stream is never read by the recorder — that would take the bytes from the app — and binary values are skipped; both cases are recorded with the reason instead of the value.
|
|
57
|
+
|
|
58
|
+
Request bodies have secret-looking JSON fields (`clientSecret`, `apiKey`, `token`, `password`, …) replaced with `REDACTED` before they leave the worker, since plenty of APIs carry a credential in the body rather than a header. Response bodies are stored verbatim. A KV `put` value is redacted the same way, for the same reason; a value read back from KV is stored verbatim, like a response body.
|
|
59
|
+
|
|
60
|
+
## Replay
|
|
61
|
+
|
|
62
|
+
The same wrapper serves the recording back when Meticulous replays a session against your app: outgoing `fetch` calls are answered from the recording instead of reaching the real service, the clock is frozen at the recorded session's end, and `Math.random` / `crypto.randomUUID` / `crypto.getRandomValues` are seeded so ids the app mints are identical in every replay. Replay is activated by a header the Meticulous replay runner injects, so nothing extra is needed to enable it.
|
|
63
|
+
|
|
64
|
+
Replay is **hermetic**: a call the recording does not cover fails with a `[backend-recorder] workerd replay: …` error rather than quietly reaching the real service, so a gap in the recording surfaces instead of turning a replay into live traffic. For a call that must stay live during a replay, set the `meticulous-passthrough` header to `true` on the request:
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
await fetch(url, { headers: { "meticulous-passthrough": "true" } });
|
|
68
|
+
```
|
|
54
69
|
|
|
55
|
-
|
|
70
|
+
Calls through bindings and KV namespaces are not served from the recording (see Limitations) and are never failed — they always reach the real binding.
|
|
56
71
|
|
|
57
72
|
## Limitations
|
|
58
73
|
|
|
59
|
-
- Bindings other than `fetch`-shaped ones are not captured:
|
|
74
|
+
- Bindings other than `fetch`-shaped ones and KV namespaces are not captured: D1, R2, Queues, and RPC method calls on a named entrypoint (`env.SVC.someMethod()`) — an RPC method is not a patchable property, so it cannot be intercepted this way.
|
|
75
|
+
- A KV value that is not text is recorded without its value: reading a `stream` would take the bytes away from the app, and binary values are skipped because KV blobs are large and not UTF-8. The operation, key and arguments are still recorded, with `omitted` saying which case it was.
|
|
60
76
|
- Assets bindings are skipped by default (`ASSETS`, `__STATIC_CONTENT`): asset bytes are large and often binary, and asset serving is usually a worker's highest-volume call. Use `options.skipBindings` to skip others.
|
|
61
77
|
- A Durable Object stub is recorded without a binding name, since the stub comes from `namespace.get()` rather than being a binding itself.
|
|
62
78
|
- A binding reference bound before the first instrumented request (`const f = env.SVC.fetch.bind(env.SVC)` at module scope) escapes instrumentation. Holding the binding _object_ and calling `.fetch()` on it per request — what SDKs normally do — is captured.
|
package/dist/fetch-patch.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e73e6f17-4a76-5ec4-a107-3aa991c55b22")}catch(e){}}();
|
|
3
3
|
import { requestCaptureContext } from "./context.js";
|
|
4
4
|
import { getOriginalFetch, setOriginalFetch } from "./original-fetch.js";
|
|
5
5
|
import { captureOutboundCall } from "./outbound-capture.js";
|
|
@@ -13,7 +13,8 @@ const FETCH_PATCHED = Symbol.for("meticulous.workerd.fetchPatched");
|
|
|
13
13
|
* never in the request path); request and response are cloned and reported in the
|
|
14
14
|
* background.
|
|
15
15
|
* - replaying: decide-then-serve. The call is looked up against the sidecar's mock store
|
|
16
|
-
* and a recorded response is synthesised, or the
|
|
16
|
+
* and a recorded response is synthesised, or the call fails — replay is hermetic unless
|
|
17
|
+
* the request opts out with the `meticulous-passthrough` header.
|
|
17
18
|
*
|
|
18
19
|
* Outside a withMeticulous request context the patch is a pure pass-through. Idempotent.
|
|
19
20
|
*/
|
|
@@ -41,4 +42,4 @@ const patchedFetch = async (input, init) => {
|
|
|
41
42
|
export { installFetchPatch };
|
|
42
43
|
|
|
43
44
|
//# sourceMappingURL=fetch-patch.js.map
|
|
44
|
-
//# debugId=
|
|
45
|
+
//# debugId=e73e6f17-4a76-5ec4-a107-3aa991c55b22
|
package/dist/fetch-patch.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-patch.js","sources":["../src/fetch-patch.ts"],"sourcesContent":["import { requestCaptureContext } from \"./context\";\nimport { getOriginalFetch, setOriginalFetch } from \"./original-fetch\";\nimport { captureOutboundCall } from \"./outbound-capture\";\nimport { replayOutboundCall } from \"./replay-fetch\";\n\ntype FetchFn = typeof globalThis.fetch;\n\n// Symbol.for so a second copy of the shim (e.g. bundled twice) still detects the patch.\nconst FETCH_PATCHED = Symbol.for(\"meticulous.workerd.fetchPatched\");\n\nexport { getOriginalFetch } from \"./original-fetch\";\nexport { headersToRecord } from \"./outbound-capture\";\n\n/**\n * Replaces globalThis.fetch with the mode-appropriate interception:\n *\n * - recording: a passive capture tee. The real fetch is called directly (the sidecar is\n * never in the request path); request and response are cloned and reported in the\n * background.\n * - replaying: decide-then-serve. The call is looked up against the sidecar's mock store\n * and a recorded response is synthesised, or the
|
|
1
|
+
{"version":3,"file":"fetch-patch.js","sources":["../src/fetch-patch.ts"],"sourcesContent":["import { requestCaptureContext } from \"./context\";\nimport { getOriginalFetch, setOriginalFetch } from \"./original-fetch\";\nimport { captureOutboundCall } from \"./outbound-capture\";\nimport { replayOutboundCall } from \"./replay-fetch\";\n\ntype FetchFn = typeof globalThis.fetch;\n\n// Symbol.for so a second copy of the shim (e.g. bundled twice) still detects the patch.\nconst FETCH_PATCHED = Symbol.for(\"meticulous.workerd.fetchPatched\");\n\nexport { getOriginalFetch } from \"./original-fetch\";\nexport { headersToRecord } from \"./outbound-capture\";\n\n/**\n * Replaces globalThis.fetch with the mode-appropriate interception:\n *\n * - recording: a passive capture tee. The real fetch is called directly (the sidecar is\n * never in the request path); request and response are cloned and reported in the\n * background.\n * - replaying: decide-then-serve. The call is looked up against the sidecar's mock store\n * and a recorded response is synthesised, or the call fails — replay is hermetic unless\n * the request opts out with the `meticulous-passthrough` header.\n *\n * Outside a withMeticulous request context the patch is a pure pass-through. Idempotent.\n */\nexport const installFetchPatch = (): void => {\n const holder = globalThis as { [FETCH_PATCHED]?: boolean };\n if (holder[FETCH_PATCHED]) {\n return;\n }\n holder[FETCH_PATCHED] = true;\n setOriginalFetch(globalThis.fetch.bind(globalThis));\n globalThis.fetch = patchedFetch;\n};\n\nconst patchedFetch: FetchFn = async (input, init) => {\n const original = getOriginalFetch();\n const ctx = requestCaptureContext.getStore();\n if (!ctx) {\n return original(input, init);\n }\n\n // Normalize to a single Request. This may consume `input`'s body (when\n // `input` is a Request), so from here on the real fetch must be given\n // `request`, never the original arguments.\n let request: Request;\n try {\n request = new Request(input, init);\n } catch {\n // Unconstructable arguments — let the real fetch produce the error.\n return original(input, init);\n }\n\n // Never intercept the shim's own traffic to the sidecar. Defence in depth: every\n // shim → sidecar call already goes through the unpatched fetch.\n if (request.url.startsWith(`${ctx.sidecarUrl}/`)) {\n return original(request);\n }\n\n return ctx.mode === \"replay\"\n ? replayOutboundCall(ctx, request, (req) => original(req))\n : captureOutboundCall(ctx, { kind: \"outbound\" }, request, (req) =>\n original(req),\n );\n};\n"],"names":[],"mappings":";;;;;;;AAQA,MAAM,gBAAgB,OAAO,IAAI,kCAAkC;;;;;;;;;;;;;AAiBnE,MAAa,0BAAgC;CAC3C,MAAM,SAAS;AACf,KAAI,OAAO,eACT;AAEF,QAAO,iBAAiB;AACxB,kBAAiB,WAAW,MAAM,KAAK,WAAW,CAAC;AACnD,YAAW,QAAQ;;AAGrB,MAAM,eAAwB,OAAO,OAAO,SAAS;CACnD,MAAM,WAAW,kBAAkB;CACnC,MAAM,MAAM,sBAAsB,UAAU;AAC5C,KAAI,CAAC,IACH,QAAO,SAAS,OAAO,KAAK;CAM9B,IAAI;AACJ,KAAI;AACF,YAAU,IAAI,QAAQ,OAAO,KAAK;SAC5B;AAEN,SAAO,SAAS,OAAO,KAAK;;AAK9B,KAAI,QAAQ,IAAI,WAAW,GAAG,IAAI,WAAW,GAAG,CAC9C,QAAO,SAAS,QAAQ;AAG1B,QAAO,IAAI,SAAS,WAChB,mBAAmB,KAAK,UAAU,QAAQ,SAAS,IAAI,CAAC,GACxD,oBAAoB,KAAK,EAAE,MAAM,YAAY,EAAE,UAAU,QACvD,SAAS,IAAI,CACd","debugId":"e73e6f17-4a76-5ec4-a107-3aa991c55b22"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BindingRequestEvent, CAPTURED_HEADERS, CaptureEvent, CaptureEventsPayload, CapturedBody, FRONTEND_SESSION_ID_HEADER, InboundRequestEvent, OutboundFetchLookupRequest, OutboundFetchLookupResponse, OutboundRequestEvent, REPLAY_SIDECAR_URL_HEADER, ReplaySessionInfoResponse, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH } from "./protocol.js";
|
|
1
|
+
import { BindingRequestEvent, CAPTURED_HEADERS, CaptureEvent, CaptureEventsPayload, CapturedBody, FRONTEND_SESSION_ID_HEADER, InboundRequestEvent, KvOmittedReason, KvOperation, KvOperationEvent, METICULOUS_PASSTHROUGH_HEADER, OutboundFetchLookupRequest, OutboundFetchLookupResponse, OutboundRequestEvent, REPLAY_SIDECAR_URL_HEADER, ReplaySessionInfoResponse, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH } from "./protocol.js";
|
|
2
2
|
import { MAX_BODY_CAPTURE_SIZE, readBodyWithCap, readRequestBodyWithCap } from "./body-capture.js";
|
|
3
3
|
import { headersToRecord } from "./outbound-capture.js";
|
|
4
4
|
import { STR_REDACTED, redactRequestBody } from "./redact-body.js";
|
|
@@ -18,6 +18,7 @@ interface WithMeticulousOptions {
|
|
|
18
18
|
/**
|
|
19
19
|
* Binding names to leave unrecorded, on top of the defaults (`ASSETS`,
|
|
20
20
|
* `__STATIC_CONTENT`). Use this for a binding whose traffic is high-volume or binary.
|
|
21
|
+
* Applies to KV namespaces as well as `fetch`-shaped bindings.
|
|
21
22
|
*/
|
|
22
23
|
skipBindings?: readonly string[];
|
|
23
24
|
}
|
|
@@ -30,13 +31,18 @@ interface WithMeticulousOptions {
|
|
|
30
31
|
* });
|
|
31
32
|
*
|
|
32
33
|
* **Recording** activates on a `METICULOUS_SIDECAR_URL` var/binding (e.g. via `.dev.vars`
|
|
33
|
-
* or `wrangler dev --var`) or `options.sidecarUrl`. Inbound requests
|
|
34
|
-
* calls
|
|
34
|
+
* or `wrangler dev --var`) or `options.sidecarUrl`. Inbound requests, outgoing `fetch`
|
|
35
|
+
* calls, calls through `fetch`-shaped bindings and KV namespace operations are reported to
|
|
36
|
+
* the sidecar as capture events, without affecting the app.
|
|
35
37
|
*
|
|
36
38
|
* **Replay** activates on the `x-meticulous-backend-replay-sidecar-url` header, injected by
|
|
37
39
|
* the Meticulous replay runner on requests to the app under test. Outgoing `fetch` calls are
|
|
38
|
-
* then served from the recording instead of reaching the real service
|
|
39
|
-
*
|
|
40
|
+
* then served from the recording instead of reaching the real service — and a call the
|
|
41
|
+
* recording does not cover fails, rather than quietly becoming live traffic; put a
|
|
42
|
+
* `meticulous-passthrough: true` header on a request that must stay real. The clock is frozen
|
|
43
|
+
* at the recorded session's end so recorded credentials are still valid, and `Math.random` /
|
|
44
|
+
* `crypto.randomUUID` / `crypto.getRandomValues` are seeded so ids the app mints are the same
|
|
45
|
+
* in every replay of that session. Workerd
|
|
40
46
|
* cannot read container environment variables, which is why per-replay config arrives as a
|
|
41
47
|
* request header; the shim validates it and only honours a loopback / docker-gateway /
|
|
42
48
|
* private-network `http:` origin.
|
|
@@ -52,5 +58,5 @@ interface WithMeticulousOptions {
|
|
|
52
58
|
*/
|
|
53
59
|
declare const withMeticulous: <H extends MeticulousWorkerHandler<never>>(handler: H, options?: WithMeticulousOptions) => H;
|
|
54
60
|
//#endregion
|
|
55
|
-
export { type BindingRequestEvent, CAPTURED_HEADERS, type CaptureEvent, type CaptureEventsPayload, type CapturedBody, FRONTEND_SESSION_ID_HEADER, type InboundRequestEvent, MAX_BODY_CAPTURE_SIZE, MeticulousExecutionContext, MeticulousWorkerHandler, type OutboundFetchLookupRequest, type OutboundFetchLookupResponse, type OutboundRequestEvent, REPLAY_SIDECAR_URL_HEADER, type ReplaySessionInfoResponse, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH, STR_REDACTED, WithMeticulousOptions, headersToRecord, readBodyWithCap, readRequestBodyWithCap, redactRequestBody, withMeticulous };
|
|
61
|
+
export { type BindingRequestEvent, CAPTURED_HEADERS, type CaptureEvent, type CaptureEventsPayload, type CapturedBody, FRONTEND_SESSION_ID_HEADER, type InboundRequestEvent, type KvOmittedReason, type KvOperation, type KvOperationEvent, MAX_BODY_CAPTURE_SIZE, METICULOUS_PASSTHROUGH_HEADER, MeticulousExecutionContext, MeticulousWorkerHandler, type OutboundFetchLookupRequest, type OutboundFetchLookupResponse, type OutboundRequestEvent, REPLAY_SIDECAR_URL_HEADER, type ReplaySessionInfoResponse, SIDECAR_EVENTS_PATH, SIDECAR_PROTOCOL_VERSION, SIDECAR_PROTOCOL_VERSION_HEADER, SIDECAR_REPLAY_OUTBOUND_FETCH_PATH, SIDECAR_REPLAY_SESSION_PATH, STR_REDACTED, WithMeticulousOptions, headersToRecord, readBodyWithCap, readRequestBodyWithCap, redactRequestBody, withMeticulous };
|
|
56
62
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
Binary file
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { installBindingPatch } from \"./binding-patch\";\nimport {\n type RequestCaptureContext,\n type RequestReplayContext,\n requestCaptureContext,\n} from \"./context\";\nimport { installFetchPatch } from \"./fetch-patch\";\nimport { warnOnce } from \"./log\";\nimport { getOriginalFetch } from \"./original-fetch\";\nimport { headersToRecord } from \"./outbound-capture\";\nimport {\n FRONTEND_SESSION_ID_HEADER,\n type InboundRequestEvent,\n REPLAY_SIDECAR_URL_HEADER,\n} from \"./protocol\";\nimport { parseReplaySidecarUrl } from \"./replay-sidecar-url\";\nimport { getReplaySessionInfo, postCaptureEvents } from \"./sidecar-client\";\nimport { installVirtualClock } from \"./virtual-clock\";\n\nexport type {\n BindingRequestEvent,\n CaptureEvent,\n CapturedBody,\n CaptureEventsPayload,\n InboundRequestEvent,\n OutboundFetchLookupRequest,\n OutboundFetchLookupResponse,\n OutboundRequestEvent,\n ReplaySessionInfoResponse,\n} from \"./protocol\";\nexport {\n CAPTURED_HEADERS,\n FRONTEND_SESSION_ID_HEADER,\n REPLAY_SIDECAR_URL_HEADER,\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\";\nexport {\n MAX_BODY_CAPTURE_SIZE,\n readBodyWithCap,\n readRequestBodyWithCap,\n} from \"./body-capture\";\nexport { headersToRecord } from \"./outbound-capture\";\nexport { redactRequestBody, STR_REDACTED } from \"./redact-body\";\n\n/** Structural subset of workerd's ExecutionContext — avoids a @cloudflare/workers-types dependency. */\nexport interface MeticulousExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n}\n\n/** Structural subset of an ES-module Worker handler (`export default {...}`). */\nexport interface MeticulousWorkerHandler<Env = never> {\n fetch(\n request: Request,\n env: Env,\n ctx: MeticulousExecutionContext,\n ): Response | Promise<Response>;\n}\n\nexport interface WithMeticulousOptions {\n /** Overrides the sidecar origin; defaults to the METICULOUS_SIDECAR_URL var/binding. */\n sidecarUrl?: string;\n /**\n * Binding names to leave unrecorded, on top of the defaults (`ASSETS`,\n * `__STATIC_CONTENT`). Use this for a binding whose traffic is high-volume or binary.\n */\n skipBindings?: readonly string[];\n}\n\n/**\n * Wraps an ES-module Worker handler so Meticulous can record, or replay, the app's HTTP\n * behaviour:\n *\n * export default withMeticulous({\n * async fetch(request, env, ctx) { ... },\n * });\n *\n * **Recording** activates on a `METICULOUS_SIDECAR_URL` var/binding (e.g. via `.dev.vars`\n * or `wrangler dev --var`) or `options.sidecarUrl`. Inbound requests and outgoing `fetch`\n * calls are reported to the sidecar as capture events, without affecting the app.\n *\n * **Replay** activates on the `x-meticulous-backend-replay-sidecar-url` header, injected by\n * the Meticulous replay runner on requests to the app under test. Outgoing `fetch` calls are\n * then served from the recording instead of reaching the real service, and the clock is\n * frozen at the recorded session's end so recorded credentials are still valid. Workerd\n * cannot read container environment variables, which is why per-replay config arrives as a\n * request header; the shim validates it and only honours a loopback / docker-gateway /\n * private-network `http:` origin.\n *\n * Replay takes precedence over recording when both are configured. A stale\n * `METICULOUS_SIDECAR_URL` baked into an image's `.dev.vars` is far more likely than a\n * spurious replay header (nothing but the replay runner emits it), and letting the env win\n * would silently record a replay instead of mocking it.\n *\n * With neither configured the wrapper is a complete pass-through, so it is safe to keep in\n * deployed code. Requires the `nodejs_als` (or `nodejs_compat`) compatibility flag. A\n * capture failure or unreachable sidecar never affects the app.\n */\nexport const withMeticulous = <H extends MeticulousWorkerHandler<never>>(\n handler: H,\n options?: WithMeticulousOptions,\n): H => {\n const wrappedFetch = async (\n request: Request,\n env: unknown,\n ctx: MeticulousExecutionContext,\n ): Promise<Response> => {\n const invokeHandler = () => handler.fetch(request, env as never, ctx);\n\n let sidecarUrl: string | undefined;\n let replayContext: RequestReplayContext | undefined;\n try {\n replayContext = await resolveReplayContext(request, ctx);\n sidecarUrl =\n replayContext === undefined\n ? resolveSidecarUrl(options, env)\n : undefined;\n if (replayContext !== undefined || sidecarUrl !== undefined) {\n installFetchPatch();\n }\n if (sidecarUrl !== undefined) {\n // Lazily, inside the request path, and never at module scope: the package declares\n // no `sideEffects` and is built with `platform: \"neutral\"`, so a module-scope side\n // effect can legitimately be tree-shaken by a customer's bundler. Re-run per\n // request because `env` is the only handle on the binding instances.\n //\n // Record mode only. Binding calls are recorded as their own technology\n // (`workerd-binding`) and the replay sidecar's store holds only `workerd-fetch`\n // spans, so there is nothing to serve them from — and patching would only route\n // them into the capture tee, which POSTs to an events route a replay sidecar 404s.\n installBindingPatch(env, { skipBindings: options?.skipBindings });\n }\n } catch (error) {\n warnOnce(\n \"shim-init\",\n \"Failed to initialize the Meticulous backend recorder shim — recording disabled.\",\n error,\n );\n replayContext = undefined;\n sidecarUrl = undefined;\n }\n\n if (replayContext !== undefined) {\n // Install the clock before any app code runs, so a module that reads Date.now() at\n // call time (the firebase auth libraries do) sees the session's frozen instant.\n installVirtualClock();\n // No inbound reporting in replay mode: there is no exporter behind the replay\n // sidecar, and the events route 404s there.\n return requestCaptureContext.run(replayContext, invokeHandler);\n }\n\n if (sidecarUrl === undefined) {\n return invokeHandler();\n }\n\n const captureCtx = buildCaptureContext(request, sidecarUrl, ctx);\n const startTimeMs = Date.now();\n let requestHeaders: Record<string, string[]> = {};\n let method = \"GET\";\n let url = \"\";\n try {\n requestHeaders = headersToRecord(request.headers);\n method = request.method;\n url = request.url;\n } catch (error) {\n warnOnce(\n \"inbound-capture\",\n \"Failed to capture the inbound request.\",\n error,\n );\n }\n\n const reportInbound = (\n outcome:\n | { statusCode: number; responseHeaders: Record<string, string[]> }\n | { error: string },\n ): void => {\n try {\n const event: InboundRequestEvent = {\n kind: \"inbound\",\n requestId: captureCtx.requestId,\n ...(captureCtx.frontendSessionId !== undefined\n ? { frontendSessionId: captureCtx.frontendSessionId }\n : {}),\n method,\n url,\n requestHeaders,\n startTimeMs,\n endTimeMs: Date.now(),\n ...outcome,\n };\n captureCtx.waitUntil(\n postCaptureEvents(getOriginalFetch(), sidecarUrl, [event]),\n );\n } catch (error) {\n warnOnce(\n \"inbound-report\",\n \"Failed to report the inbound request.\",\n error,\n );\n }\n };\n\n let response: Response;\n try {\n response = await requestCaptureContext.run(captureCtx, invokeHandler);\n } catch (error) {\n reportInbound({ error: String(error) });\n throw error;\n }\n\n try {\n reportInbound({\n statusCode: response.status,\n responseHeaders: headersToRecord(response.headers),\n });\n } catch (error) {\n warnOnce(\n \"inbound-report\",\n \"Failed to report the inbound request.\",\n error,\n );\n }\n return response;\n };\n\n // The wrapper only replaces `fetch` (same call signature), but TypeScript\n // cannot verify a spread against the bare generic H.\n return { ...handler, fetch: wrappedFetch } as H;\n};\n\n/**\n * Whether this request should be replayed, and the context to serve it under.\n *\n * Both the session id and a usable sidecar URL must be present: mocks are indexed per\n * session, so replay without a session id could only miss. The sidecar is consulted once\n * per (sidecar, session) per isolate to confirm it holds mocks and to learn the clock\n * anchor — a sidecar that does not recognise the session, or the route, means replay is\n * unavailable and the request runs normally.\n */\nconst resolveReplayContext = async (\n request: Request,\n ctx: MeticulousExecutionContext,\n): Promise<RequestReplayContext | undefined> => {\n let sidecarUrl: string | undefined;\n let frontendSessionId: string | undefined;\n try {\n sidecarUrl = parseReplaySidecarUrl(\n request.headers.get(REPLAY_SIDECAR_URL_HEADER),\n );\n frontendSessionId =\n request.headers.get(FRONTEND_SESSION_ID_HEADER) ?? undefined;\n } catch {\n return undefined;\n }\n if (sidecarUrl === undefined || frontendSessionId === undefined) {\n return undefined;\n }\n\n const info = await getCachedReplaySessionInfo(sidecarUrl, frontendSessionId);\n if (info === null) {\n return undefined;\n }\n\n return {\n mode: \"replay\",\n requestId: crypto.randomUUID(),\n frontendSessionId,\n sidecarUrl,\n clockAnchorMs: info.clockAnchorMs,\n waitUntil: buildWaitUntil(ctx),\n };\n};\n\n// Caches the promise, not the result, so concurrent first requests share one round trip.\n// Bounded so a stream of unrecognised session ids cannot grow it without limit.\nconst MAX_CACHED_SESSIONS = 50;\nconst replaySessionInfoCache = new Map<\n string,\n Promise<{ clockAnchorMs: number | undefined } | null>\n>();\n\nconst getCachedReplaySessionInfo = (\n sidecarUrl: string,\n frontendSessionId: string,\n): Promise<{ clockAnchorMs: number | undefined } | null> => {\n const key = `${sidecarUrl}\u0000${frontendSessionId}`;\n const cached = replaySessionInfoCache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const pending = getReplaySessionInfo(\n getOriginalFetch(),\n sidecarUrl,\n frontendSessionId,\n ).then((result) => {\n if (result.outcome === \"unreachable\") {\n // Only settled answers are worth keeping. Caching a timeout or transport blip would\n // disable mocking for this session for the life of the isolate, quietly sending every\n // later outbound call to the real service — the failure this path exists to prevent.\n // Dropping the entry costs one extra handshake and lets the next request recover.\n replaySessionInfoCache.delete(key);\n return null;\n }\n return result.outcome === \"found\"\n ? { clockAnchorMs: result.clockAnchorMs }\n : null;\n });\n if (replaySessionInfoCache.size >= MAX_CACHED_SESSIONS) {\n const oldest = replaySessionInfoCache.keys().next();\n if (!oldest.done) {\n replaySessionInfoCache.delete(oldest.value);\n }\n }\n replaySessionInfoCache.set(key, pending);\n return pending;\n};\n\nconst resolveSidecarUrl = (\n options: WithMeticulousOptions | undefined,\n env: unknown,\n): string | undefined => {\n const fromEnv =\n env !== null && typeof env === \"object\"\n ? (env as Record<string, unknown>)[\"METICULOUS_SIDECAR_URL\"]\n : undefined;\n const raw = options?.sidecarUrl ?? fromEnv;\n if (typeof raw !== \"string\" || raw.length === 0) {\n return undefined;\n }\n return raw.replace(/\\/+$/, \"\");\n};\n\nconst buildCaptureContext = (\n request: Request,\n sidecarUrl: string,\n ctx: MeticulousExecutionContext,\n): RequestCaptureContext => {\n let frontendSessionId: string | undefined;\n try {\n frontendSessionId =\n request.headers.get(FRONTEND_SESSION_ID_HEADER) ?? undefined;\n } catch {\n frontendSessionId = undefined;\n }\n return {\n mode: \"record\",\n requestId: crypto.randomUUID(),\n frontendSessionId,\n sidecarUrl,\n waitUntil: buildWaitUntil(ctx),\n };\n};\n\nconst buildWaitUntil =\n (ctx: MeticulousExecutionContext) =>\n (promise: Promise<unknown>): void => {\n try {\n ctx.waitUntil(promise);\n } catch (error) {\n warnOnce(\n \"wait-until\",\n \"ctx.waitUntil failed — capture events may be lost.\",\n error,\n );\n }\n };\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,MAAa,kBACX,SACA,YACM;CACN,MAAM,eAAe,OACnB,SACA,KACA,QACsB;EACtB,MAAM,sBAAsB,QAAQ,MAAM,SAAS,KAAc,IAAI;EAErE,IAAI;EACJ,IAAI;AACJ,MAAI;AACF,mBAAgB,MAAM,qBAAqB,SAAS,IAAI;AACxD,gBACE,kBAAkB,KAAA,IACd,kBAAkB,SAAS,IAAI,GAC/B,KAAA;AACN,OAAI,kBAAkB,KAAA,KAAa,eAAe,KAAA,EAChD,oBAAmB;AAErB,OAAI,eAAe,KAAA,EAUjB,qBAAoB,KAAK,EAAE,cAAc,SAAS,cAAc,CAAC;WAE5D,OAAO;AACd,YACE,aACA,mFACA,MACD;AACD,mBAAgB,KAAA;AAChB,gBAAa,KAAA;;AAGf,MAAI,kBAAkB,KAAA,GAAW;AAG/B,wBAAqB;AAGrB,UAAO,sBAAsB,IAAI,eAAe,cAAc;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A,YAAoC;AACnC,KAAI;AACF,MAAI,UAAU,QAAQ;UACf,OAAO;AACd,WACE,cACA,sDACA,MACD","debugId":"8791d2a2-34c5-5ddf-81a1-7f74833160ef"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { installBindingPatch } from \"./binding-patch\";\nimport {\n type RequestCaptureContext,\n type RequestReplayContext,\n requestCaptureContext,\n} from \"./context\";\nimport { installFetchPatch } from \"./fetch-patch\";\nimport { installKvPatch } from \"./kv-patch\";\nimport { warnOnce } from \"./log\";\nimport { getOriginalFetch } from \"./original-fetch\";\nimport { headersToRecord } from \"./outbound-capture\";\nimport {\n FRONTEND_SESSION_ID_HEADER,\n type InboundRequestEvent,\n REPLAY_SIDECAR_URL_HEADER,\n} from \"./protocol\";\nimport { parseReplaySidecarUrl } from \"./replay-sidecar-url\";\nimport { getReplaySessionInfo, postCaptureEvents } from \"./sidecar-client\";\nimport { installVirtualClock } from \"./virtual-clock\";\nimport { installVirtualRandom } from \"./virtual-random\";\n\nexport type {\n BindingRequestEvent,\n CaptureEvent,\n CapturedBody,\n CaptureEventsPayload,\n InboundRequestEvent,\n KvOmittedReason,\n KvOperation,\n KvOperationEvent,\n OutboundFetchLookupRequest,\n OutboundFetchLookupResponse,\n OutboundRequestEvent,\n ReplaySessionInfoResponse,\n} from \"./protocol\";\nexport {\n CAPTURED_HEADERS,\n FRONTEND_SESSION_ID_HEADER,\n METICULOUS_PASSTHROUGH_HEADER,\n REPLAY_SIDECAR_URL_HEADER,\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\";\nexport {\n MAX_BODY_CAPTURE_SIZE,\n readBodyWithCap,\n readRequestBodyWithCap,\n} from \"./body-capture\";\nexport { headersToRecord } from \"./outbound-capture\";\nexport { redactRequestBody, STR_REDACTED } from \"./redact-body\";\n\n/** Structural subset of workerd's ExecutionContext — avoids a @cloudflare/workers-types dependency. */\nexport interface MeticulousExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n}\n\n/** Structural subset of an ES-module Worker handler (`export default {...}`). */\nexport interface MeticulousWorkerHandler<Env = never> {\n fetch(\n request: Request,\n env: Env,\n ctx: MeticulousExecutionContext,\n ): Response | Promise<Response>;\n}\n\nexport interface WithMeticulousOptions {\n /** Overrides the sidecar origin; defaults to the METICULOUS_SIDECAR_URL var/binding. */\n sidecarUrl?: string;\n /**\n * Binding names to leave unrecorded, on top of the defaults (`ASSETS`,\n * `__STATIC_CONTENT`). Use this for a binding whose traffic is high-volume or binary.\n * Applies to KV namespaces as well as `fetch`-shaped bindings.\n */\n skipBindings?: readonly string[];\n}\n\n/**\n * Wraps an ES-module Worker handler so Meticulous can record, or replay, the app's HTTP\n * behaviour:\n *\n * export default withMeticulous({\n * async fetch(request, env, ctx) { ... },\n * });\n *\n * **Recording** activates on a `METICULOUS_SIDECAR_URL` var/binding (e.g. via `.dev.vars`\n * or `wrangler dev --var`) or `options.sidecarUrl`. Inbound requests, outgoing `fetch`\n * calls, calls through `fetch`-shaped bindings and KV namespace operations are reported to\n * the sidecar as capture events, without affecting the app.\n *\n * **Replay** activates on the `x-meticulous-backend-replay-sidecar-url` header, injected by\n * the Meticulous replay runner on requests to the app under test. Outgoing `fetch` calls are\n * then served from the recording instead of reaching the real service — and a call the\n * recording does not cover fails, rather than quietly becoming live traffic; put a\n * `meticulous-passthrough: true` header on a request that must stay real. The clock is frozen\n * at the recorded session's end so recorded credentials are still valid, and `Math.random` /\n * `crypto.randomUUID` / `crypto.getRandomValues` are seeded so ids the app mints are the same\n * in every replay of that session. Workerd\n * cannot read container environment variables, which is why per-replay config arrives as a\n * request header; the shim validates it and only honours a loopback / docker-gateway /\n * private-network `http:` origin.\n *\n * Replay takes precedence over recording when both are configured. A stale\n * `METICULOUS_SIDECAR_URL` baked into an image's `.dev.vars` is far more likely than a\n * spurious replay header (nothing but the replay runner emits it), and letting the env win\n * would silently record a replay instead of mocking it.\n *\n * With neither configured the wrapper is a complete pass-through, so it is safe to keep in\n * deployed code. Requires the `nodejs_als` (or `nodejs_compat`) compatibility flag. A\n * capture failure or unreachable sidecar never affects the app.\n */\nexport const withMeticulous = <H extends MeticulousWorkerHandler<never>>(\n handler: H,\n options?: WithMeticulousOptions,\n): H => {\n const wrappedFetch = async (\n request: Request,\n env: unknown,\n ctx: MeticulousExecutionContext,\n ): Promise<Response> => {\n const invokeHandler = () => handler.fetch(request, env as never, ctx);\n\n let sidecarUrl: string | undefined;\n let replayContext: RequestReplayContext | undefined;\n try {\n replayContext = await resolveReplayContext(request, ctx);\n sidecarUrl =\n replayContext === undefined\n ? resolveSidecarUrl(options, env)\n : undefined;\n if (replayContext !== undefined || sidecarUrl !== undefined) {\n installFetchPatch();\n }\n if (sidecarUrl !== undefined) {\n // Lazily, inside the request path, and never at module scope: the package declares\n // no `sideEffects` and is built with `platform: \"neutral\"`, so a module-scope side\n // effect can legitimately be tree-shaken by a customer's bundler. Re-run per\n // request because `env` is the only handle on the binding instances.\n //\n // Record mode only. Binding and KV calls are recorded as their own technologies\n // (`workerd-binding`, `workerd-kv`) and the replay sidecar's store holds only\n // `workerd-fetch` spans, so there is nothing to serve them from — and patching would\n // only route them into the capture tee, which POSTs to an events route a replay\n // sidecar 404s.\n installBindingPatch(env, { skipBindings: options?.skipBindings });\n installKvPatch(env, { skipBindings: options?.skipBindings });\n }\n } catch (error) {\n warnOnce(\n \"shim-init\",\n \"Failed to initialize the Meticulous backend recorder shim — recording disabled.\",\n error,\n );\n replayContext = undefined;\n sidecarUrl = undefined;\n }\n\n if (replayContext !== undefined) {\n // Install the clock before any app code runs, so a module that reads Date.now() at\n // call time (the firebase auth libraries do) sees the session's frozen instant.\n installVirtualClock();\n // Likewise the random generators: an id the app mints during SSR (a guest id, a\n // request id) otherwise differs between a base and a head replay, and every rendered\n // page carrying it diffs forever.\n installVirtualRandom();\n // No inbound reporting in replay mode: there is no exporter behind the replay\n // sidecar, and the events route 404s there.\n return requestCaptureContext.run(replayContext, invokeHandler);\n }\n\n if (sidecarUrl === undefined) {\n return invokeHandler();\n }\n\n const captureCtx = buildCaptureContext(request, sidecarUrl, ctx);\n const startTimeMs = Date.now();\n let requestHeaders: Record<string, string[]> = {};\n let method = \"GET\";\n let url = \"\";\n try {\n requestHeaders = headersToRecord(request.headers);\n method = request.method;\n url = request.url;\n } catch (error) {\n warnOnce(\n \"inbound-capture\",\n \"Failed to capture the inbound request.\",\n error,\n );\n }\n\n const reportInbound = (\n outcome:\n | { statusCode: number; responseHeaders: Record<string, string[]> }\n | { error: string },\n ): void => {\n try {\n const event: InboundRequestEvent = {\n kind: \"inbound\",\n requestId: captureCtx.requestId,\n ...(captureCtx.frontendSessionId !== undefined\n ? { frontendSessionId: captureCtx.frontendSessionId }\n : {}),\n method,\n url,\n requestHeaders,\n startTimeMs,\n endTimeMs: Date.now(),\n ...outcome,\n };\n captureCtx.waitUntil(\n postCaptureEvents(getOriginalFetch(), sidecarUrl, [event]),\n );\n } catch (error) {\n warnOnce(\n \"inbound-report\",\n \"Failed to report the inbound request.\",\n error,\n );\n }\n };\n\n let response: Response;\n try {\n response = await requestCaptureContext.run(captureCtx, invokeHandler);\n } catch (error) {\n reportInbound({ error: String(error) });\n throw error;\n }\n\n try {\n reportInbound({\n statusCode: response.status,\n responseHeaders: headersToRecord(response.headers),\n });\n } catch (error) {\n warnOnce(\n \"inbound-report\",\n \"Failed to report the inbound request.\",\n error,\n );\n }\n return response;\n };\n\n // The wrapper only replaces `fetch` (same call signature), but TypeScript\n // cannot verify a spread against the bare generic H.\n return { ...handler, fetch: wrappedFetch } as H;\n};\n\n/**\n * Whether this request should be replayed, and the context to serve it under.\n *\n * Both the session id and a usable sidecar URL must be present: mocks are indexed per\n * session, so replay without a session id could only miss. The sidecar is consulted once\n * per (sidecar, session) per isolate to confirm it holds mocks and to learn the clock\n * anchor — a sidecar that does not recognise the session, or the route, means replay is\n * unavailable and the request runs normally.\n */\nconst resolveReplayContext = async (\n request: Request,\n ctx: MeticulousExecutionContext,\n): Promise<RequestReplayContext | undefined> => {\n let sidecarUrl: string | undefined;\n let frontendSessionId: string | undefined;\n try {\n sidecarUrl = parseReplaySidecarUrl(\n request.headers.get(REPLAY_SIDECAR_URL_HEADER),\n );\n frontendSessionId =\n request.headers.get(FRONTEND_SESSION_ID_HEADER) ?? undefined;\n } catch {\n return undefined;\n }\n if (sidecarUrl === undefined || frontendSessionId === undefined) {\n return undefined;\n }\n\n const info = await getCachedReplaySessionInfo(sidecarUrl, frontendSessionId);\n if (info === null) {\n return undefined;\n }\n\n return {\n mode: \"replay\",\n requestId: crypto.randomUUID(),\n frontendSessionId,\n sidecarUrl,\n clockAnchorMs: info.clockAnchorMs,\n waitUntil: buildWaitUntil(ctx),\n };\n};\n\n// Caches the promise, not the result, so concurrent first requests share one round trip.\n// Bounded so a stream of unrecognised session ids cannot grow it without limit.\nconst MAX_CACHED_SESSIONS = 50;\nconst replaySessionInfoCache = new Map<\n string,\n Promise<{ clockAnchorMs: number | undefined } | null>\n>();\n\nconst getCachedReplaySessionInfo = (\n sidecarUrl: string,\n frontendSessionId: string,\n): Promise<{ clockAnchorMs: number | undefined } | null> => {\n const key = `${sidecarUrl}\u0000${frontendSessionId}`;\n const cached = replaySessionInfoCache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const pending = getReplaySessionInfo(\n getOriginalFetch(),\n sidecarUrl,\n frontendSessionId,\n ).then((result) => {\n if (result.outcome === \"unreachable\") {\n // Only settled answers are worth keeping. Caching a timeout or transport blip would\n // disable mocking for this session for the life of the isolate, quietly sending every\n // later outbound call to the real service — the failure this path exists to prevent.\n // Dropping the entry costs one extra handshake and lets the next request recover.\n replaySessionInfoCache.delete(key);\n return null;\n }\n return result.outcome === \"found\"\n ? { clockAnchorMs: result.clockAnchorMs }\n : null;\n });\n if (replaySessionInfoCache.size >= MAX_CACHED_SESSIONS) {\n const oldest = replaySessionInfoCache.keys().next();\n if (!oldest.done) {\n replaySessionInfoCache.delete(oldest.value);\n }\n }\n replaySessionInfoCache.set(key, pending);\n return pending;\n};\n\nconst resolveSidecarUrl = (\n options: WithMeticulousOptions | undefined,\n env: unknown,\n): string | undefined => {\n const fromEnv =\n env !== null && typeof env === \"object\"\n ? (env as Record<string, unknown>)[\"METICULOUS_SIDECAR_URL\"]\n : undefined;\n const raw = options?.sidecarUrl ?? fromEnv;\n if (typeof raw !== \"string\" || raw.length === 0) {\n return undefined;\n }\n return raw.replace(/\\/+$/, \"\");\n};\n\nconst buildCaptureContext = (\n request: Request,\n sidecarUrl: string,\n ctx: MeticulousExecutionContext,\n): RequestCaptureContext => {\n let frontendSessionId: string | undefined;\n try {\n frontendSessionId =\n request.headers.get(FRONTEND_SESSION_ID_HEADER) ?? undefined;\n } catch {\n frontendSessionId = undefined;\n }\n return {\n mode: \"record\",\n requestId: crypto.randomUUID(),\n frontendSessionId,\n sidecarUrl,\n waitUntil: buildWaitUntil(ctx),\n };\n};\n\nconst buildWaitUntil =\n (ctx: MeticulousExecutionContext) =>\n (promise: Promise<unknown>): void => {\n try {\n ctx.waitUntil(promise);\n } catch (error) {\n warnOnce(\n \"wait-until\",\n \"ctx.waitUntil failed — capture events may be lost.\",\n error,\n );\n }\n };\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA,MAAa,kBACX,SACA,YACM;CACN,MAAM,eAAe,OACnB,SACA,KACA,QACsB;EACtB,MAAM,sBAAsB,QAAQ,MAAM,SAAS,KAAc,IAAI;EAErE,IAAI;EACJ,IAAI;AACJ,MAAI;AACF,mBAAgB,MAAM,qBAAqB,SAAS,IAAI;AACxD,gBACE,kBAAkB,KAAA,IACd,kBAAkB,SAAS,IAAI,GAC/B,KAAA;AACN,OAAI,kBAAkB,KAAA,KAAa,eAAe,KAAA,EAChD,oBAAmB;A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,IAAI,WAAW,EAC5C;AAEF,QAAO,IAAI,QAAQ,QAAQ,GAAG;;AAGhC,MAAM,uBACJ,SACA,YACA,QAC0B;CAC1B,IAAI;AACJ,KAAI;AACF,sBACE,QAAQ,QAAQ,IAAA,0BAA+B,IAAI,KAAA;SAC/C;AACN,sBAAoB,KAAA;;AAEtB,QAAO;EACL,MAAM;EACN,WAAW,OAAO,YAAY;EAC9B;EACA;EACA,WAAW,eAAe,IAAI;EAC/B;;AAGH,MAAM,kBACH,SACA,YAAoC;AACnC,KAAI;AACF,MAAI,UAAU,QAAQ;UACf,OAAO;AACd,WACE,cACA,sDACA,MACD","debugId":"00301fec-a17c-5e8e-8e2f-f16608d3b611"}
|
package/dist/kv-patch.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
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]="93bf09ea-4e78-5ac4-92cd-661f2ce03542")}catch(e){}}();
|
|
3
|
+
import { requestCaptureContext } from "./context.js";
|
|
4
|
+
import { warnOnce } from "./log.js";
|
|
5
|
+
import { redactRequestBody } from "./redact-body.js";
|
|
6
|
+
import { MAX_BODY_CAPTURE_SIZE } from "./body-capture.js";
|
|
7
|
+
import { getOriginalFetch } from "./original-fetch.js";
|
|
8
|
+
import { postCaptureEvents } from "./sidecar-client.js";
|
|
9
|
+
//#region src/kv-patch.ts
|
|
10
|
+
/**
|
|
11
|
+
* Records operations on Cloudflare KV namespace bindings (`env.MY_KV.get(key)`).
|
|
12
|
+
*
|
|
13
|
+
* KV is invisible to both the `globalThis.fetch` patch and the binding patch: a namespace is
|
|
14
|
+
* a host object with no `fetch`, and workerd services its methods internally rather than as
|
|
15
|
+
* a subrequest. So the namespace's *prototype* methods are patched instead — the same move
|
|
16
|
+
* `binding-patch.ts` makes on a Fetcher, and the Node recorder on `Redis.prototype.sendCommand`.
|
|
17
|
+
*
|
|
18
|
+
* The prototype is reached from an instance found on `env`: as with bindings there is no
|
|
19
|
+
* global to name, and going through an instance is what makes this work for an app that reads
|
|
20
|
+
* its bindings from `cloudflare:workers` rather than the handler argument — that module hands
|
|
21
|
+
* out a different `env` object but the same namespace instances, so the prototype is shared
|
|
22
|
+
* either way.
|
|
23
|
+
*
|
|
24
|
+
* Verified against real workerd in `packages/backend-recorder-js/src/__tests__/`:
|
|
25
|
+
* `workerd-binding-patch.spec.ts` pins the property shape this relies on (every recorded
|
|
26
|
+
* method inherited and configurable, one prototype across namespaces), and
|
|
27
|
+
* `workerd-kv-sidecar.spec.ts` drives real KV through the patch end to end.
|
|
28
|
+
*/
|
|
29
|
+
const KV_PATCHED = Symbol.for("meticulous.workerd.kvPatched");
|
|
30
|
+
/**
|
|
31
|
+
* The methods recorded, and the shape a KV namespace is recognised by.
|
|
32
|
+
*
|
|
33
|
+
* `getWithMetadata` is what separates KV from R2: an R2 bucket also has `get`, `put`,
|
|
34
|
+
* `delete` and `list`, so without it a bucket would be duck-typed as a namespace and its
|
|
35
|
+
* (large, binary) objects pushed through value capture.
|
|
36
|
+
*/
|
|
37
|
+
const RECORDED_KV_METHODS = [
|
|
38
|
+
"get",
|
|
39
|
+
"getWithMetadata",
|
|
40
|
+
"put",
|
|
41
|
+
"delete",
|
|
42
|
+
"list"
|
|
43
|
+
];
|
|
44
|
+
/**
|
|
45
|
+
* The namespaces being recorded, and the `env` key each was found under.
|
|
46
|
+
*
|
|
47
|
+
* Doubles as the allow-list: only an instance in here is recorded. A skipped namespace is
|
|
48
|
+
* simply never registered, and — since the patch can land on a prototype shared with another
|
|
49
|
+
* binding type — nothing that is not a discovered KV namespace can be recorded by accident.
|
|
50
|
+
*/
|
|
51
|
+
const kvBindingNames = /* @__PURE__ */ new WeakMap();
|
|
52
|
+
/**
|
|
53
|
+
* Discovers KV namespace bindings on `env` and patches their shared prototype so their
|
|
54
|
+
* operations are recorded. Safe to call on every request — discovery is cheap and the patch
|
|
55
|
+
* itself is applied once per prototype per isolate.
|
|
56
|
+
*
|
|
57
|
+
* Never throws: a runtime that does not permit the patch simply goes unrecorded.
|
|
58
|
+
*/
|
|
59
|
+
const installKvPatch = (env, options) => {
|
|
60
|
+
try {
|
|
61
|
+
for (const { name, value, skip } of kvBindings(env, options?.skipBindings)) {
|
|
62
|
+
patchKvMethods(value);
|
|
63
|
+
if (!skip) kvBindingNames.set(value, name);
|
|
64
|
+
}
|
|
65
|
+
} catch (error) {
|
|
66
|
+
warnOnce("kv-patch-install", "Failed to install the Meticulous KV patch — KV operations will not be recorded.", error);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const kvBindings = (env, skipBindings) => {
|
|
70
|
+
if (env === null || typeof env !== "object") return [];
|
|
71
|
+
const skipped = new Set(skipBindings ?? []);
|
|
72
|
+
const found = [];
|
|
73
|
+
for (const [name, value] of Object.entries(env)) if (isKvNamespaceLike(value)) found.push({
|
|
74
|
+
name,
|
|
75
|
+
value,
|
|
76
|
+
skip: skipped.has(name)
|
|
77
|
+
});
|
|
78
|
+
return found;
|
|
79
|
+
};
|
|
80
|
+
const isKvNamespaceLike = (value) => value !== null && typeof value === "object" && RECORDED_KV_METHODS.every((method) => typeof value[method] === "function");
|
|
81
|
+
/**
|
|
82
|
+
* Patches every recorded method, or none of them: a half-patched namespace would record a
|
|
83
|
+
* partial view of the app's KV usage, which is worse than recording none of it, because
|
|
84
|
+
* nothing in the recording would say which half is missing. So the whole chain is resolved
|
|
85
|
+
* first, and only then patched.
|
|
86
|
+
*
|
|
87
|
+
* Each method is patched where it actually lives rather than on the instance's immediate
|
|
88
|
+
* prototype — workerd already puts an inherited method further up the chain for Durable
|
|
89
|
+
* Object stubs, so assuming one flat prototype is not safe.
|
|
90
|
+
*/
|
|
91
|
+
const patchKvMethods = (binding) => {
|
|
92
|
+
const owners = /* @__PURE__ */ new Map();
|
|
93
|
+
for (const method of RECORDED_KV_METHODS) {
|
|
94
|
+
const owner = findMethodOwner(binding, method);
|
|
95
|
+
if (owner === void 0) {
|
|
96
|
+
warnOnce("kv-patch-unsupported", `This runtime does not expose a patchable KV \`${method}\` — KV operations will not be recorded.`);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
owners.set(method, owner);
|
|
100
|
+
}
|
|
101
|
+
for (const [method, { owner, original }] of owners) {
|
|
102
|
+
if (original[KV_PATCHED] === true) continue;
|
|
103
|
+
Object.defineProperty(owner, method, {
|
|
104
|
+
value: patchedKvMethod(method, original),
|
|
105
|
+
writable: true,
|
|
106
|
+
enumerable: false,
|
|
107
|
+
configurable: true
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* The prototype whose `method` a call on `instance` would reach, or undefined if there is none
|
|
113
|
+
* or it cannot be replaced. The search stops at the first prototype that *has* the property,
|
|
114
|
+
* patchable or not: that is the one a call resolves to, so anything further up is shadowed.
|
|
115
|
+
*/
|
|
116
|
+
const findMethodOwner = (instance, method) => {
|
|
117
|
+
if (Object.hasOwn(instance, method)) return;
|
|
118
|
+
let current = Object.getPrototypeOf(instance);
|
|
119
|
+
while (current !== null) {
|
|
120
|
+
const descriptor = Object.getOwnPropertyDescriptor(current, method);
|
|
121
|
+
if (descriptor !== void 0) return typeof descriptor.value === "function" && descriptor.configurable === true ? {
|
|
122
|
+
owner: current,
|
|
123
|
+
original: descriptor.value
|
|
124
|
+
} : void 0;
|
|
125
|
+
current = Object.getPrototypeOf(current);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* A `function`, not an arrow: `this` is the namespace the call was made on, and it must be
|
|
130
|
+
* forwarded to the original or workerd throws "Illegal invocation".
|
|
131
|
+
*/
|
|
132
|
+
const patchedKvMethod = (operation, original) => {
|
|
133
|
+
const patched = function(...args) {
|
|
134
|
+
const passThrough = () => original.apply(this, args);
|
|
135
|
+
const ctx = requestCaptureContext.getStore();
|
|
136
|
+
if (!ctx || ctx.mode !== "record") return passThrough();
|
|
137
|
+
const receiver = typeof this === "object" && this !== null ? this : void 0;
|
|
138
|
+
const bindingName = receiver === void 0 ? void 0 : kvBindingNames.get(receiver);
|
|
139
|
+
if (bindingName === void 0) return passThrough();
|
|
140
|
+
return captureKvOperation(ctx, operation, bindingName, args, passThrough);
|
|
141
|
+
};
|
|
142
|
+
Object.defineProperty(patched, KV_PATCHED, {
|
|
143
|
+
value: true,
|
|
144
|
+
enumerable: false,
|
|
145
|
+
configurable: true
|
|
146
|
+
});
|
|
147
|
+
return patched;
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Records an operation without affecting it: the real method runs untouched and its result is
|
|
151
|
+
* returned as-is, with the event reported in the background via `ctx.waitUntil`. Any capture
|
|
152
|
+
* failure is warned about once and swallowed — recording must never break the app.
|
|
153
|
+
*/
|
|
154
|
+
const captureKvOperation = async (ctx, operation, bindingName, args, invoke) => {
|
|
155
|
+
const startTimeMs = Date.now();
|
|
156
|
+
let result;
|
|
157
|
+
try {
|
|
158
|
+
result = await invoke();
|
|
159
|
+
} catch (error) {
|
|
160
|
+
report(ctx, operation, bindingName, args, startTimeMs, { error: String(error) });
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
report(ctx, operation, bindingName, args, startTimeMs, { result });
|
|
164
|
+
return result;
|
|
165
|
+
};
|
|
166
|
+
const report = (ctx, operation, bindingName, args, startTimeMs, outcome) => {
|
|
167
|
+
try {
|
|
168
|
+
const event = buildKvEvent(ctx, operation, bindingName, args, startTimeMs, outcome);
|
|
169
|
+
ctx.waitUntil(postCaptureEvents(getOriginalFetch(), ctx.sidecarUrl, [event]));
|
|
170
|
+
} catch (error) {
|
|
171
|
+
warnOnce("kv-report", "Failed to report a KV operation.", error);
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
const buildKvEvent = (ctx, operation, bindingName, args, startTimeMs, outcome) => {
|
|
175
|
+
const [key] = args;
|
|
176
|
+
const written = operation === "put" ? serializeWrittenValue(args[1]) : void 0;
|
|
177
|
+
const read = "result" in outcome ? serializeKvValue(outcome.result) : void 0;
|
|
178
|
+
const omitted = written?.omitted ?? read?.omitted;
|
|
179
|
+
const serializedArgs = serializeKvArgs(operation, args);
|
|
180
|
+
return {
|
|
181
|
+
kind: "kv",
|
|
182
|
+
requestId: ctx.requestId,
|
|
183
|
+
...ctx.frontendSessionId !== void 0 ? { frontendSessionId: ctx.frontendSessionId } : {},
|
|
184
|
+
bindingName,
|
|
185
|
+
operation,
|
|
186
|
+
...typeof key === "string" ? { key } : {},
|
|
187
|
+
...serializedArgs !== void 0 ? { args: serializedArgs } : {},
|
|
188
|
+
...written?.captured !== void 0 ? { value: written.captured } : {},
|
|
189
|
+
...read?.captured !== void 0 ? { result: read.captured } : {},
|
|
190
|
+
...omitted !== void 0 ? { omitted } : {},
|
|
191
|
+
startTimeMs,
|
|
192
|
+
endTimeMs: Date.now(),
|
|
193
|
+
..."error" in outcome ? { error: outcome.error } : {}
|
|
194
|
+
};
|
|
195
|
+
};
|
|
196
|
+
/**
|
|
197
|
+
* JSON of a value workerd returned, with anything unpersistable replaced by `null` and the
|
|
198
|
+
* reason reported alongside. A `Map` (what a bulk `get` returns) becomes a plain object,
|
|
199
|
+
* which `JSON.stringify` would otherwise flatten to `{}`.
|
|
200
|
+
*
|
|
201
|
+
* Read values are stored verbatim, deliberately: a future replay would serve them straight
|
|
202
|
+
* back to the app, so redacting one would corrupt what the app receives. Only the write path
|
|
203
|
+
* ({@link serializeWrittenValue}) is redacted — nothing ever replays a `put`.
|
|
204
|
+
*/
|
|
205
|
+
const serializeKvValue = (value) => {
|
|
206
|
+
let omitted;
|
|
207
|
+
try {
|
|
208
|
+
const json = JSON.stringify(value, (_key, nested) => {
|
|
209
|
+
const reason = omittedReason(nested);
|
|
210
|
+
if (reason !== void 0) {
|
|
211
|
+
omitted ??= reason;
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
return nested instanceof Map ? Object.fromEntries(nested) : nested;
|
|
215
|
+
});
|
|
216
|
+
return {
|
|
217
|
+
...json !== void 0 ? { captured: capture(json) } : {},
|
|
218
|
+
...omitted !== void 0 ? { omitted } : {}
|
|
219
|
+
};
|
|
220
|
+
} catch {
|
|
221
|
+
return {};
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
/**
|
|
225
|
+
* JSON of the value a `put` wrote, redacted like a request body. KV takes a string, an
|
|
226
|
+
* ArrayBuffer(View) or a stream; only the string form can be captured, and it is redacted as
|
|
227
|
+
* text before being JSON-encoded so that secret-looking fields *inside* the app's payload are
|
|
228
|
+
* caught (redacting the JSON-encoded form would only ever see one opaque string).
|
|
229
|
+
*/
|
|
230
|
+
const serializeWrittenValue = (value) => {
|
|
231
|
+
if (typeof value === "string") try {
|
|
232
|
+
return { captured: capture(JSON.stringify(redactRequestBody(value))) };
|
|
233
|
+
} catch {
|
|
234
|
+
return {};
|
|
235
|
+
}
|
|
236
|
+
return serializeKvValue(value);
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* JSON of the call's arguments. A `put` value is replaced by `null` rather than dropped, so
|
|
240
|
+
* the remaining arguments keep their positions — and so the value is only ever persisted via
|
|
241
|
+
* the redacted {@link serializeWrittenValue} path.
|
|
242
|
+
*/
|
|
243
|
+
const serializeKvArgs = (operation, args) => {
|
|
244
|
+
return serializeKvValue(operation === "put" ? args.map((arg, index) => index === 1 ? null : arg) : args).captured;
|
|
245
|
+
};
|
|
246
|
+
const omittedReason = (value) => {
|
|
247
|
+
if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return "stream";
|
|
248
|
+
if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return "binary";
|
|
249
|
+
};
|
|
250
|
+
const capture = (json) => json.length > 262144 ? {
|
|
251
|
+
body: json.slice(0, MAX_BODY_CAPTURE_SIZE),
|
|
252
|
+
truncated: true
|
|
253
|
+
} : {
|
|
254
|
+
body: json,
|
|
255
|
+
truncated: false
|
|
256
|
+
};
|
|
257
|
+
//#endregion
|
|
258
|
+
export { installKvPatch };
|
|
259
|
+
|
|
260
|
+
//# sourceMappingURL=kv-patch.js.map
|
|
261
|
+
//# debugId=93bf09ea-4e78-5ac4-92cd-661f2ce03542
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kv-patch.js","sources":["../src/kv-patch.ts"],"sourcesContent":["import { MAX_BODY_CAPTURE_SIZE } from \"./body-capture\";\nimport { type RequestCaptureContext, requestCaptureContext } from \"./context\";\nimport { warnOnce } from \"./log\";\nimport { getOriginalFetch } from \"./original-fetch\";\nimport type {\n CapturedBody,\n KvOmittedReason,\n KvOperation,\n KvOperationEvent,\n} from \"./protocol\";\nimport { redactRequestBody } from \"./redact-body\";\nimport { postCaptureEvents } from \"./sidecar-client\";\n\n/**\n * Records operations on Cloudflare KV namespace bindings (`env.MY_KV.get(key)`).\n *\n * KV is invisible to both the `globalThis.fetch` patch and the binding patch: a namespace is\n * a host object with no `fetch`, and workerd services its methods internally rather than as\n * a subrequest. So the namespace's *prototype* methods are patched instead — the same move\n * `binding-patch.ts` makes on a Fetcher, and the Node recorder on `Redis.prototype.sendCommand`.\n *\n * The prototype is reached from an instance found on `env`: as with bindings there is no\n * global to name, and going through an instance is what makes this work for an app that reads\n * its bindings from `cloudflare:workers` rather than the handler argument — that module hands\n * out a different `env` object but the same namespace instances, so the prototype is shared\n * either way.\n *\n * Verified against real workerd in `packages/backend-recorder-js/src/__tests__/`:\n * `workerd-binding-patch.spec.ts` pins the property shape this relies on (every recorded\n * method inherited and configurable, one prototype across namespaces), and\n * `workerd-kv-sidecar.spec.ts` drives real KV through the patch end to end.\n */\n\n// Marks a patched method, rather than the prototype holding it: methods can live at different\n// depths of one chain, and a base prototype can be shared with another binding type, so\n// \"already ours\" has to be answerable per function. Symbol.for so a second copy of the shim\n// (e.g. bundled twice) still detects the patch.\nconst KV_PATCHED = Symbol.for(\"meticulous.workerd.kvPatched\");\n\n/**\n * The methods recorded, and the shape a KV namespace is recognised by.\n *\n * `getWithMetadata` is what separates KV from R2: an R2 bucket also has `get`, `put`,\n * `delete` and `list`, so without it a bucket would be duck-typed as a namespace and its\n * (large, binary) objects pushed through value capture.\n */\nconst RECORDED_KV_METHODS = [\n \"get\",\n \"getWithMetadata\",\n \"put\",\n \"delete\",\n \"list\",\n] as const;\n\n/**\n * The namespaces being recorded, and the `env` key each was found under.\n *\n * Doubles as the allow-list: only an instance in here is recorded. A skipped namespace is\n * simply never registered, and — since the patch can land on a prototype shared with another\n * binding type — nothing that is not a discovered KV namespace can be recorded by accident.\n */\nconst kvBindingNames = new WeakMap<object, string>();\n\ntype KvMethod = (...args: unknown[]) => Promise<unknown>;\n\ntype KvNamespaceLike = Record<KvOperation, KvMethod>;\n\nexport interface InstallKvPatchOptions {\n /** Binding names to leave unrecorded. */\n skipBindings?: readonly string[];\n}\n\n/**\n * Discovers KV namespace bindings on `env` and patches their shared prototype so their\n * operations are recorded. Safe to call on every request — discovery is cheap and the patch\n * itself is applied once per prototype per isolate.\n *\n * Never throws: a runtime that does not permit the patch simply goes unrecorded.\n */\nexport const installKvPatch = (\n env: unknown,\n options?: InstallKvPatchOptions,\n): void => {\n try {\n for (const { name, value, skip } of kvBindings(\n env,\n options?.skipBindings,\n )) {\n // Patch even a skipped namespace's methods: they are shared with every other namespace,\n // so seeding them is what gives those coverage. Skipping is enforced by leaving the\n // instance off the allow-list below, not by declining to patch.\n patchKvMethods(value);\n if (!skip) {\n kvBindingNames.set(value, name);\n }\n }\n } catch (error) {\n warnOnce(\n \"kv-patch-install\",\n \"Failed to install the Meticulous KV patch — KV operations will not be recorded.\",\n error,\n );\n }\n};\n\ninterface DiscoveredKvBinding {\n name: string;\n value: object;\n skip: boolean;\n}\n\nconst kvBindings = (\n env: unknown,\n skipBindings: readonly string[] | undefined,\n): DiscoveredKvBinding[] => {\n if (env === null || typeof env !== \"object\") {\n return [];\n }\n const skipped = new Set<string>(skipBindings ?? []);\n const found: DiscoveredKvBinding[] = [];\n for (const [name, value] of Object.entries(env)) {\n if (isKvNamespaceLike(value)) {\n found.push({ name, value, skip: skipped.has(name) });\n }\n }\n return found;\n};\n\nconst isKvNamespaceLike = (value: unknown): value is object & KvNamespaceLike =>\n value !== null &&\n typeof value === \"object\" &&\n RECORDED_KV_METHODS.every(\n (method) =>\n typeof (value as Record<string, unknown>)[method] === \"function\",\n );\n\n/**\n * Patches every recorded method, or none of them: a half-patched namespace would record a\n * partial view of the app's KV usage, which is worse than recording none of it, because\n * nothing in the recording would say which half is missing. So the whole chain is resolved\n * first, and only then patched.\n *\n * Each method is patched where it actually lives rather than on the instance's immediate\n * prototype — workerd already puts an inherited method further up the chain for Durable\n * Object stubs, so assuming one flat prototype is not safe.\n */\nconst patchKvMethods = (binding: object): void => {\n const owners = new Map<KvOperation, MethodOwner>();\n for (const method of RECORDED_KV_METHODS) {\n const owner = findMethodOwner(binding, method);\n if (owner === undefined) {\n // Either the method is an own per-instance property or the runtime has locked the\n // prototype. Recording KV is not possible; everything else keeps working.\n warnOnce(\n \"kv-patch-unsupported\",\n `This runtime does not expose a patchable KV \\`${method}\\` — KV operations will not be recorded.`,\n );\n return;\n }\n owners.set(method, owner);\n }\n\n for (const [method, { owner, original }] of owners) {\n if ((original as unknown as Record<symbol, unknown>)[KV_PATCHED] === true) {\n continue;\n }\n Object.defineProperty(owner, method, {\n value: patchedKvMethod(method, original),\n writable: true,\n enumerable: false,\n configurable: true,\n });\n }\n};\n\ninterface MethodOwner {\n owner: object;\n original: KvMethod;\n}\n\n/**\n * The prototype whose `method` a call on `instance` would reach, or undefined if there is none\n * or it cannot be replaced. The search stops at the first prototype that *has* the property,\n * patchable or not: that is the one a call resolves to, so anything further up is shadowed.\n */\nconst findMethodOwner = (\n instance: object,\n method: KvOperation,\n): MethodOwner | undefined => {\n if (Object.hasOwn(instance, method)) {\n // An own per-instance method would shadow anything we patched on the prototype.\n return undefined;\n }\n let current: object | null = Object.getPrototypeOf(instance) as object | null;\n while (current !== null) {\n const descriptor = Object.getOwnPropertyDescriptor(current, method);\n if (descriptor !== undefined) {\n return typeof descriptor.value === \"function\" &&\n descriptor.configurable === true\n ? { owner: current, original: descriptor.value as KvMethod }\n : undefined;\n }\n current = Object.getPrototypeOf(current) as object | null;\n }\n return undefined;\n};\n\n/**\n * A `function`, not an arrow: `this` is the namespace the call was made on, and it must be\n * forwarded to the original or workerd throws \"Illegal invocation\".\n */\nconst patchedKvMethod = (\n operation: KvOperation,\n original: KvMethod,\n): KvMethod => {\n const patched = function (\n this: unknown,\n ...args: unknown[]\n ): Promise<unknown> {\n const passThrough = (): Promise<unknown> => original.apply(this, args);\n\n const ctx = requestCaptureContext.getStore();\n // Record mode only. `installKvPatch` is not called for a replay request, but the patch is\n // per-isolate: a record request could have installed it earlier, and no mock store serves\n // KV, so a replay request must reach the real namespace.\n if (!ctx || ctx.mode !== \"record\") {\n return passThrough();\n }\n const receiver =\n typeof this === \"object\" && this !== null ? this : undefined;\n // Only namespaces discovered on `env` are recorded — see `kvBindingNames`.\n const bindingName =\n receiver === undefined ? undefined : kvBindingNames.get(receiver);\n if (bindingName === undefined) {\n return passThrough();\n }\n\n return captureKvOperation(ctx, operation, bindingName, args, passThrough);\n };\n Object.defineProperty(patched, KV_PATCHED, {\n value: true,\n enumerable: false,\n configurable: true,\n });\n return patched;\n};\n\n/**\n * Records an operation without affecting it: the real method runs untouched and its result is\n * returned as-is, with the event reported in the background via `ctx.waitUntil`. Any capture\n * failure is warned about once and swallowed — recording must never break the app.\n */\nconst captureKvOperation = async (\n ctx: RequestCaptureContext,\n operation: KvOperation,\n bindingName: string,\n args: unknown[],\n invoke: () => Promise<unknown>,\n): Promise<unknown> => {\n const startTimeMs = Date.now();\n let result: unknown;\n try {\n result = await invoke();\n } catch (error) {\n report(ctx, operation, bindingName, args, startTimeMs, {\n error: String(error),\n });\n throw error;\n }\n report(ctx, operation, bindingName, args, startTimeMs, { result });\n return result;\n};\n\nconst report = (\n ctx: RequestCaptureContext,\n operation: KvOperation,\n bindingName: string,\n args: unknown[],\n startTimeMs: number,\n outcome: { result: unknown } | { error: string },\n): void => {\n try {\n const event = buildKvEvent(\n ctx,\n operation,\n bindingName,\n args,\n startTimeMs,\n outcome,\n );\n // postCaptureEvents never rejects — it warns once on an unreachable sidecar.\n ctx.waitUntil(\n postCaptureEvents(getOriginalFetch(), ctx.sidecarUrl, [event]),\n );\n } catch (error) {\n warnOnce(\"kv-report\", \"Failed to report a KV operation.\", error);\n }\n};\n\nconst buildKvEvent = (\n ctx: RequestCaptureContext,\n operation: KvOperation,\n bindingName: string,\n args: unknown[],\n startTimeMs: number,\n outcome: { result: unknown } | { error: string },\n): KvOperationEvent => {\n const [key] = args;\n const written =\n operation === \"put\" ? serializeWrittenValue(args[1]) : undefined;\n const read =\n \"result\" in outcome ? serializeKvValue(outcome.result) : undefined;\n const omitted = written?.omitted ?? read?.omitted;\n const serializedArgs = serializeKvArgs(operation, args);\n\n return {\n kind: \"kv\",\n requestId: ctx.requestId,\n ...(ctx.frontendSessionId !== undefined\n ? { frontendSessionId: ctx.frontendSessionId }\n : {}),\n bindingName,\n operation,\n ...(typeof key === \"string\" ? { key } : {}),\n ...(serializedArgs !== undefined ? { args: serializedArgs } : {}),\n ...(written?.captured !== undefined ? { value: written.captured } : {}),\n ...(read?.captured !== undefined ? { result: read.captured } : {}),\n ...(omitted !== undefined ? { omitted } : {}),\n startTimeMs,\n endTimeMs: Date.now(),\n ...(\"error\" in outcome ? { error: outcome.error } : {}),\n };\n};\n\ninterface SerializedKvValue {\n captured?: CapturedBody;\n omitted?: KvOmittedReason;\n}\n\n/**\n * JSON of a value workerd returned, with anything unpersistable replaced by `null` and the\n * reason reported alongside. A `Map` (what a bulk `get` returns) becomes a plain object,\n * which `JSON.stringify` would otherwise flatten to `{}`.\n *\n * Read values are stored verbatim, deliberately: a future replay would serve them straight\n * back to the app, so redacting one would corrupt what the app receives. Only the write path\n * ({@link serializeWrittenValue}) is redacted — nothing ever replays a `put`.\n */\nconst serializeKvValue = (value: unknown): SerializedKvValue => {\n let omitted: KvOmittedReason | undefined;\n try {\n const json = JSON.stringify(value, (_key: string, nested: unknown) => {\n const reason = omittedReason(nested);\n if (reason !== undefined) {\n omitted ??= reason;\n return null;\n }\n return nested instanceof Map\n ? Object.fromEntries(nested as Map<string, unknown>)\n : nested;\n });\n return {\n // `undefined` (what `put`/`delete` resolve to) has no JSON form — nothing to capture.\n ...(json !== undefined ? { captured: capture(json) } : {}),\n ...(omitted !== undefined ? { omitted } : {}),\n };\n } catch {\n // Circular, or a getter that throws. The operation itself is still recorded.\n return {};\n }\n};\n\n/**\n * JSON of the value a `put` wrote, redacted like a request body. KV takes a string, an\n * ArrayBuffer(View) or a stream; only the string form can be captured, and it is redacted as\n * text before being JSON-encoded so that secret-looking fields *inside* the app's payload are\n * caught (redacting the JSON-encoded form would only ever see one opaque string).\n */\nconst serializeWrittenValue = (value: unknown): SerializedKvValue => {\n if (typeof value === \"string\") {\n try {\n return { captured: capture(JSON.stringify(redactRequestBody(value))) };\n } catch {\n return {};\n }\n }\n return serializeKvValue(value);\n};\n\n/**\n * JSON of the call's arguments. A `put` value is replaced by `null` rather than dropped, so\n * the remaining arguments keep their positions — and so the value is only ever persisted via\n * the redacted {@link serializeWrittenValue} path.\n */\nconst serializeKvArgs = (\n operation: KvOperation,\n args: unknown[],\n): CapturedBody | undefined => {\n const withoutValue =\n operation === \"put\"\n ? args.map((arg, index) => (index === 1 ? null : arg))\n : args;\n return serializeKvValue(withoutValue).captured;\n};\n\nconst omittedReason = (value: unknown): KvOmittedReason | undefined => {\n // A stream is never read, only recognised: reading it would consume the app's bytes.\n if (\n typeof ReadableStream !== \"undefined\" &&\n value instanceof ReadableStream\n ) {\n return \"stream\";\n }\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n return \"binary\";\n }\n return undefined;\n};\n\nconst capture = (json: string): CapturedBody =>\n json.length > MAX_BODY_CAPTURE_SIZE\n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AAM,OAAO,KAAK,UAAU,QAAQ,MAAc,WAAoB;GACpE,MAAM,SAAS,cAAc,OAAO;AACpC,OAAI,WAAW,KAAA,GAAW;AACxB,gBAAY;AACZ,WAAO;;AAET,UAAO,kBAAkB,MACrB,OAAO,YAAY,OAA+B,GAClD;IACJ;AACF,SAAO;GAEL,GAAI,SAAS,KAAA,IAAY,EAAE,UAAU,QAAQ,KAAK,EAAE,GAAG,EAAE;GACzD,GAAI,YAAY,KAAA,IAAY,EAAE,SAAS,GAAG,EAAE;GAC7C;SACK;AAEN,SAAO,EAAE;;;;;;;;;AAUb,MAAM,yBAAyB,UAAsC;AACnE,KAAI,OAAO,UAAU,SACnB,KAAI;AACF,SAAO,EAAE,UAAU,QAAQ,KAAK,UAAU,kBAAkB,MAAM,CAAC,CAAC,EAAE;SAChE;AACN,SAAO,EAAE;;AAGb,QAAO,iBAAiB,MAAM;;;;;;;AAQhC,MAAM,mBACJ,WACA,SAC6B;AAK7B,QAAO,iBAHL,cAAc,QACV,KAAK,KAAK,KAAK,UAAW,UAAU,IAAI,OAAO,IAAK,GACpD,KAC+B,CAAC;;AAGxC,MAAM,iBAAiB,UAAgD;AAErE,KACE,OAAO,mBAAmB,eAC1B,iBAAiB,eAEjB,QAAO;AAET,KAAI,iBAAiB,eAAe,YAAY,OAAO,MAAM,CAC3D,QAAO;;AAKX,MAAM,WAAW,SACf,KAAK,SAAA,SACD;CAAE,MAAM,KAAK,MAAM,GAAG,sBAAsB;CAAE,WAAW;CAAM,GAC/D;CAAE,MAAM;CAAM,WAAW;CAAO","debugId":"93bf09ea-4e78-5ac4-92cd-661f2ce03542"}
|
package/dist/log.js
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
//#region src/log.ts
|
|
2
|
+
/**
|
|
3
|
+
* console.warn every time. Only for something the app is about to see anyway (a replay call
|
|
4
|
+
* that cannot be served, which throws), where knowing _which_ call it was matters more than
|
|
5
|
+
* keeping the log short — a deduped key would hide every miss after the first.
|
|
6
|
+
*/
|
|
2
7
|
|
|
3
|
-
!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]="
|
|
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]="af311c85-9c8c-5901-81b9-33d469149fa7")}catch(e){}}();
|
|
9
|
+
const warn = (message) => {
|
|
10
|
+
console.warn(`[meticulous] ${message}`);
|
|
11
|
+
};
|
|
4
12
|
const warned = /* @__PURE__ */ new Set();
|
|
5
13
|
/** console.warn once per unique key — capture problems must never spam or break the app. */
|
|
6
14
|
const warnOnce = (key, message, error) => {
|
|
@@ -10,7 +18,7 @@ const warnOnce = (key, message, error) => {
|
|
|
10
18
|
else console.warn(`[meticulous] ${message}`, error);
|
|
11
19
|
};
|
|
12
20
|
//#endregion
|
|
13
|
-
export { warnOnce };
|
|
21
|
+
export { warn, warnOnce };
|
|
14
22
|
|
|
15
23
|
//# sourceMappingURL=log.js.map
|
|
16
|
-
//# debugId=
|
|
24
|
+
//# debugId=af311c85-9c8c-5901-81b9-33d469149fa7
|
package/dist/log.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log.js","sources":["../src/log.ts"],"sourcesContent":["const warned = new Set<string>();\n\n/** console.warn once per unique key — capture problems must never spam or break the app. */\nexport const warnOnce = (\n key: string,\n message: string,\n error?: unknown,\n): void => {\n if (warned.has(key)) {\n return;\n }\n warned.add(key);\n if (error === undefined) {\n console.warn(`[meticulous] ${message}`);\n } else {\n console.warn(`[meticulous] ${message}`, error);\n }\n};\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"log.js","sources":["../src/log.ts"],"sourcesContent":["/**\n * console.warn every time. Only for something the app is about to see anyway (a replay call\n * that cannot be served, which throws), where knowing _which_ call it was matters more than\n * keeping the log short — a deduped key would hide every miss after the first.\n */\nexport const warn = (message: string): void => {\n console.warn(`[meticulous] ${message}`);\n};\n\nconst warned = new Set<string>();\n\n/** console.warn once per unique key — capture problems must never spam or break the app. */\nexport const warnOnce = (\n key: string,\n message: string,\n error?: unknown,\n): void => {\n if (warned.has(key)) {\n return;\n }\n warned.add(key);\n if (error === undefined) {\n console.warn(`[meticulous] ${message}`);\n } else {\n console.warn(`[meticulous] ${message}`, error);\n }\n};\n"],"names":[],"mappings":";;;;;;;;AAKA,MAAa,QAAQ,YAA0B;AAC7C,SAAQ,KAAK,gBAAgB,UAAU;;AAGzC,MAAM,yBAAS,IAAI,KAAa;;AAGhC,MAAa,YACX,KACA,SACA,UACS;AACT,KAAI,OAAO,IAAI,IAAI,CACjB;AAEF,QAAO,IAAI,IAAI;AACf,KAAI,UAAU,KAAA,EACZ,SAAQ,KAAK,gBAAgB,UAAU;KAEvC,SAAQ,KAAK,gBAAgB,WAAW,MAAM","debugId":"af311c85-9c8c-5901-81b9-33d469149fa7"}
|