@timber-js/app 0.2.0-alpha.234 → 0.2.0-alpha.236
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/dist/_chunks/{actions-CYjRMpZI.js → actions-Top9GftB.js} +3 -3
- package/dist/_chunks/{actions-CYjRMpZI.js.map → actions-Top9GftB.js.map} +1 -1
- package/dist/_chunks/{cache-api-BZJNt01a.js → cache-api-Bo8c7XVF.js} +6 -6
- package/dist/_chunks/{cache-api-BZJNt01a.js.map → cache-api-Bo8c7XVF.js.map} +1 -1
- package/dist/_chunks/{chains-D-RRc7CM.js → chains-BsGKkMTK.js} +2 -2
- package/dist/_chunks/{chains-D-RRc7CM.js.map → chains-BsGKkMTK.js.map} +1 -1
- package/dist/_chunks/chains-DHmoKxkO.js +1 -0
- package/dist/_chunks/{classify-_W0RWa5w.js → classify-cmE0Gins.js} +2 -2
- package/dist/_chunks/{classify-_W0RWa5w.js.map → classify-cmE0Gins.js.map} +1 -1
- package/dist/_chunks/{cli-check-BAKOSTkg.js → cli-check-BwiahbTC.js} +5 -5
- package/dist/_chunks/{cli-check-BAKOSTkg.js.map → cli-check-BwiahbTC.js.map} +1 -1
- package/dist/_chunks/{cli-context-BPdyA7Fp.js → cli-context-BbwVqarO.js} +1 -1
- package/dist/_chunks/{cli-context-CwTKMjVe.js → cli-context-DZh5v0yd.js} +2 -2
- package/dist/_chunks/{cli-context-CwTKMjVe.js.map → cli-context-DZh5v0yd.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-CAllbqRB.js → cli-schema-sync-B2ldclRO.js} +3 -3
- package/dist/_chunks/{cli-schema-sync-CAllbqRB.js.map → cli-schema-sync-B2ldclRO.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-y_8ijmzO.js → cli-schema-sync-Brw7kTmm.js} +1 -1
- package/dist/_chunks/{client-dep-entries-C9hv-3k9.js → client-dep-entries-C1nMlLKV.js} +2 -2
- package/dist/_chunks/{client-dep-entries-C9hv-3k9.js.map → client-dep-entries-C1nMlLKV.js.map} +1 -1
- package/dist/_chunks/{cloudflare-_2fhxQE8.js → cloudflare-Dk5Hqo-O.js} +3 -3
- package/dist/_chunks/{cloudflare-_2fhxQE8.js.map → cloudflare-Dk5Hqo-O.js.map} +1 -1
- package/dist/_chunks/{convention-lint-D54k6uUM.js → convention-lint-CLpuzY5h.js} +3 -3
- package/dist/_chunks/{convention-lint-D54k6uUM.js.map → convention-lint-CLpuzY5h.js.map} +1 -1
- package/dist/_chunks/dev-server-BGGGhHXx.js +1 -0
- package/dist/_chunks/{dev-server-Rq659RR1.js → dev-server-lrdpD7Ws.js} +122 -6
- package/dist/_chunks/dev-server-lrdpD7Ws.js.map +1 -0
- package/dist/_chunks/{dev-span-_NzMX-au.js → dev-span-RsVeYYc_.js} +5 -2
- package/dist/_chunks/dev-span-RsVeYYc_.js.map +1 -0
- package/dist/_chunks/{error-boundary-Cf1m-Ywk.js → error-boundary-Bh-egWUI.js} +6 -6
- package/dist/_chunks/{error-boundary-Cf1m-Ywk.js.map → error-boundary-Bh-egWUI.js.map} +1 -1
- package/dist/_chunks/{flight-source-node-BGanuoSS.js → flight-source-node-BO_xD9jC.js} +2 -2
- package/dist/_chunks/{flight-source-node-BGanuoSS.js.map → flight-source-node-BO_xD9jC.js.map} +1 -1
- package/dist/_chunks/{href-BtspoNc9.js → href-8l5VD23D.js} +2 -2
- package/dist/_chunks/{href-BtspoNc9.js.map → href-8l5VD23D.js.map} +1 -1
- package/dist/_chunks/{json-lossy-check-BXM45k8p.js → json-lossy-check-D47R9Fp5.js} +2 -2
- package/dist/_chunks/{json-lossy-check-BXM45k8p.js.map → json-lossy-check-D47R9Fp5.js.map} +1 -1
- package/dist/_chunks/{live-graph-C7-yA8W9.js → live-graph-ChuFfmLi.js} +4 -4
- package/dist/_chunks/{live-graph-C7-yA8W9.js.map → live-graph-ChuFfmLi.js.map} +1 -1
- package/dist/_chunks/{logger-YtMSKfft.js → logger-DDLtp5e-.js} +16 -1
- package/dist/_chunks/logger-DDLtp5e-.js.map +1 -0
- package/dist/_chunks/navigation-root-Cvb7P1ud.js.map +1 -1
- package/dist/_chunks/{node-response-D3hXWb8y.js → node-response-DNNnKnoS.js} +2 -2
- package/dist/_chunks/{node-response-D3hXWb8y.js.map → node-response-DNNnKnoS.js.map} +1 -1
- package/dist/_chunks/{plugin-context-FCkaNLUB.js → plugin-context-BtaQcMuh.js} +2 -2
- package/dist/_chunks/{plugin-context-FCkaNLUB.js.map → plugin-context-BtaQcMuh.js.map} +1 -1
- package/dist/_chunks/{plugin-context-BfSRKJfz.js → plugin-context-I1dvGccO.js} +1 -1
- package/dist/_chunks/{poison-scan-CRSP06Es.js → poison-scan-CJ9QfJWb.js} +2 -2
- package/dist/_chunks/{poison-scan-CRSP06Es.js.map → poison-scan-CJ9QfJWb.js.map} +1 -1
- package/dist/_chunks/{scanner-BNQ4qnLX.js → scanner-CrB_h6FA.js} +5 -5
- package/dist/_chunks/{scanner-BNQ4qnLX.js.map → scanner-CrB_h6FA.js.map} +1 -1
- package/dist/_chunks/{sizeof-Cmx6Fs-Y.js → sizeof-DVhEVN_y.js} +2 -2
- package/dist/_chunks/{sizeof-Cmx6Fs-Y.js.map → sizeof-DVhEVN_y.js.map} +1 -1
- package/dist/_chunks/{walkers-D_QHR_nf.js → walkers-BUvpsb2Q.js} +3 -3
- package/dist/_chunks/{walkers-D_QHR_nf.js.map → walkers-BUvpsb2Q.js.map} +1 -1
- package/dist/adapters/cloudflare-dev.js +1 -1
- package/dist/adapters/cloudflare-kv-cache.js +2 -2
- package/dist/adapters/cloudflare.js +1 -1
- package/dist/adapters/nitro.js +1 -1
- package/dist/analyze/crawl-entry.js +4 -4
- package/dist/analyze/graph-command.js +5 -5
- package/dist/cache/index.js +2 -2
- package/dist/cache/stores/memory.js +1 -1
- package/dist/cli.js +6 -6
- package/dist/client/dev-pill/index.d.ts +2 -1
- package/dist/client/dev-pill/index.d.ts.map +1 -1
- package/dist/client/dev-pill/store.d.ts +0 -18
- package/dist/client/dev-pill/store.d.ts.map +1 -1
- package/dist/client/dev-pill/view.d.ts.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/index.js +4 -4
- package/dist/client/internal.js +3 -3
- package/dist/cookies/index.js +1 -1
- package/dist/dev-tools/await-span.d.ts +12 -1
- package/dist/dev-tools/await-span.d.ts.map +1 -1
- package/dist/dev-tools/instrumentation.d.ts.map +1 -1
- package/dist/dev-tools/logger.d.ts +8 -2
- package/dist/dev-tools/logger.d.ts.map +1 -1
- package/dist/dev-tools/span-sink.d.ts +9 -1
- package/dist/dev-tools/span-sink.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +183 -40
- package/dist/index.js.map +1 -1
- package/dist/native/rsc/_react/chunks/{react-server-dom-webpack-server.node.development-hQ_odxIB.js → react-server-dom-webpack-server.node.development-CAttMzVD.js} +2 -2
- package/dist/native/rsc/_react/flight-client.js +2 -2
- package/dist/native/rsc/_react/flight-server.js +1 -1
- package/dist/native/rsc/_react/flight-static.js +1 -1
- package/dist/native/rsc/adapters/cloudflare-kv-cache.js +1 -1
- package/dist/native/rsc/adapters/cloudflare.js +2 -2
- package/dist/native/rsc/cache/cache-api.js +3 -3
- package/dist/native/rsc/cache/index.js +3 -3
- package/dist/native/rsc/cache/timber-cache.js +2 -2
- package/dist/native/rsc/cdn/index.js +1 -1
- package/dist/native/rsc/client/use-cookie.js +1 -1
- package/dist/native/rsc/dev-tools/404-page.js +1 -1
- package/dist/native/rsc/dev-tools/await-span.js +10 -7
- package/dist/native/rsc/dev-tools/await-span.js.map +1 -1
- package/dist/native/rsc/dev-tools/error-page.js +2 -2
- package/dist/native/rsc/dev-tools/instrumentation.js +38 -3
- package/dist/native/rsc/dev-tools/instrumentation.js.map +1 -1
- package/dist/native/rsc/dev-tools/logger.js +123 -80
- package/dist/native/rsc/dev-tools/logger.js.map +1 -1
- package/dist/native/rsc/dev-tools/span-sink.js +1 -0
- package/dist/native/rsc/dev-tools/span-sink.js.map +1 -1
- package/dist/native/rsc/dev-tools/terminal.js +1 -1
- package/dist/native/rsc/manifest.json +2 -2
- package/dist/native/rsc/params/index.js +1 -1
- package/dist/native/rsc/routing/collision-probe.js +1 -1
- package/dist/native/rsc/routing/interception.js +1 -1
- package/dist/native/rsc/search-params/define.js +2 -2
- package/dist/native/rsc/server/access-gate.js +1 -1
- package/dist/native/rsc/server/action-client.js +2 -2
- package/dist/native/rsc/server/action-handler.js +8 -8
- package/dist/native/rsc/server/actions.js +3 -3
- package/dist/native/rsc/server/children-interception.js +1 -1
- package/dist/native/rsc/server/deny-boundary.js +1 -1
- package/dist/native/rsc/server/deny-renderer.js +10 -10
- package/dist/native/rsc/server/fallback-error.js +1 -1
- package/dist/native/rsc/server/flight-injector-core.js +2 -2
- package/dist/native/rsc/server/flight-source-node.js +2 -2
- package/dist/native/rsc/server/index.js +4 -4
- package/dist/native/rsc/server/interception-gates.js +2 -2
- package/dist/native/rsc/server/internal.js +15 -15
- package/dist/native/rsc/server/logger.js +2 -2
- package/dist/native/rsc/server/metadata-route-links.js +1 -1
- package/dist/native/rsc/server/node-body-response.js +1 -1
- package/dist/native/rsc/server/param-coercion.js +1 -1
- package/dist/native/rsc/server/pipeline-helpers.js +10 -10
- package/dist/native/rsc/server/pipeline-interception.js +4 -4
- package/dist/native/rsc/server/pipeline-metadata-route.js +10 -10
- package/dist/native/rsc/server/pipeline-outcome.js +4 -4
- package/dist/native/rsc/server/pipeline-phases.js +11 -11
- package/dist/native/rsc/server/pipeline.js +10 -10
- package/dist/native/rsc/server/prebuilt/capture-render.js +1 -1
- package/dist/native/rsc/server/prebuilt/dev-store.js +1 -1
- package/dist/native/rsc/server/prebuilt/overlay.js +3 -3
- package/dist/native/rsc/server/prebuilt-builder.js +8 -8
- package/dist/native/rsc/server/prebuilt-runtime.js +15 -15
- package/dist/native/rsc/server/primitives.js +2 -2
- package/dist/native/rsc/server/publish-params.js +1 -1
- package/dist/native/rsc/server/request-context.js +1 -1
- package/dist/native/rsc/server/route-element-builder.js +7 -7
- package/dist/native/rsc/server/route-element-helpers.js +1 -1
- package/dist/native/rsc/server/route-handler.js +1 -1
- package/dist/native/rsc/server/rsc-entry/action-dispatcher.js +1 -1
- package/dist/native/rsc/server/rsc-entry/action-middleware-runner.js +1 -1
- package/dist/native/rsc/server/rsc-entry/api-handler.js +1 -1
- package/dist/native/rsc/server/rsc-entry/deny-fallback.js +6 -6
- package/dist/native/rsc/server/rsc-entry/error-renderer.js +7 -7
- package/dist/native/rsc/server/rsc-entry/helpers.js +1 -1
- package/dist/native/rsc/server/rsc-entry/render-route.js +4 -4
- package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js +7 -7
- package/dist/native/rsc/server/rsc-entry/rsc-payload.js +3 -3
- package/dist/native/rsc/server/rsc-entry/rsc-stream.js +6 -6
- package/dist/native/rsc/server/rsc-entry/ssr-renderer.js +10 -10
- package/dist/native/rsc/server/rsc-error-envelope.js +1 -1
- package/dist/native/rsc/server/sitemap-handler.js +1 -1
- package/dist/native/rsc/server/skippable-prefix.js +2 -2
- package/dist/native/rsc/server/slot-interception.js +1 -1
- package/dist/native/rsc/server/slot-resolver.js +11 -11
- package/dist/native/rsc/server/static-generator.js +2 -2
- package/dist/native/rsc/server/traced-access.js +1 -1
- package/dist/native/rsc/server/tracing.js +10 -0
- package/dist/native/rsc/server/tracing.js.map +1 -1
- package/dist/native/rsc/shared/dev-span.js +11 -4
- package/dist/native/rsc/shared/dev-span.js.map +1 -1
- package/dist/native/rsc/shared/href.js +1 -1
- package/dist/native/rsc/shared/span-waterfall.js +90 -0
- package/dist/native/rsc/shared/span-waterfall.js.map +1 -0
- package/dist/native/ssr/adapters/cloudflare-kv-cache.js +1 -1
- package/dist/native/ssr/adapters/cloudflare.js +2 -2
- package/dist/native/ssr/cache/cache-api.js +3 -3
- package/dist/native/ssr/cache/guarded-read.js +1 -1
- package/dist/native/ssr/cache/index.js +3 -3
- package/dist/native/ssr/cache/timber-cache.js +3 -3
- package/dist/native/ssr/cdn/index.js +1 -1
- package/dist/native/ssr/client/error-boundary.js +1 -1
- package/dist/native/ssr/client/index.js +5 -5
- package/dist/native/ssr/client/link.js +5 -5
- package/dist/native/ssr/client/navigation-commit.js +2 -2
- package/dist/native/ssr/client/nuqs-adapter.js +2 -2
- package/dist/native/ssr/client/params-context.js +1 -1
- package/dist/native/ssr/client/router-skew.js +1 -1
- package/dist/native/ssr/client/rsc-fetch.js +2 -2
- package/dist/native/ssr/client/use-pending-navigation.js +1 -1
- package/dist/native/ssr/client/use-search-params.js +2 -2
- package/dist/native/ssr/client/use-segment-params.js +1 -1
- package/dist/native/ssr/client/use-selected-layout-segment.js +1 -1
- package/dist/native/ssr/dev-tools/await-span.js +10 -7
- package/dist/native/ssr/dev-tools/await-span.js.map +1 -1
- package/dist/native/ssr/dev-tools/instrumentation.js +38 -3
- package/dist/native/ssr/dev-tools/instrumentation.js.map +1 -1
- package/dist/native/ssr/dev-tools/logger.js +123 -80
- package/dist/native/ssr/dev-tools/logger.js.map +1 -1
- package/dist/native/ssr/dev-tools/span-sink.js +1 -0
- package/dist/native/ssr/dev-tools/span-sink.js.map +1 -1
- package/dist/native/ssr/manifest.json +1 -0
- package/dist/native/ssr/params/index.js +1 -1
- package/dist/native/ssr/search-params/define.js +2 -2
- package/dist/native/ssr/server/access-gate.js +1 -1
- package/dist/native/ssr/server/action-client.js +2 -2
- package/dist/native/ssr/server/actions.js +3 -3
- package/dist/native/ssr/server/deny-boundary.js +2 -2
- package/dist/native/ssr/server/flight-injector-core.js +1 -1
- package/dist/native/ssr/server/flight-source-node.js +2 -2
- package/dist/native/ssr/server/index.js +4 -4
- package/dist/native/ssr/server/internal.js +12 -12
- package/dist/native/ssr/server/logger.js +2 -2
- package/dist/native/ssr/server/node-body-response.js +1 -1
- package/dist/native/ssr/server/node-stream-transforms.js +2 -2
- package/dist/native/ssr/server/param-coercion.js +3 -3
- package/dist/native/ssr/server/pipeline-helpers.js +7 -7
- package/dist/native/ssr/server/pipeline-interception.js +4 -4
- package/dist/native/ssr/server/pipeline-metadata-route.js +10 -10
- package/dist/native/ssr/server/pipeline-outcome.js +4 -4
- package/dist/native/ssr/server/pipeline-phases.js +10 -10
- package/dist/native/ssr/server/pipeline.js +10 -10
- package/dist/native/ssr/server/prebuilt/capture-render.js +2 -2
- package/dist/native/ssr/server/prebuilt/dev-store.js +1 -1
- package/dist/native/ssr/server/prebuilt/overlay.js +4 -4
- package/dist/native/ssr/server/prebuilt-runtime.js +14 -14
- package/dist/native/ssr/server/primitives.js +2 -2
- package/dist/native/ssr/server/request-context.js +2 -2
- package/dist/native/ssr/server/route-handler.js +1 -1
- package/dist/native/ssr/server/rsc-error-envelope.js +1 -1
- package/dist/native/ssr/server/ssr-form-state.js +2 -2
- package/dist/native/ssr/server/ssr-wrappers.js +1 -1
- package/dist/native/ssr/server/traced-access.js +1 -1
- package/dist/native/ssr/server/tracing.js +10 -0
- package/dist/native/ssr/server/tracing.js.map +1 -1
- package/dist/native/ssr/shared/dev-span.js +11 -4
- package/dist/native/ssr/shared/dev-span.js.map +1 -1
- package/dist/native/ssr/shared/href.js +1 -1
- package/dist/native/ssr/shared/span-waterfall.js +90 -0
- package/dist/native/ssr/shared/span-waterfall.js.map +1 -0
- package/dist/plugins/dev-await.d.ts +3 -0
- package/dist/plugins/dev-await.d.ts.map +1 -1
- package/dist/plugins/dev-precompile.d.ts +84 -0
- package/dist/plugins/dev-precompile.d.ts.map +1 -0
- package/dist/plugins/dev-server.d.ts.map +1 -1
- package/dist/plugins/entries.d.ts.map +1 -1
- package/dist/plugins/native-runtime.d.ts +2 -2
- package/dist/plugins/native-runtime.d.ts.map +1 -1
- package/dist/plugins/plugin-rsc-package.d.ts +35 -0
- package/dist/plugins/plugin-rsc-package.d.ts.map +1 -0
- package/dist/plugins/virtual-ids.d.ts +16 -0
- package/dist/plugins/virtual-ids.d.ts.map +1 -0
- package/dist/routes/index.js +1 -1
- package/dist/routing/index.js +3 -3
- package/dist/search-params/index.js +2 -2
- package/dist/server/index.js +2 -2
- package/dist/server/internal.js +14 -14
- package/dist/server/tracing.d.ts.map +1 -1
- package/dist/shared/dev-span.d.ts +21 -3
- package/dist/shared/dev-span.d.ts.map +1 -1
- package/dist/shared/span-waterfall.d.ts +88 -0
- package/dist/shared/span-waterfall.d.ts.map +1 -0
- package/package.json +3 -3
- package/src/client/dev-pill/index.ts +5 -2
- package/src/client/dev-pill/store.ts +5 -64
- package/src/client/dev-pill/view.ts +175 -53
- package/src/dev-tools/await-span.ts +32 -13
- package/src/dev-tools/instrumentation.ts +44 -6
- package/src/dev-tools/logger.ts +230 -155
- package/src/dev-tools/span-sink.ts +34 -3
- package/src/index.ts +24 -21
- package/src/plugins/dev-await.ts +61 -3
- package/src/plugins/dev-precompile.ts +168 -0
- package/src/plugins/dev-server.ts +16 -3
- package/src/plugins/entries.ts +1 -11
- package/src/plugins/native-runtime.ts +4 -3
- package/src/plugins/plugin-rsc-package.ts +81 -0
- package/src/plugins/virtual-ids.ts +15 -0
- package/src/server/tracing.ts +29 -0
- package/src/shared/dev-span.ts +29 -6
- package/src/shared/span-waterfall.ts +227 -0
- package/dist/_chunks/chains-KblEfYzm.js +0 -1
- package/dist/_chunks/dev-server-L8biS7Az.js +0 -1
- package/dist/_chunks/dev-server-Rq659RR1.js.map +0 -1
- package/dist/_chunks/dev-span-_NzMX-au.js.map +0 -1
- package/dist/_chunks/logger-YtMSKfft.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as DEFAULT_MAX_BUFFER_BYTES, f as releaseReason, l as teeBufferExceeded, p as onAbortUntil, s as createStreamTimingRecorder, t as NODE_BODY, u as wrapResponseWithStreamTiming } from "./node-response-
|
|
1
|
+
import { a as DEFAULT_MAX_BUFFER_BYTES, f as releaseReason, l as teeBufferExceeded, p as onAbortUntil, s as createStreamTimingRecorder, t as NODE_BODY, u as wrapResponseWithStreamTiming } from "./node-response-DNNnKnoS.js";
|
|
2
2
|
import { r as RenderTimeoutError } from "./render-timeout-MrrqD1wd.js";
|
|
3
3
|
import { Readable, Transform, pipeline } from "node:stream";
|
|
4
4
|
// src/server/node-body-response.ts
|
|
@@ -513,4 +513,4 @@ function whenNodeFlightReadable(source) {
|
|
|
513
513
|
}
|
|
514
514
|
export { destroyNodeFlight, nodeFlightResponse, pipeFlightToNode, teeNodeFlight, whenNodeFlightReadable };
|
|
515
515
|
|
|
516
|
-
//# sourceMappingURL=flight-source-node-
|
|
516
|
+
//# sourceMappingURL=flight-source-node-BO_xD9jC.js.map
|
package/dist/_chunks/{flight-source-node-BGanuoSS.js.map → flight-source-node-BO_xD9jC.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flight-source-node-BGanuoSS.js","names":["ignoreError"],"sources":["../../src/server/node-body-response.ts","../../src/server/flight-source-node.ts"],"sourcesContent":["/**\n * `NodeBodyResponse` — a `Response` whose body is a Node `Readable`, so a\n * response built on Node streams reaches the socket without a Web Streams\n * round trip (LOCAL-1475). Node only: loaded behind `nodeStreamsPlatform`.\n *\n * The status and headers are an ordinary `Response`'s. The body stays a Node\n * stream until one of two things takes it:\n *\n * - **An adapter**, through `_toNodeResponse()` — srvx's protocol (nitro and\n * the dev server send with srvx; nitro-preview's sender speaks it too). The\n * stream is piped straight into `ServerResponse`.\n * - **Web-API code** reading `body`, `text()`, `arrayBuffer()`, `clone()`, …\n * The response then converts its body once, with `Readable.toWeb`, and\n * behaves as a native `Response` from then on. Correct anywhere, so code\n * that does not know about Node bodies keeps working; pipeline code on the\n * hot path goes through `node-response.ts` instead, which never converts.\n *\n * Pattern from srvx's `NodeResponse` (`FastResponse`).\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport { Readable, Transform, pipeline, type Duplex } from 'node:stream';\nimport { NODE_BODY, type NodeBodyOps } from './node-response.ts';\nimport { createStreamTimingRecorder, wrapResponseWithStreamTiming } from './stream-utils.ts';\n\n/** Statuses whose responses carry no body (Fetch \"null body status\"). */\nconst NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);\n\nfunction ignoreError(): void {}\n\n/** Destroy a body nothing will read, without an unhandled `'error'`. */\nfunction destroyBody(body: Readable): void {\n if (!body.listeners('error').includes(ignoreError)) body.on('error', ignoreError);\n body.destroy();\n}\n\nexport class NodeBodyResponse extends Response {\n #body: Readable | null;\n #native: Response | null = null;\n /** An adapter or a pipeline op took the body: it is used, as a read one is. */\n #taken = false;\n\n constructor(body: Readable, init?: ResponseInit) {\n super(null, init);\n if (NULL_BODY_STATUSES.has(this.status)) {\n destroyBody(body);\n this.#body = null;\n } else {\n this.#body = body;\n }\n }\n\n /** Take the Node body; this response no longer has it. */\n #take(): Readable | null {\n const body = this.#body;\n if (body) this.#taken = true;\n this.#body = null;\n return body;\n }\n\n /**\n * This response as a native one, converting the Node body once. Throws, as\n * a native Response whose body was read does, if something already took\n * the body (an adapter, a re-wrap), rather than reading as empty.\n */\n #toNative(): Response {\n if (!this.#native) {\n if (this.#taken) throw new TypeError('Body is unusable: Body has already been read');\n const body = this.#body;\n this.#body = null;\n this.#native = new Response(\n body ? (Readable.toWeb(body) as ReadableStream<Uint8Array>) : null,\n {\n status: this.status,\n statusText: this.statusText,\n headers: this.headers,\n }\n );\n }\n return this.#native;\n }\n\n get [NODE_BODY](): NodeBodyOps {\n return {\n hasBody: this.#native ? this.#native.body !== null : this.#body !== null,\n rewrap: (init) => {\n if (this.#native) return new Response(this.#native.body, init);\n const body = this.#take();\n return body ? new NodeBodyResponse(body, init) : new Response(null, init);\n },\n discard: () => {\n if (this.#native) {\n this.#native.body?.cancel().catch(() => {});\n return;\n }\n const body = this.#take();\n if (body) destroyBody(body);\n },\n through: (stream, init) => {\n const body = this.#native\n ? this.#native.body && webToNode(this.#native.body)\n : this.#take();\n return body\n ? new NodeBodyResponse(pipeThrough(body, stream), init)\n : new Response(null, init);\n },\n timed: (startTime) => {\n const init = { status: this.status, statusText: this.statusText, headers: this.headers };\n if (this.#native) {\n const native = this.#native.body;\n return new Response(\n native ? wrapResponseWithStreamTiming(native, startTime) : null,\n init\n );\n }\n const body = this.#take();\n return body ? new NodeBodyResponse(timeBody(body, startTime), init) : this;\n },\n };\n }\n\n /**\n * srvx's protocol for a response with a Node body: srvx pipes `body` into\n * `ServerResponse` with `pipeline()`. Headers as a flat `[name, value, …]`\n * list, as srvx's own `NodeResponse` returns them.\n */\n _toNodeResponse(): {\n status: number;\n statusText: string;\n headers: string[];\n body: Readable | ReadableStream<Uint8Array> | null;\n } {\n const headers: string[] = [];\n for (const [name, value] of this.headers) headers.push(name, value);\n return {\n status: this.status,\n statusText: this.statusText,\n headers,\n body: this.#native ? this.#native.body : this.#take(),\n };\n }\n\n // ─── Web API: convert once, then behave natively ─────────────────────────\n\n get body(): Response['body'] {\n return this.#toNative().body;\n }\n\n get bodyUsed(): boolean {\n return this.#native ? this.#native.bodyUsed : this.#taken;\n }\n\n /**\n * The other half of srvx's protocol: srvx/bun and srvx/deno send\n * `res._response` for anything with `_toNodeResponse` (`toNativeResponse`),\n * and their runtimes stream Web bodies natively. Converts once.\n */\n get _response(): Response {\n return this.#toNative();\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.#toNative().arrayBuffer();\n }\n\n blob(): Promise<Blob> {\n return this.#toNative().blob();\n }\n\n // Built from arrayBuffer(): its type satisfies both lib.dom's `bytes()` and\n // the Workers types', which some importers (the website) merge in.\n bytes(): Promise<Uint8Array<ArrayBuffer>> {\n return this.#toNative()\n .arrayBuffer()\n .then((buffer) => new Uint8Array(buffer));\n }\n\n formData(): Promise<FormData> {\n return this.#toNative().formData();\n }\n\n json(): Promise<unknown> {\n return this.#toNative().json();\n }\n\n text(): Promise<string> {\n return this.#toNative().text();\n }\n\n clone(): Response {\n return this.#toNative().clone();\n }\n}\n\n/** `body` piped through `stream`; an error or destroy on either end tears down both. */\nfunction pipeThrough(body: Readable, stream: Duplex): Duplex {\n stream.on('error', ignoreError);\n pipeline(body, stream, ignoreError);\n return stream;\n}\n\n/** A Web body already taken out of this response, back as a Node stream. */\nfunction webToNode(body: ReadableStream<Uint8Array>): Readable {\n return Readable.fromWeb(body as import('node:stream/web').ReadableStream<Uint8Array>);\n}\n\n/** A body that reports stream-lifecycle timing ({@link createStreamTimingRecorder}). */\nfunction timeBody(body: Readable, startTime: number): Readable {\n const timing = createStreamTimingRecorder(startTime);\n const timed = new Transform({\n transform(chunk: Uint8Array, _encoding, callback) {\n timing.chunk(chunk.byteLength);\n callback(null, chunk);\n },\n flush(callback) {\n timing.end(false);\n callback();\n },\n // Reached by the consumer leaving early (a cancellation) and by the\n // producer failing; the producer path records itself first, below, so a\n // render error is not logged as a disconnect — as the Web wrapper logs it.\n destroy(error, callback) {\n timing.end(true);\n body.destroy(error ?? undefined);\n callback(error);\n },\n });\n timed.on('error', ignoreError);\n body.on('error', (error) => {\n timing.end(false);\n timed.destroy(error);\n });\n body.pipe(timed);\n return timed;\n}\n","/**\n * Node halves of the Flight source helpers in `flight-source.ts`.\n *\n * Only loaded on Node (`flight-source.ts` imports it behind\n * `nodeStreamsPlatform`), so Workers never evaluate it.\n *\n * A Node Flight source is an object-mode `Readable` whose chunks are exactly\n * what React's `renderToPipeableStream` wrote: `Uint8Array` views for short\n * rows, and JS strings for long rows (≥ ~1365 chars) and text row bodies.\n * The Node Flight client (`createFromNodeStream`) requires every string chunk\n * in its original shape — it throws \"String chunks need to be passed in their\n * original shape\" if one is split or merged — so nothing here splits or\n * concatenates a chunk on its way to a consumer.\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\",\n * §\"Stream Tee\"\n */\n\nimport { Readable, Transform } from 'node:stream';\nimport { NodeBodyResponse } from './node-body-response.ts';\nimport { DEFAULT_MAX_BUFFER_BYTES, teeBufferExceeded } from './stream-utils.ts';\nimport { onAbortUntil } from './abort-scope.ts';\nimport { RenderTimeoutError } from './render-timeout.ts';\nimport { releaseReason } from './render-utils.ts';\n\n// `String.prototype.toWellFormed` ships in every Node timber supports\n// (engines: >=22.18) but is ES2024, past the project's ES2022 lib; this file\n// only runs on Node.\ndeclare global {\n interface String {\n toWellFormed(): string;\n }\n}\n\n/** A chunk of a Node Flight source. */\nexport type NodeFlightChunk = string | Uint8Array;\n\n/** The part of React's `PipeableStream` a Flight render hands us. */\nexport interface PipeableFlight {\n pipe<T extends NodeJS.WritableStream>(destination: T): T;\n abort(reason?: unknown): void;\n}\n\n/**\n * Every stream here carries one no-op `'error'` listener. `destroy(err)` emits\n * `'error'`, and a stream whose consumer already detached (an iterator that\n * returned, a pipeline that finished) or has not attached yet would otherwise\n * turn a cancel into an uncaught exception. Real consumers attach their own\n * listeners, which still see every error.\n */\nfunction ignoreError(): void {}\n\n/**\n * Release a Node Flight source: destroy it with `reason`, which aborts the\n * render behind it. Cancellation reasons in the pipeline are `unknown` (a Web\n * `cancel(reason)` takes anything); `destroy` takes an `Error`. Never throws\n * and never leaves an unhandled `'error'` event, whoever is listening.\n */\nexport function destroyNodeFlight(stream: Readable, reason: unknown): void {\n if (!stream.listeners('error').includes(ignoreError)) stream.on('error', ignoreError);\n const error =\n reason === undefined || reason === null\n ? undefined\n : reason instanceof Error\n ? reason\n : new Error(String(reason));\n stream.destroy(error);\n}\n\n/** When a Node Flight render is aborted, besides its consumer cancelling. */\nexport interface NodeFlightAbort {\n /** The request's signal (client disconnect). */\n signal?: AbortSignal;\n /** Abort with a `RenderTimeoutError` after this long, if still rendering. */\n timeoutMs?: number;\n}\n\n/**\n * Pipe a Flight render into an object-mode Node source.\n *\n * - Strings pass through `toWellFormed()`, as Next does\n * (`renderToNodeFlightStream`): SSR decodes the raw string while the inline\n * copy round-trips through JSON + `TextEncoder`, which turns a lone\n * surrogate into U+FFFD, so without it SSR and hydration see different\n * text. Length in UTF-16 units is unchanged, so a text row's length header\n * still holds.\n * - `renderToPipeableStream` takes no `signal`. `abort()` is called when the\n * request signal fires, when `timeoutMs` passes (design/02 §\"Always Wire\n * abort() to Both Request Signal AND Timeout\"), and when the source is\n * destroyed (a consumer cancelling), with the destroy reason — the reason a\n * Web `cancel(reason)` hands Flight. The listener and the timer are\n * released when the source closes.\n */\nexport function pipeFlightToNode(\n flight: PipeableFlight,\n { signal, timeoutMs }: NodeFlightAbort\n): Readable {\n const scope = new AbortController();\n const timer =\n timeoutMs === undefined\n ? undefined\n : setTimeout(\n () => flight.abort(new RenderTimeoutError(timeoutMs, 'Flight render')),\n timeoutMs\n );\n const stream = new Transform({\n objectMode: true,\n transform(chunk: NodeFlightChunk, _encoding, callback) {\n callback(null, typeof chunk === 'string' ? chunk.toWellFormed() : chunk);\n },\n destroy(error, callback) {\n scope.abort();\n clearTimeout(timer);\n // A no-op once Flight has finished (it ignores abort after close). A\n // release without a reason aborts with an AbortError, so the render's\n // onError does not log the abort (releaseReason, TIM-1597).\n flight.abort(releaseReason(error));\n callback(error);\n },\n });\n stream.on('error', ignoreError);\n // The listener lasts until the stream is destroyed (server/abort-scope.ts).\n onAbortUntil(signal, () => flight.abort(signal?.reason), scope.signal);\n flight.pipe(stream);\n return stream;\n}\n\n/** Bytes a chunk occupies, for the tee's divergence guard. */\nfunction chunkByteLength(chunk: NodeFlightChunk): number {\n return typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength;\n}\n\n/**\n * Tee a Node Flight source into two object-mode branches, with the contract\n * of `teeWithErrorPropagation` (`stream-utils.ts`):\n *\n * - Each branch has its own queue, so the lagging branch buffers without\n * bound until the divergence guard (`maxBufferBytes`, default 5MB, counted\n * in UTF-8 bytes) cancels both. Nothing couples the branches' backpressure:\n * the inline branch is not read until Fizz emits its first HTML chunk, and\n * Fizz needs SSR to consume Flight first, so a `pipe()` into two\n * PassThroughs would deadlock once the inline one filled.\n * - The source is read at the pace of the faster branch (paused only while\n * neither branch wants data), like a Web `tee()`.\n * - An error on the source, or a branch destroyed before it ended, destroys\n * the other branch with an error and destroys the source — which aborts the\n * render — so neither consumer hangs and both are released.\n */\nexport function teeNodeFlight(\n source: Readable,\n maxBufferBytes: number = DEFAULT_MAX_BUFFER_BYTES\n): [Readable, Readable] {\n interface Branch {\n readable: Readable;\n queue: Array<NodeFlightChunk | null>;\n /**\n * Bytes this branch holds that its consumer has not read: the queue, plus\n * chunks pushed into the readable and still in its buffer.\n */\n heldBytes: number;\n /**\n * Sizes of the chunks pushed into the readable, oldest first, until the\n * consumer reads them. In object mode `readableLength` counts buffered\n * chunks, so any beyond it at the front have been consumed.\n */\n pushedSizes: number[];\n /** `_read` was called and nothing has been pushed since. */\n wanting: boolean;\n }\n\n let tornDown = false;\n const branches: [Branch, Branch] = [createBranch(), createBranch()];\n\n function createBranch(): Branch {\n const branch: Branch = {\n readable: new Readable({\n objectMode: true,\n read() {\n settle(branch);\n branch.wanting = true;\n drain(branch);\n },\n destroy(error, callback) {\n // A branch that ended normally releases nothing; one destroyed\n // early (its consumer cancelled, or teardown) takes the rest down.\n if (!branch.readable.readableEnded) {\n teardown(error ?? new Error('RSC stream tee branch cancelled'), error);\n }\n callback(error);\n },\n }),\n queue: [],\n heldBytes: 0,\n pushedSizes: [],\n wanting: false,\n };\n branch.readable.on('error', ignoreError);\n return branch;\n }\n\n /** Stop counting the pushed chunks the consumer has read. */\n function settle(branch: Branch): void {\n while (branch.pushedSizes.length > branch.readable.readableLength) {\n branch.heldBytes -= branch.pushedSizes.shift() ?? 0;\n }\n }\n\n function drain(branch: Branch): void {\n while (branch.wanting) {\n const chunk = branch.queue.shift();\n if (chunk === undefined) break;\n if (chunk === null) {\n branch.wanting = false;\n branch.readable.push(null);\n return;\n }\n branch.pushedSizes.push(chunkByteLength(chunk));\n branch.wanting = branch.readable.push(chunk);\n }\n if (branch.wanting && source.isPaused()) source.resume();\n }\n\n /**\n * Destroy both branches and the source. `branchError` is what the branches'\n * consumers see; `sourceReason` is what Flight is aborted with — the\n * consumer's own cancel reason, which may be `undefined`, as with a Web tee.\n */\n function teardown(branchError: Error, sourceReason: Error | null | undefined): void {\n if (tornDown) return;\n tornDown = true;\n source.off('data', onData);\n for (const branch of branches) {\n branch.queue.length = 0;\n branch.heldBytes = 0;\n branch.pushedSizes.length = 0;\n if (!branch.readable.destroyed) branch.readable.destroy(branchError);\n }\n source.destroy(sourceReason ?? undefined);\n }\n\n function onData(chunk: NodeFlightChunk): void {\n const bytes = chunkByteLength(chunk);\n for (const branch of branches) {\n branch.queue.push(chunk);\n branch.heldBytes += bytes;\n drain(branch);\n }\n // What the lagging branch holds is the divergence between the two.\n for (const branch of branches) settle(branch);\n const divergence = Math.max(branches[0].heldBytes, branches[1].heldBytes);\n if (divergence > maxBufferBytes) {\n const error = teeBufferExceeded(maxBufferBytes, divergence);\n teardown(error, error);\n return;\n }\n if (!branches[0].wanting && !branches[1].wanting) source.pause();\n }\n\n const finished = finishedState(source);\n if (finished) {\n if ('error' in finished) teardown(finished.error, finished.error);\n else for (const branch of branches) branch.readable.push(null);\n return [branches[0].readable, branches[1].readable];\n }\n\n source.on('data', onData);\n source.on('end', () => {\n for (const branch of branches) {\n branch.queue.push(null);\n drain(branch);\n }\n });\n source.on('error', (error: Error) => teardown(error, error));\n source.on('close', () => {\n if (!source.readableEnded) {\n teardown(new Error('RSC stream closed before it ended'), undefined);\n }\n });\n\n return [branches[0].readable, branches[1].readable];\n}\n\n/**\n * A Node Flight source as a `Response` (`NodeBodyResponse`): its body stays a\n * Node stream all the way to the adapter, which pipes it to the socket\n * (LOCAL-1475). Nothing in the Flight path converts it to a Web stream.\n *\n * Every chunk that arrives in one tick goes out as one buffer, with string\n * chunks encoded straight into it. React writes a flush synchronously, and\n * its Node build passes each long row as its own string: a heavy payload\n * arrives as ~4x the chunks of the Web build's 4KB views, and the socket pays\n * per write. The body pauses the source while the client is slow (a payload\n * never piles up in memory), destroying it early destroys the source (which\n * aborts the render), and an error or early close on the source ends it.\n * Wired by hand rather than with `pipeline()`, which allocates an\n * AbortController and an error on every finish.\n */\nexport function nodeFlightResponse(source: Readable, init: ResponseInit): Response {\n return new NodeBodyResponse(batchFlightBytes(source), init);\n}\n\n/** Largest batch the payload body coalesces before pushing (and checking backpressure). */\nconst MAX_BATCH_BYTES = 64 * 1024;\n\nfunction batchFlightBytes(source: Readable): Readable {\n let batch: NodeFlightChunk[] = [];\n let batchBytes = 0;\n let scheduled = false;\n // Assigned once the source listeners exist; a body destroyed before then\n // (an already-finished source) has none to remove.\n let detach = (): void => {};\n\n // One allocation per batch: strings are encoded straight into it, at their\n // offset, rather than each into its own array and then copied.\n const emit = (): void => {\n scheduled = false;\n if (batch.length === 0 || bytes.destroyed) return;\n const merged = Buffer.allocUnsafe(batchBytes);\n let offset = 0;\n for (const chunk of batch) {\n if (typeof chunk === 'string') {\n offset += merged.write(chunk, offset);\n } else {\n merged.set(chunk, offset);\n offset += chunk.byteLength;\n }\n }\n batch = [];\n batchBytes = 0;\n // Backpressure: a slow client stops the render's output here instead of\n // the whole payload piling up in memory. read() resumes it.\n if (!bytes.push(merged)) source.pause();\n };\n\n const bytes = new Readable({\n read() {\n if (source.isPaused()) source.resume();\n },\n destroy(error, callback) {\n // A batch still queued is dropped, so its microtask pushes nothing.\n batch = [];\n batchBytes = 0;\n detach();\n // The client left early: release the render.\n if (!source.readableEnded) destroyNodeFlight(source, error ?? undefined);\n callback(error);\n },\n });\n bytes.on('error', ignoreError);\n\n const finished = finishedState(source);\n if (finished) {\n // A finished source emits no more events for the wiring below to see.\n if ('error' in finished) bytes.destroy(finished.error);\n else bytes.push(null);\n return bytes;\n }\n\n const onData = (chunk: NodeFlightChunk): void => {\n batch.push(chunk);\n batchBytes += chunkByteLength(chunk);\n // A flush that writes a lot in one tick goes out in capped batches, so\n // backpressure can pause the source mid-flush instead of after it.\n if (batchBytes >= MAX_BATCH_BYTES) {\n emit();\n } else if (!scheduled) {\n scheduled = true;\n queueMicrotask(emit);\n }\n };\n const onEnd = (): void => {\n emit();\n bytes.push(null);\n };\n const onError = (error: Error): void => {\n bytes.destroy(error);\n };\n const onClose = (): void => {\n if (!source.readableEnded) {\n bytes.destroy(source.errored ?? new Error('RSC stream closed before it ended'));\n }\n };\n detach = (): void => {\n source.off('data', onData);\n source.off('end', onEnd);\n source.off('error', onError);\n source.off('close', onClose);\n };\n source.on('data', onData);\n source.on('end', onEnd);\n source.on('error', onError);\n source.on('close', onClose);\n return bytes;\n}\n\n/**\n * Why `source` will never emit again, if it was destroyed or ended before a\n * consumer attached: `'end'`, `'error'` and `'close'` have already fired,\n * so a consumer that only listens would wait forever. `null` while live.\n */\nfunction finishedState(source: Readable): { ended: true } | { error: Error } | null {\n if (source.readableEnded) return { ended: true };\n if (!source.destroyed) return null;\n return { error: source.errored ?? new Error('RSC stream closed before it ended') };\n}\n\n/**\n * Settles once a chunk (or the end) can be read from `source`, without\n * consuming it: the chunk stays in the source for whatever reads it next.\n * Rejects if the source errors first.\n *\n * The `'readable'` listener is removed on settle; Node restores the stream's\n * flowing state on the next tick, so a consumer attached afterwards (a pipe,\n * a `'data'` listener) still starts it.\n */\nexport function whenNodeFlightReadable(source: Readable): Promise<void> {\n if (source.readableLength > 0) return Promise.resolve();\n const finished = finishedState(source);\n if (finished) return 'error' in finished ? Promise.reject(finished.error) : Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const settle = (error?: Error): void => {\n source.off('readable', onReadable);\n source.off('error', settle);\n source.off('close', onClose);\n if (error) reject(error);\n else resolve();\n };\n const onReadable = (): void => settle();\n const onClose = (): void => settle(source.errored ?? undefined);\n source.on('readable', onReadable);\n source.on('error', settle);\n source.on('close', onClose);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAE5D,SAASA,gBAAoB,CAAC;;AAG9B,SAAS,YAAY,MAAsB;CACzC,IAAI,CAAC,KAAK,UAAU,OAAO,CAAC,CAAC,SAASA,aAAW,GAAG,KAAK,GAAG,SAASA,aAAW;CAChF,KAAK,QAAQ;AACf;AAEA,IAAa,mBAAb,MAAa,yBAAyB,SA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SAAgB,uBAAuB,QAAiC;CACtE,IAAI,OAAO,iBAAiB,GAAG,OAAO,QAAQ,QAAQ;CACtD,MAAM,WAAW,cAAc,MAAM;CACrC,IAAI,UAAU,OAAO,WAAW,WAAW,QAAQ,OAAO,SAAS,KAAK,IAAI,QAAQ,QAAQ;CAC5F,OAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,UAAU,UAAwB;GACtC,OAAO,IAAI,YAAY,UAAU;GACjC,OAAO,IAAI,SAAS,MAAM;GAC1B,OAAO,IAAI,SAAS,OAAO;GAC3B,IAAI,OAAO,OAAO,KAAK;QAClB,QAAQ;EACf;EACA,MAAM,mBAAyB,OAAO;EACtC,MAAM,gBAAsB,OAAO,OAAO,WAAW,KAAA,CAAS;EAC9D,OAAO,GAAG,YAAY,UAAU;EAChC,OAAO,GAAG,SAAS,MAAM;EACzB,OAAO,GAAG,SAAS,OAAO;CAC5B,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"flight-source-node-BO_xD9jC.js","names":["ignoreError"],"sources":["../../src/server/node-body-response.ts","../../src/server/flight-source-node.ts"],"sourcesContent":["/**\n * `NodeBodyResponse` — a `Response` whose body is a Node `Readable`, so a\n * response built on Node streams reaches the socket without a Web Streams\n * round trip (LOCAL-1475). Node only: loaded behind `nodeStreamsPlatform`.\n *\n * The status and headers are an ordinary `Response`'s. The body stays a Node\n * stream until one of two things takes it:\n *\n * - **An adapter**, through `_toNodeResponse()` — srvx's protocol (nitro and\n * the dev server send with srvx; nitro-preview's sender speaks it too). The\n * stream is piped straight into `ServerResponse`.\n * - **Web-API code** reading `body`, `text()`, `arrayBuffer()`, `clone()`, …\n * The response then converts its body once, with `Readable.toWeb`, and\n * behaves as a native `Response` from then on. Correct anywhere, so code\n * that does not know about Node bodies keeps working; pipeline code on the\n * hot path goes through `node-response.ts` instead, which never converts.\n *\n * Pattern from srvx's `NodeResponse` (`FastResponse`).\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport { Readable, Transform, pipeline, type Duplex } from 'node:stream';\nimport { NODE_BODY, type NodeBodyOps } from './node-response.ts';\nimport { createStreamTimingRecorder, wrapResponseWithStreamTiming } from './stream-utils.ts';\n\n/** Statuses whose responses carry no body (Fetch \"null body status\"). */\nconst NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);\n\nfunction ignoreError(): void {}\n\n/** Destroy a body nothing will read, without an unhandled `'error'`. */\nfunction destroyBody(body: Readable): void {\n if (!body.listeners('error').includes(ignoreError)) body.on('error', ignoreError);\n body.destroy();\n}\n\nexport class NodeBodyResponse extends Response {\n #body: Readable | null;\n #native: Response | null = null;\n /** An adapter or a pipeline op took the body: it is used, as a read one is. */\n #taken = false;\n\n constructor(body: Readable, init?: ResponseInit) {\n super(null, init);\n if (NULL_BODY_STATUSES.has(this.status)) {\n destroyBody(body);\n this.#body = null;\n } else {\n this.#body = body;\n }\n }\n\n /** Take the Node body; this response no longer has it. */\n #take(): Readable | null {\n const body = this.#body;\n if (body) this.#taken = true;\n this.#body = null;\n return body;\n }\n\n /**\n * This response as a native one, converting the Node body once. Throws, as\n * a native Response whose body was read does, if something already took\n * the body (an adapter, a re-wrap), rather than reading as empty.\n */\n #toNative(): Response {\n if (!this.#native) {\n if (this.#taken) throw new TypeError('Body is unusable: Body has already been read');\n const body = this.#body;\n this.#body = null;\n this.#native = new Response(\n body ? (Readable.toWeb(body) as ReadableStream<Uint8Array>) : null,\n {\n status: this.status,\n statusText: this.statusText,\n headers: this.headers,\n }\n );\n }\n return this.#native;\n }\n\n get [NODE_BODY](): NodeBodyOps {\n return {\n hasBody: this.#native ? this.#native.body !== null : this.#body !== null,\n rewrap: (init) => {\n if (this.#native) return new Response(this.#native.body, init);\n const body = this.#take();\n return body ? new NodeBodyResponse(body, init) : new Response(null, init);\n },\n discard: () => {\n if (this.#native) {\n this.#native.body?.cancel().catch(() => {});\n return;\n }\n const body = this.#take();\n if (body) destroyBody(body);\n },\n through: (stream, init) => {\n const body = this.#native\n ? this.#native.body && webToNode(this.#native.body)\n : this.#take();\n return body\n ? new NodeBodyResponse(pipeThrough(body, stream), init)\n : new Response(null, init);\n },\n timed: (startTime) => {\n const init = { status: this.status, statusText: this.statusText, headers: this.headers };\n if (this.#native) {\n const native = this.#native.body;\n return new Response(\n native ? wrapResponseWithStreamTiming(native, startTime) : null,\n init\n );\n }\n const body = this.#take();\n return body ? new NodeBodyResponse(timeBody(body, startTime), init) : this;\n },\n };\n }\n\n /**\n * srvx's protocol for a response with a Node body: srvx pipes `body` into\n * `ServerResponse` with `pipeline()`. Headers as a flat `[name, value, …]`\n * list, as srvx's own `NodeResponse` returns them.\n */\n _toNodeResponse(): {\n status: number;\n statusText: string;\n headers: string[];\n body: Readable | ReadableStream<Uint8Array> | null;\n } {\n const headers: string[] = [];\n for (const [name, value] of this.headers) headers.push(name, value);\n return {\n status: this.status,\n statusText: this.statusText,\n headers,\n body: this.#native ? this.#native.body : this.#take(),\n };\n }\n\n // ─── Web API: convert once, then behave natively ─────────────────────────\n\n get body(): Response['body'] {\n return this.#toNative().body;\n }\n\n get bodyUsed(): boolean {\n return this.#native ? this.#native.bodyUsed : this.#taken;\n }\n\n /**\n * The other half of srvx's protocol: srvx/bun and srvx/deno send\n * `res._response` for anything with `_toNodeResponse` (`toNativeResponse`),\n * and their runtimes stream Web bodies natively. Converts once.\n */\n get _response(): Response {\n return this.#toNative();\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.#toNative().arrayBuffer();\n }\n\n blob(): Promise<Blob> {\n return this.#toNative().blob();\n }\n\n // Built from arrayBuffer(): its type satisfies both lib.dom's `bytes()` and\n // the Workers types', which some importers (the website) merge in.\n bytes(): Promise<Uint8Array<ArrayBuffer>> {\n return this.#toNative()\n .arrayBuffer()\n .then((buffer) => new Uint8Array(buffer));\n }\n\n formData(): Promise<FormData> {\n return this.#toNative().formData();\n }\n\n json(): Promise<unknown> {\n return this.#toNative().json();\n }\n\n text(): Promise<string> {\n return this.#toNative().text();\n }\n\n clone(): Response {\n return this.#toNative().clone();\n }\n}\n\n/** `body` piped through `stream`; an error or destroy on either end tears down both. */\nfunction pipeThrough(body: Readable, stream: Duplex): Duplex {\n stream.on('error', ignoreError);\n pipeline(body, stream, ignoreError);\n return stream;\n}\n\n/** A Web body already taken out of this response, back as a Node stream. */\nfunction webToNode(body: ReadableStream<Uint8Array>): Readable {\n return Readable.fromWeb(body as import('node:stream/web').ReadableStream<Uint8Array>);\n}\n\n/** A body that reports stream-lifecycle timing ({@link createStreamTimingRecorder}). */\nfunction timeBody(body: Readable, startTime: number): Readable {\n const timing = createStreamTimingRecorder(startTime);\n const timed = new Transform({\n transform(chunk: Uint8Array, _encoding, callback) {\n timing.chunk(chunk.byteLength);\n callback(null, chunk);\n },\n flush(callback) {\n timing.end(false);\n callback();\n },\n // Reached by the consumer leaving early (a cancellation) and by the\n // producer failing; the producer path records itself first, below, so a\n // render error is not logged as a disconnect — as the Web wrapper logs it.\n destroy(error, callback) {\n timing.end(true);\n body.destroy(error ?? undefined);\n callback(error);\n },\n });\n timed.on('error', ignoreError);\n body.on('error', (error) => {\n timing.end(false);\n timed.destroy(error);\n });\n body.pipe(timed);\n return timed;\n}\n","/**\n * Node halves of the Flight source helpers in `flight-source.ts`.\n *\n * Only loaded on Node (`flight-source.ts` imports it behind\n * `nodeStreamsPlatform`), so Workers never evaluate it.\n *\n * A Node Flight source is an object-mode `Readable` whose chunks are exactly\n * what React's `renderToPipeableStream` wrote: `Uint8Array` views for short\n * rows, and JS strings for long rows (≥ ~1365 chars) and text row bodies.\n * The Node Flight client (`createFromNodeStream`) requires every string chunk\n * in its original shape — it throws \"String chunks need to be passed in their\n * original shape\" if one is split or merged — so nothing here splits or\n * concatenates a chunk on its way to a consumer.\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\",\n * §\"Stream Tee\"\n */\n\nimport { Readable, Transform } from 'node:stream';\nimport { NodeBodyResponse } from './node-body-response.ts';\nimport { DEFAULT_MAX_BUFFER_BYTES, teeBufferExceeded } from './stream-utils.ts';\nimport { onAbortUntil } from './abort-scope.ts';\nimport { RenderTimeoutError } from './render-timeout.ts';\nimport { releaseReason } from './render-utils.ts';\n\n// `String.prototype.toWellFormed` ships in every Node timber supports\n// (engines: >=22.18) but is ES2024, past the project's ES2022 lib; this file\n// only runs on Node.\ndeclare global {\n interface String {\n toWellFormed(): string;\n }\n}\n\n/** A chunk of a Node Flight source. */\nexport type NodeFlightChunk = string | Uint8Array;\n\n/** The part of React's `PipeableStream` a Flight render hands us. */\nexport interface PipeableFlight {\n pipe<T extends NodeJS.WritableStream>(destination: T): T;\n abort(reason?: unknown): void;\n}\n\n/**\n * Every stream here carries one no-op `'error'` listener. `destroy(err)` emits\n * `'error'`, and a stream whose consumer already detached (an iterator that\n * returned, a pipeline that finished) or has not attached yet would otherwise\n * turn a cancel into an uncaught exception. Real consumers attach their own\n * listeners, which still see every error.\n */\nfunction ignoreError(): void {}\n\n/**\n * Release a Node Flight source: destroy it with `reason`, which aborts the\n * render behind it. Cancellation reasons in the pipeline are `unknown` (a Web\n * `cancel(reason)` takes anything); `destroy` takes an `Error`. Never throws\n * and never leaves an unhandled `'error'` event, whoever is listening.\n */\nexport function destroyNodeFlight(stream: Readable, reason: unknown): void {\n if (!stream.listeners('error').includes(ignoreError)) stream.on('error', ignoreError);\n const error =\n reason === undefined || reason === null\n ? undefined\n : reason instanceof Error\n ? reason\n : new Error(String(reason));\n stream.destroy(error);\n}\n\n/** When a Node Flight render is aborted, besides its consumer cancelling. */\nexport interface NodeFlightAbort {\n /** The request's signal (client disconnect). */\n signal?: AbortSignal;\n /** Abort with a `RenderTimeoutError` after this long, if still rendering. */\n timeoutMs?: number;\n}\n\n/**\n * Pipe a Flight render into an object-mode Node source.\n *\n * - Strings pass through `toWellFormed()`, as Next does\n * (`renderToNodeFlightStream`): SSR decodes the raw string while the inline\n * copy round-trips through JSON + `TextEncoder`, which turns a lone\n * surrogate into U+FFFD, so without it SSR and hydration see different\n * text. Length in UTF-16 units is unchanged, so a text row's length header\n * still holds.\n * - `renderToPipeableStream` takes no `signal`. `abort()` is called when the\n * request signal fires, when `timeoutMs` passes (design/02 §\"Always Wire\n * abort() to Both Request Signal AND Timeout\"), and when the source is\n * destroyed (a consumer cancelling), with the destroy reason — the reason a\n * Web `cancel(reason)` hands Flight. The listener and the timer are\n * released when the source closes.\n */\nexport function pipeFlightToNode(\n flight: PipeableFlight,\n { signal, timeoutMs }: NodeFlightAbort\n): Readable {\n const scope = new AbortController();\n const timer =\n timeoutMs === undefined\n ? undefined\n : setTimeout(\n () => flight.abort(new RenderTimeoutError(timeoutMs, 'Flight render')),\n timeoutMs\n );\n const stream = new Transform({\n objectMode: true,\n transform(chunk: NodeFlightChunk, _encoding, callback) {\n callback(null, typeof chunk === 'string' ? chunk.toWellFormed() : chunk);\n },\n destroy(error, callback) {\n scope.abort();\n clearTimeout(timer);\n // A no-op once Flight has finished (it ignores abort after close). A\n // release without a reason aborts with an AbortError, so the render's\n // onError does not log the abort (releaseReason, TIM-1597).\n flight.abort(releaseReason(error));\n callback(error);\n },\n });\n stream.on('error', ignoreError);\n // The listener lasts until the stream is destroyed (server/abort-scope.ts).\n onAbortUntil(signal, () => flight.abort(signal?.reason), scope.signal);\n flight.pipe(stream);\n return stream;\n}\n\n/** Bytes a chunk occupies, for the tee's divergence guard. */\nfunction chunkByteLength(chunk: NodeFlightChunk): number {\n return typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength;\n}\n\n/**\n * Tee a Node Flight source into two object-mode branches, with the contract\n * of `teeWithErrorPropagation` (`stream-utils.ts`):\n *\n * - Each branch has its own queue, so the lagging branch buffers without\n * bound until the divergence guard (`maxBufferBytes`, default 5MB, counted\n * in UTF-8 bytes) cancels both. Nothing couples the branches' backpressure:\n * the inline branch is not read until Fizz emits its first HTML chunk, and\n * Fizz needs SSR to consume Flight first, so a `pipe()` into two\n * PassThroughs would deadlock once the inline one filled.\n * - The source is read at the pace of the faster branch (paused only while\n * neither branch wants data), like a Web `tee()`.\n * - An error on the source, or a branch destroyed before it ended, destroys\n * the other branch with an error and destroys the source — which aborts the\n * render — so neither consumer hangs and both are released.\n */\nexport function teeNodeFlight(\n source: Readable,\n maxBufferBytes: number = DEFAULT_MAX_BUFFER_BYTES\n): [Readable, Readable] {\n interface Branch {\n readable: Readable;\n queue: Array<NodeFlightChunk | null>;\n /**\n * Bytes this branch holds that its consumer has not read: the queue, plus\n * chunks pushed into the readable and still in its buffer.\n */\n heldBytes: number;\n /**\n * Sizes of the chunks pushed into the readable, oldest first, until the\n * consumer reads them. In object mode `readableLength` counts buffered\n * chunks, so any beyond it at the front have been consumed.\n */\n pushedSizes: number[];\n /** `_read` was called and nothing has been pushed since. */\n wanting: boolean;\n }\n\n let tornDown = false;\n const branches: [Branch, Branch] = [createBranch(), createBranch()];\n\n function createBranch(): Branch {\n const branch: Branch = {\n readable: new Readable({\n objectMode: true,\n read() {\n settle(branch);\n branch.wanting = true;\n drain(branch);\n },\n destroy(error, callback) {\n // A branch that ended normally releases nothing; one destroyed\n // early (its consumer cancelled, or teardown) takes the rest down.\n if (!branch.readable.readableEnded) {\n teardown(error ?? new Error('RSC stream tee branch cancelled'), error);\n }\n callback(error);\n },\n }),\n queue: [],\n heldBytes: 0,\n pushedSizes: [],\n wanting: false,\n };\n branch.readable.on('error', ignoreError);\n return branch;\n }\n\n /** Stop counting the pushed chunks the consumer has read. */\n function settle(branch: Branch): void {\n while (branch.pushedSizes.length > branch.readable.readableLength) {\n branch.heldBytes -= branch.pushedSizes.shift() ?? 0;\n }\n }\n\n function drain(branch: Branch): void {\n while (branch.wanting) {\n const chunk = branch.queue.shift();\n if (chunk === undefined) break;\n if (chunk === null) {\n branch.wanting = false;\n branch.readable.push(null);\n return;\n }\n branch.pushedSizes.push(chunkByteLength(chunk));\n branch.wanting = branch.readable.push(chunk);\n }\n if (branch.wanting && source.isPaused()) source.resume();\n }\n\n /**\n * Destroy both branches and the source. `branchError` is what the branches'\n * consumers see; `sourceReason` is what Flight is aborted with — the\n * consumer's own cancel reason, which may be `undefined`, as with a Web tee.\n */\n function teardown(branchError: Error, sourceReason: Error | null | undefined): void {\n if (tornDown) return;\n tornDown = true;\n source.off('data', onData);\n for (const branch of branches) {\n branch.queue.length = 0;\n branch.heldBytes = 0;\n branch.pushedSizes.length = 0;\n if (!branch.readable.destroyed) branch.readable.destroy(branchError);\n }\n source.destroy(sourceReason ?? undefined);\n }\n\n function onData(chunk: NodeFlightChunk): void {\n const bytes = chunkByteLength(chunk);\n for (const branch of branches) {\n branch.queue.push(chunk);\n branch.heldBytes += bytes;\n drain(branch);\n }\n // What the lagging branch holds is the divergence between the two.\n for (const branch of branches) settle(branch);\n const divergence = Math.max(branches[0].heldBytes, branches[1].heldBytes);\n if (divergence > maxBufferBytes) {\n const error = teeBufferExceeded(maxBufferBytes, divergence);\n teardown(error, error);\n return;\n }\n if (!branches[0].wanting && !branches[1].wanting) source.pause();\n }\n\n const finished = finishedState(source);\n if (finished) {\n if ('error' in finished) teardown(finished.error, finished.error);\n else for (const branch of branches) branch.readable.push(null);\n return [branches[0].readable, branches[1].readable];\n }\n\n source.on('data', onData);\n source.on('end', () => {\n for (const branch of branches) {\n branch.queue.push(null);\n drain(branch);\n }\n });\n source.on('error', (error: Error) => teardown(error, error));\n source.on('close', () => {\n if (!source.readableEnded) {\n teardown(new Error('RSC stream closed before it ended'), undefined);\n }\n });\n\n return [branches[0].readable, branches[1].readable];\n}\n\n/**\n * A Node Flight source as a `Response` (`NodeBodyResponse`): its body stays a\n * Node stream all the way to the adapter, which pipes it to the socket\n * (LOCAL-1475). Nothing in the Flight path converts it to a Web stream.\n *\n * Every chunk that arrives in one tick goes out as one buffer, with string\n * chunks encoded straight into it. React writes a flush synchronously, and\n * its Node build passes each long row as its own string: a heavy payload\n * arrives as ~4x the chunks of the Web build's 4KB views, and the socket pays\n * per write. The body pauses the source while the client is slow (a payload\n * never piles up in memory), destroying it early destroys the source (which\n * aborts the render), and an error or early close on the source ends it.\n * Wired by hand rather than with `pipeline()`, which allocates an\n * AbortController and an error on every finish.\n */\nexport function nodeFlightResponse(source: Readable, init: ResponseInit): Response {\n return new NodeBodyResponse(batchFlightBytes(source), init);\n}\n\n/** Largest batch the payload body coalesces before pushing (and checking backpressure). */\nconst MAX_BATCH_BYTES = 64 * 1024;\n\nfunction batchFlightBytes(source: Readable): Readable {\n let batch: NodeFlightChunk[] = [];\n let batchBytes = 0;\n let scheduled = false;\n // Assigned once the source listeners exist; a body destroyed before then\n // (an already-finished source) has none to remove.\n let detach = (): void => {};\n\n // One allocation per batch: strings are encoded straight into it, at their\n // offset, rather than each into its own array and then copied.\n const emit = (): void => {\n scheduled = false;\n if (batch.length === 0 || bytes.destroyed) return;\n const merged = Buffer.allocUnsafe(batchBytes);\n let offset = 0;\n for (const chunk of batch) {\n if (typeof chunk === 'string') {\n offset += merged.write(chunk, offset);\n } else {\n merged.set(chunk, offset);\n offset += chunk.byteLength;\n }\n }\n batch = [];\n batchBytes = 0;\n // Backpressure: a slow client stops the render's output here instead of\n // the whole payload piling up in memory. read() resumes it.\n if (!bytes.push(merged)) source.pause();\n };\n\n const bytes = new Readable({\n read() {\n if (source.isPaused()) source.resume();\n },\n destroy(error, callback) {\n // A batch still queued is dropped, so its microtask pushes nothing.\n batch = [];\n batchBytes = 0;\n detach();\n // The client left early: release the render.\n if (!source.readableEnded) destroyNodeFlight(source, error ?? undefined);\n callback(error);\n },\n });\n bytes.on('error', ignoreError);\n\n const finished = finishedState(source);\n if (finished) {\n // A finished source emits no more events for the wiring below to see.\n if ('error' in finished) bytes.destroy(finished.error);\n else bytes.push(null);\n return bytes;\n }\n\n const onData = (chunk: NodeFlightChunk): void => {\n batch.push(chunk);\n batchBytes += chunkByteLength(chunk);\n // A flush that writes a lot in one tick goes out in capped batches, so\n // backpressure can pause the source mid-flush instead of after it.\n if (batchBytes >= MAX_BATCH_BYTES) {\n emit();\n } else if (!scheduled) {\n scheduled = true;\n queueMicrotask(emit);\n }\n };\n const onEnd = (): void => {\n emit();\n bytes.push(null);\n };\n const onError = (error: Error): void => {\n bytes.destroy(error);\n };\n const onClose = (): void => {\n if (!source.readableEnded) {\n bytes.destroy(source.errored ?? new Error('RSC stream closed before it ended'));\n }\n };\n detach = (): void => {\n source.off('data', onData);\n source.off('end', onEnd);\n source.off('error', onError);\n source.off('close', onClose);\n };\n source.on('data', onData);\n source.on('end', onEnd);\n source.on('error', onError);\n source.on('close', onClose);\n return bytes;\n}\n\n/**\n * Why `source` will never emit again, if it was destroyed or ended before a\n * consumer attached: `'end'`, `'error'` and `'close'` have already fired,\n * so a consumer that only listens would wait forever. `null` while live.\n */\nfunction finishedState(source: Readable): { ended: true } | { error: Error } | null {\n if (source.readableEnded) return { ended: true };\n if (!source.destroyed) return null;\n return { error: source.errored ?? new Error('RSC stream closed before it ended') };\n}\n\n/**\n * Settles once a chunk (or the end) can be read from `source`, without\n * consuming it: the chunk stays in the source for whatever reads it next.\n * Rejects if the source errors first.\n *\n * The `'readable'` listener is removed on settle; Node restores the stream's\n * flowing state on the next tick, so a consumer attached afterwards (a pipe,\n * a `'data'` listener) still starts it.\n */\nexport function whenNodeFlightReadable(source: Readable): Promise<void> {\n if (source.readableLength > 0) return Promise.resolve();\n const finished = finishedState(source);\n if (finished) return 'error' in finished ? Promise.reject(finished.error) : Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const settle = (error?: Error): void => {\n source.off('readable', onReadable);\n source.off('error', settle);\n source.off('close', onClose);\n if (error) reject(error);\n else resolve();\n };\n const onReadable = (): void => settle();\n const onClose = (): void => settle(source.errored ?? undefined);\n source.on('readable', onReadable);\n source.on('error', settle);\n source.on('close', onClose);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAE5D,SAASA,gBAAoB,CAAC;;AAG9B,SAAS,YAAY,MAAsB;CACz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AO,EAAE,OAAO,KAAK;CAC/C,IAAI,CAAC,OAAO,WAAW,OAAO;CAC9B,OAAO,EAAE,OAAO,OAAO,2BAAW,IAAI,MAAM,mCAAmC,EAAE;AACnF;;;;;;;;;;AAWA,SAAgB,uBAAuB,QAAiC;CACtE,IAAI,OAAO,iBAAiB,GAAG,OAAO,QAAQ,QAAQ;CACtD,MAAM,WAAW,cAAc,MAAM;CACrC,IAAI,UAAU,OAAO,WAAW,WAAW,QAAQ,OAAO,SAAS,KAAK,IAAI,QAAQ,QAAQ;CAC5F,OAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,UAAU,UAAwB;GACtC,OAAO,IAAI,YAAY,UAAU;GACjC,OAAO,IAAI,SAAS,MAAM;GAC1B,OAAO,IAAI,SAAS,OAAO;GAC3B,IAAI,OAAO,OAAO,KAAK;QAClB,QAAQ;EACf;EACA,MAAM,mBAAyB,OAAO;EACtC,MAAM,gBAAsB,OAAO,OAAO,WAAW,KAAA,CAAS;EAC9D,OAAO,GAAG,YAAY,UAAU;EAChC,OAAO,GAAG,SAAS,MAAM;EACzB,OAAO,GAAG,SAAS,OAAO;CAC5B,CAAC;AACH"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as classifyUrlSegment } from "./segment-classify-Ho8jXWeC.js";
|
|
2
|
-
import { i as validateNavigationHref } from "./href-validation-DNg-zV7u.js";
|
|
3
2
|
import { t as getSchemaCodec } from "./codec-registry-C8hOGmZo.js";
|
|
3
|
+
import { i as validateNavigationHref } from "./href-validation-DNg-zV7u.js";
|
|
4
4
|
// src/shared/href.ts
|
|
5
5
|
/**
|
|
6
6
|
* Route-pattern interpolation and query serialization — the runtime behind
|
|
@@ -161,4 +161,4 @@ function buildHref(pattern, segmentParams, searchParams) {
|
|
|
161
161
|
}
|
|
162
162
|
export { interpolateParams as n, resolveHref as r, buildHref as t };
|
|
163
163
|
|
|
164
|
-
//# sourceMappingURL=href-
|
|
164
|
+
//# sourceMappingURL=href-8l5VD23D.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"href-BtspoNc9.js","names":[],"sources":["../../src/shared/href.ts"],"sourcesContent":["/**\n * Route-pattern interpolation and query serialization — the runtime behind\n * `<Link segmentParams searchParams>` and `href()` from `@timber-js/app/routes`.\n *\n * Directive-free and isomorphic: no `'use client'`, no React, no ALS. It\n * lived in `client/link.tsx` until TIM-1621, where the `'use client'`\n * directive turned every import from a server component, middleware or\n * action into a client-reference stub — so nothing on the server could\n * build a URL with it.\n *\n * Segment values serialize through the app/schema.ts codecs registered in\n * `params/codec-registry.ts`. Every entry (RSC, SSR, browser) registers\n * them, so a URL built here is the same in every environment.\n *\n * Design docs: design/09-typescript.md §\"Typed Routes\",\n * design/41-global-params.md §\"Link Component\".\n */\n\nimport { classifyUrlSegment, type UrlSegment } from '../routing/segment-classify.ts';\nimport { getSchemaCodec } from '../params/codec-registry.ts';\nimport { validateNavigationHref } from './href-validation.ts';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ParamValue = string | number | string[] | { toString(): string; [key: string]: any };\n\n/**\n * A query, in one of two shapes discriminated by `typeof === 'string'`:\n *\n * 1. Codec-aware (preferred) — the string `definition.buildSearchParams()`\n * returns. It applies each codec, honours `withUrlKey` aliases, and omits\n * values equal to their default. Passed through untouched.\n *\n * 2. Plain record (escape hatch) — every value is String()-coerced, arrays\n * repeat their key, null/undefined are skipped. No codecs, no aliases, so\n * it must not carry keys a definition owns: `{ search: 'x' }` emits\n * `?search=x` where the definition would emit `?q=x`.\n *\n * Why a STRING and not a URLSearchParams: a Link is routinely rendered by a\n * Server Component, so this value crosses the RSC Flight boundary before the\n * client Link runs. `URLSearchParams` is iterable, and React serializes any\n * iterable as an array — so the prop arrived as `[['pg','2'], …]`, fell into\n * the plain-object branch, and rendered `?0=pg&0=2`. Strings survive Flight\n * unchanged. (Codex P1 on PR #1021; reproduced against a live dev server.)\n *\n * See design/23-search-params.md §\"Link Integration\".\n */\nexport type SearchParamsArg = string | Record<string, unknown>;\n\n/**\n * Parse a route pattern's path portion into classified segments.\n * Uses the shared character-based classifier.\n */\nexport function parseSegments(pattern: string): UrlSegment[] {\n return pattern.split('/').filter(Boolean).map(classifyUrlSegment);\n}\n\n/**\n * Encode a codec's path-shaped output (it may contain '/') segment by segment.\n */\nfunction encodePath(serialized: string): string {\n return serialized.split('/').map(encodeURIComponent).join('/');\n}\n\n/**\n * Resolve a single classified segment into its string representation.\n * Returns null for optional catch-all with no value (filtered out before join).\n *\n * When schema codecs are registered (from virtual:timber-schema), uses\n * codec.serialize() for URL construction instead of plain String().\n */\nfunction resolveSegment(\n seg: UrlSegment,\n params: Record<string, ParamValue>,\n pattern: string\n): string | null {\n switch (seg.kind) {\n case 'static':\n return seg.value;\n\n case 'optional-catch-all': {\n const value = params[seg.name];\n if (value === undefined || (Array.isArray(value) && value.length === 0)) {\n return null;\n }\n const codec = getSchemaCodec(`[[...${seg.name}]]`);\n if (codec) {\n const serialized = codec.serialize(value);\n return serialized ? encodePath(serialized) : null;\n }\n const segments = Array.isArray(value) ? value : [value];\n return segments.map(encodeURIComponent).join('/');\n }\n\n case 'catch-all': {\n const value = params[seg.name];\n if (value === undefined) {\n throw new Error(\n `Missing required catch-all segment param \"${seg.name}\" for pattern \"${pattern}\".`\n );\n }\n const codec = getSchemaCodec(`[...${seg.name}]`);\n if (codec) {\n const serialized = codec.serialize(value);\n if (!serialized) {\n throw new Error(\n `Catch-all segment param \"${seg.name}\" codec returned null for pattern \"${pattern}\".`\n );\n }\n return encodePath(serialized);\n }\n const segments = Array.isArray(value) ? value : [value];\n if (segments.length === 0) {\n throw new Error(\n `Catch-all segment param \"${seg.name}\" must have at least one segment for pattern \"${pattern}\".`\n );\n }\n return segments.map(encodeURIComponent).join('/');\n }\n\n case 'dynamic': {\n const value = params[seg.name];\n if (value === undefined) {\n throw new Error(`Missing required segment param \"${seg.name}\" for pattern \"${pattern}\".`);\n }\n if (Array.isArray(value)) {\n throw new Error(\n `Segment param \"${seg.name}\" expected a string but received an array for pattern \"${pattern}\".`\n );\n }\n const codec = getSchemaCodec(`[${seg.name}]`);\n const str = codec ? (codec.serialize(value) ?? String(value)) : String(value);\n return (seg.prefix ?? '') + encodeURIComponent(str) + (seg.suffix ?? '');\n }\n }\n}\n\n/**\n * Split a URL pattern into the path portion and any trailing ?query/#hash suffix.\n * Uses URL parsing for correctness rather than manual index arithmetic.\n */\nfunction splitPatternSuffix(pattern: string): [path: string, suffix: string] {\n if (!pattern.includes('?') && !pattern.includes('#')) {\n return [pattern, ''];\n }\n const url = new URL(pattern, 'http://x');\n const suffix = url.search + url.hash;\n const path = pattern.slice(0, pattern.length - suffix.length);\n return [path, suffix];\n}\n\n/**\n * Interpolate dynamic segments in a route pattern with actual values.\n * e.g. interpolateParams(\"/products/[id]\", { id: \"123\" }) → \"/products/123\"\n *\n * Supports:\n * - [param] → single segment (with optional static prefix/suffix)\n * - [...param] → catch-all (joined with /)\n * - [[...param]] → optional catch-all (omitted if undefined/empty)\n *\n * Every value is percent-encoded per segment; catch-all elements are encoded\n * individually, so a value can never introduce a path separator of its own.\n */\nexport function interpolateParams(pattern: string, params: Record<string, ParamValue>): string {\n const [pathPart, suffix] = splitPatternSuffix(pattern);\n\n const resolved = parseSegments(pathPart)\n .map((seg) => resolveSegment(seg, params, pattern))\n .filter((s): s is string => s !== null);\n return ('/' + resolved.join('/') || '/') + suffix;\n}\n\n/**\n * Tolerate a leading '?'. `buildSearchParams()` never emits one, but callers\n * hand-rolling a query string reasonably might, and silently producing\n * `?%3Fa=b` for it would be a worse failure than accepting both.\n */\nfunction stripLeadingQuestionMark(qs: string): string {\n return qs.startsWith('?') ? qs.slice(1) : qs;\n}\n\n/**\n * Escape-hatch serialization for a plain object: String()-coerce every\n * value, append arrays as repeated keys, skip null/undefined.\n *\n * Deliberately codec-free and alias-free — see `SearchParamsArg`.\n */\nfunction coerceToQueryString(values: Record<string, unknown>): string {\n const usp = new URLSearchParams();\n for (const [key, val] of Object.entries(values)) {\n if (val === undefined || val === null) continue;\n if (Array.isArray(val)) {\n for (const item of val) usp.append(key, String(item));\n } else {\n usp.set(key, String(val));\n }\n }\n return usp.toString();\n}\n\n/**\n * Resolve an href from a pattern, its segment params and a query.\n *\n * - `params` given → the href is interpolated as a pattern\n * - `searchParams` given → serialized and appended (an empty query appends\n * nothing, not a bare `?`)\n * - a query in both `href` and `searchParams` throws: they are exclusive\n *\n * Does not validate the result; callers that hand it to a navigation sink\n * run `validateNavigationHref` on it.\n */\nexport function resolveHref(\n href: string,\n params?: Record<string, ParamValue>,\n searchParams?: SearchParamsArg\n): string {\n const resolvedPath = params ? interpolateParams(href, params) : href;\n if (!searchParams) return resolvedPath;\n\n if (resolvedPath.includes('?')) {\n throw new Error(\n `Received both searchParams and a query string in href \"${resolvedPath}\". ` +\n 'These are mutually exclusive — use one or the other.'\n );\n }\n\n // `typeof` is the only discriminator that survives the RSC Flight\n // boundary — see `SearchParamsArg`.\n const qs =\n typeof searchParams === 'string'\n ? stripLeadingQuestionMark(searchParams)\n : coerceToQueryString(searchParams);\n\n return qs ? `${resolvedPath}?${qs}` : resolvedPath;\n}\n\n/**\n * The runtime of `href()` (@timber-js/app/routes), untyped: the typed\n * surface lives in `routes/href.ts` and only narrows what may be passed.\n *\n * A pattern with no dynamic segment is already its URL. One with any —\n * including a lone optional catch-all called with no params — is\n * interpolated, or `/docs/[[...path]]` would come back verbatim. The query\n * is appended exactly as `<Link searchParams>` appends it, and the result is\n * validated like every navigation sink: segment values that would make a\n * protocol-relative URL (`/[...slug]` with `['', 'evil.com']` →\n * `//evil.com`) throw instead of returning an open redirect.\n */\nexport function buildHref(\n pattern: string,\n segmentParams?: Record<string, ParamValue>,\n searchParams?: SearchParamsArg\n): string {\n const dynamic = parseSegments(pattern).some((seg) => seg.kind !== 'static');\n const result = resolveHref(pattern, dynamic ? (segmentParams ?? {}) : undefined, searchParams);\n validateNavigationHref(result);\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;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gBAAgB;CAChC,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,MAAM,GAAG;EAC/C,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAAM;EACvC,IAAI,MAAM,QAAQ,GAAG,GACnB,KAAK,MAAM,QAAQ,KAAK,IAAI,OAAO,KAAK,OAAO,IAAI,CAAC;OAEpD,IAAI,IAAI,KAAK,OAAO,GAAG,CAAC;CAE5B;CACA,OAAO,IAAI,SAAS;AACtB;;;;;;;;;;;;AAaA,SAAgB,YACd,MACA,QACA,cACQ;CACR,MAAM,eAAe,SAAS,kBAAkB,MAAM,MAAM,IAAI;CAChE,IAAI,CAAC,cAAc,OAAO;CAE1B,IAAI,aAAa,SAAS,GAAG,GAC3B,MAAM,IAAI,MACR,0DAA0D,aAAa,wDAEzE;CAKF,MAAM,KACJ,OAAO,iBAAiB,WACpB,yBAAyB,YAAY,IACrC,oBAAoB,YAAY;CAEtC,OAAO,KAAK,GAAG,aAAa,GAAG,OAAO;AACxC;;;;;;;;;;;;;AAcA,SAAgB,UACd,SACA,eACA,cACQ;CAER,MAAM,SAAS,YAAY,SADX,cAAc,OAAO,CAAC,CAAC,MAAM,QAAQ,IAAI,SAAS,QAC9B,IAAW,iBAAiB,CAAC,IAAK,KAAA,GAAW,YAAY;CAC7F,uBAAuB,MAAM;CAC7B,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"href-8l5VD23D.js","names":[],"sources":["../../src/shared/href.ts"],"sourcesContent":["/**\n * Route-pattern interpolation and query serialization — the runtime behind\n * `<Link segmentParams searchParams>` and `href()` from `@timber-js/app/routes`.\n *\n * Directive-free and isomorphic: no `'use client'`, no React, no ALS. It\n * lived in `client/link.tsx` until TIM-1621, where the `'use client'`\n * directive turned every import from a server component, middleware or\n * action into a client-reference stub — so nothing on the server could\n * build a URL with it.\n *\n * Segment values serialize through the app/schema.ts codecs registered in\n * `params/codec-registry.ts`. Every entry (RSC, SSR, browser) registers\n * them, so a URL built here is the same in every environment.\n *\n * Design docs: design/09-typescript.md §\"Typed Routes\",\n * design/41-global-params.md §\"Link Component\".\n */\n\nimport { classifyUrlSegment, type UrlSegment } from '../routing/segment-classify.ts';\nimport { getSchemaCodec } from '../params/codec-registry.ts';\nimport { validateNavigationHref } from './href-validation.ts';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ParamValue = string | number | string[] | { toString(): string; [key: string]: any };\n\n/**\n * A query, in one of two shapes discriminated by `typeof === 'string'`:\n *\n * 1. Codec-aware (preferred) — the string `definition.buildSearchParams()`\n * returns. It applies each codec, honours `withUrlKey` aliases, and omits\n * values equal to their default. Passed through untouched.\n *\n * 2. Plain record (escape hatch) — every value is String()-coerced, arrays\n * repeat their key, null/undefined are skipped. No codecs, no aliases, so\n * it must not carry keys a definition owns: `{ search: 'x' }` emits\n * `?search=x` where the definition would emit `?q=x`.\n *\n * Why a STRING and not a URLSearchParams: a Link is routinely rendered by a\n * Server Component, so this value crosses the RSC Flight boundary before the\n * client Link runs. `URLSearchParams` is iterable, and React serializes any\n * iterable as an array — so the prop arrived as `[['pg','2'], …]`, fell into\n * the plain-object branch, and rendered `?0=pg&0=2`. Strings survive Flight\n * unchanged. (Codex P1 on PR #1021; reproduced against a live dev server.)\n *\n * See design/23-search-params.md §\"Link Integration\".\n */\nexport type SearchParamsArg = string | Record<string, unknown>;\n\n/**\n * Parse a route pattern's path portion into classified segments.\n * Uses the shared character-based classifier.\n */\nexport function parseSegments(pattern: string): UrlSegment[] {\n return pattern.split('/').filter(Boolean).map(classifyUrlSegment);\n}\n\n/**\n * Encode a codec's path-shaped output (it may contain '/') segment by segment.\n */\nfunction encodePath(serialized: string): string {\n return serialized.split('/').map(encodeURIComponent).join('/');\n}\n\n/**\n * Resolve a single classified segment into its string representation.\n * Returns null for optional catch-all with no value (filtered out before join).\n *\n * When schema codecs are registered (from virtual:timber-schema), uses\n * codec.serialize() for URL construction instead of plain String().\n */\nfunction resolveSegment(\n seg: UrlSegment,\n params: Record<string, ParamValue>,\n pattern: string\n): string | null {\n switch (seg.kind) {\n case 'static':\n return seg.value;\n\n case 'optional-catch-all': {\n const value = params[seg.name];\n if (value === undefined || (Array.isArray(value) && value.length === 0)) {\n return null;\n }\n const codec = getSchemaCodec(`[[...${seg.name}]]`);\n if (codec) {\n const serialized = codec.serialize(value);\n return serialized ? encodePath(serialized) : null;\n }\n const segments = Array.isArray(value) ? value : [value];\n return segments.map(encodeURIComponent).join('/');\n }\n\n case 'catch-all': {\n const value = params[seg.name];\n if (value === undefined) {\n throw new Error(\n `Missing required catch-all segment param \"${seg.name}\" for pattern \"${pattern}\".`\n );\n }\n const codec = getSchemaCodec(`[...${seg.name}]`);\n if (codec) {\n const serialized = codec.serialize(value);\n if (!serialized) {\n throw new Error(\n `Catch-all segment param \"${seg.name}\" codec returned null for pattern \"${pattern}\".`\n );\n }\n return encodePath(serialized);\n }\n const segments = Array.isArray(value) ? value : [value];\n if (segments.length === 0) {\n throw new Error(\n `Catch-all segment param \"${seg.name}\" must have at least one segment for pattern \"${pattern}\".`\n );\n }\n return segments.map(encodeURIComponent).join('/');\n }\n\n case 'dynamic': {\n const value = params[seg.name];\n if (value === undefined) {\n throw new Error(`Missing required segment param \"${seg.name}\" for pattern \"${pattern}\".`);\n }\n if (Array.isArray(value)) {\n throw new Error(\n `Segment param \"${seg.name}\" expected a string but received an array for pattern \"${pattern}\".`\n );\n }\n const codec = getSchemaCodec(`[${seg.name}]`);\n const str = codec ? (codec.serialize(value) ?? String(value)) : String(value);\n return (seg.prefix ?? '') + encodeURIComponent(str) + (seg.suffix ?? '');\n }\n }\n}\n\n/**\n * Split a URL pattern into the path portion and any trailing ?query/#hash suffix.\n * Uses URL parsing for correctness rather than manual index arithmetic.\n */\nfunction splitPatternSuffix(pattern: string): [path: string, suffix: string] {\n if (!pattern.includes('?') && !pattern.includes('#')) {\n return [pattern, ''];\n }\n const url = new URL(pattern, 'http://x');\n const suffix = url.search + url.hash;\n const path = pattern.slice(0, pattern.length - suffix.length);\n return [path, suffix];\n}\n\n/**\n * Interpolate dynamic segments in a route pattern with actual values.\n * e.g. interpolateParams(\"/products/[id]\", { id: \"123\" }) → \"/products/123\"\n *\n * Supports:\n * - [param] → single segment (with optional static prefix/suffix)\n * - [...param] → catch-all (joined with /)\n * - [[...param]] → optional catch-all (omitted if undefined/empty)\n *\n * Every value is percent-encoded per segment; catch-all elements are encoded\n * individually, so a value can never introduce a path separator of its own.\n */\nexport function interpolateParams(pattern: string, params: Record<string, ParamValue>): string {\n const [pathPart, suffix] = splitPatternSuffix(pattern);\n\n const resolved = parseSegments(pathPart)\n .map((seg) => resolveSegment(seg, params, pattern))\n .filter((s): s is string => s !== null);\n return ('/' + resolved.join('/') || '/') + suffix;\n}\n\n/**\n * Tolerate a leading '?'. `buildSearchParams()` never emits one, but callers\n * hand-rolling a query string reasonably might, and silently producing\n * `?%3Fa=b` for it would be a worse failure than accepting both.\n */\nfunction stripLeadingQuestionMark(qs: string): string {\n return qs.startsWith('?') ? qs.slice(1) : qs;\n}\n\n/**\n * Escape-hatch serialization for a plain object: String()-coerce every\n * value, append arrays as repeated keys, skip null/undefined.\n *\n * Deliberately codec-free and alias-free — see `SearchParamsArg`.\n */\nfunction coerceToQueryString(values: Record<string, unknown>): string {\n const usp = new URLSearchParams();\n for (const [key, val] of Object.entries(values)) {\n if (val === undefined || val === null) continue;\n if (Array.isArray(val)) {\n for (const item of val) usp.append(key, String(item));\n } else {\n usp.set(key, String(val));\n }\n }\n return usp.toString();\n}\n\n/**\n * Resolve an href from a pattern, its segment params and a query.\n *\n * - `params` given → the href is interpolated as a pattern\n * - `searchParams` given → serialized and appended (an empty query appends\n * nothing, not a bare `?`)\n * - a query in both `href` and `searchParams` throws: they are exclusive\n *\n * Does not validate the result; callers that hand it to a navigation sink\n * run `validateNavigationHref` on it.\n */\nexport function resolveHref(\n href: string,\n params?: Record<string, ParamValue>,\n searchParams?: SearchParamsArg\n): string {\n const resolvedPath = params ? interpolateParams(href, params) : href;\n if (!searchParams) return resolvedPath;\n\n if (resolvedPath.includes('?')) {\n throw new Error(\n `Received both searchParams and a query string in href \"${resolvedPath}\". ` +\n 'These are mutually exclusive — use one or the other.'\n );\n }\n\n // `typeof` is the only discriminator that survives the RSC Flight\n // boundary — see `SearchParamsArg`.\n const qs =\n typeof searchParams === 'string'\n ? stripLeadingQuestionMark(searchParams)\n : coerceToQueryString(searchParams);\n\n return qs ? `${resolvedPath}?${qs}` : resolvedPath;\n}\n\n/**\n * The runtime of `href()` (@timber-js/app/routes), untyped: the typed\n * surface lives in `routes/href.ts` and only narrows what may be passed.\n *\n * A pattern with no dynamic segment is already its URL. One with any —\n * including a lone optional catch-all called with no params — is\n * interpolated, or `/docs/[[...path]]` would come back verbatim. The query\n * is appended exactly as `<Link searchParams>` appends it, and the result is\n * validated like every navigation sink: segment values that would make a\n * protocol-relative URL (`/[...slug]` with `['', 'evil.com']` →\n * `//evil.com`) throw instead of returning an open redirect.\n */\nexport function buildHref(\n pattern: string,\n segmentParams?: Record<string, ParamValue>,\n searchParams?: SearchParamsArg\n): string {\n const dynamic = parseSegments(pattern).some((seg) => seg.kind !== 'static');\n const result = resolveHref(pattern, dynamic ? (segmentParams ?? {}) : undefined, searchParams);\n validateNavigationHref(result);\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,cAAc,SAA+B;CAC3D,OAAO,QAAQ,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,IAAI,kBAAkB;AAClE;;;;AAKA,SAAS,WAAW,YAA4B;CAC9C,OAAO,WAAW,MAAM,GAAG,CAAC,CAAC,IAAI,kBAAkB,CAAC,CAAC,KAAK,GAAG;AAC/D;;;;;;;;AASA,SAAS,eACP,KACA,QACA,SACe;CACf,QAAQ,IAAI,MAAZ;EACE,KAAK,UACH,OAAO,IAAI;EAEb,KAAK,sBAAsB;GACzB,MAAM,QAAQ,OAAO,IAAI;GACzB,IAAI,UAAU,KAAA,KAAc,MAA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E1B,IAAI,aAAa,SAAS,GAAG,GAC3B,MAAM,IAAI,MACR,0DAA0D,aAAa,wDAEzE;CAKF,MAAM,KACJ,OAAO,iBAAiB,WACpB,yBAAyB,YAAY,IACrC,oBAAoB,YAAY;CAEtC,OAAO,KAAK,GAAG,aAAa,GAAG,OAAO;AACxC;;;;;;;;;;;;;AAcA,SAAgB,UACd,SACA,eACA,cACQ;CAER,MAAM,SAAS,YAAY,SADX,cAAc,OAAO,CAAC,CAAC,MAAM,QAAQ,IAAI,SAAS,QAC9B,IAAW,iBAAiB,CAAC,IAAK,KAAA,GAAW,YAAY;CAC7F,uBAAuB,MAAM;CAC7B,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as logLossyCacheValue } from "./logger-
|
|
1
|
+
import { o as logLossyCacheValue } from "./logger-DDLtp5e-.js";
|
|
2
2
|
// src/cache/json-lossy-check.ts
|
|
3
3
|
var LOSSY_TYPES = [
|
|
4
4
|
"Date",
|
|
@@ -62,4 +62,4 @@ function findLossyTypes(value, seen, depth) {
|
|
|
62
62
|
}
|
|
63
63
|
export { warnLossyJsonValue as t };
|
|
64
64
|
|
|
65
|
-
//# sourceMappingURL=json-lossy-check-
|
|
65
|
+
//# sourceMappingURL=json-lossy-check-D47R9Fp5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-lossy-check-
|
|
1
|
+
{"version":3,"file":"json-lossy-check-D47R9Fp5.js","names":[],"sources":["../../src/cache/json-lossy-check.ts"],"sourcesContent":["import { logLossyCacheValue } from '../server/logger.ts';\n\nconst LOSSY_TYPES = ['Date', 'Map', 'Set', 'BigInt'] as const;\n\nlet hasWarned = false;\n\n/**\n * Dev-mode warning when a cache value contains types that lose fidelity\n * through JSON round-trip. Only runs in development — no-op in production.\n *\n * Detects: Date (→ ISO string), Map/Set (→ {}), BigInt (→ throws).\n * Emits once per process to avoid log spam.\n */\nexport function warnLossyJsonValue(value: unknown, cacheKey: string): void {\n if (hasWarned) return;\n if (process.env.NODE_ENV === 'production') return;\n\n const lossy = findLossyTypes(value, new Set(), 0);\n if (lossy.size === 0) return;\n\n hasWarned = true;\n logLossyCacheValue({ cacheKey, types: [...lossy].join(', ') });\n}\n\nfunction findLossyTypes(value: unknown, seen: Set<unknown>, depth: number): Set<string> {\n const lossy = new Set<string>();\n if (depth > 8 || value === null || value === undefined) return lossy;\n if (typeof value === 'bigint') {\n lossy.add('BigInt');\n return lossy;\n }\n if (typeof value !== 'object' && typeof value !== 'function') return lossy;\n if (seen.has(value)) return lossy;\n seen.add(value);\n\n if (value instanceof Date) {\n lossy.add('Date');\n return lossy;\n }\n if (value instanceof Map) {\n lossy.add('Map');\n return lossy;\n }\n if (value instanceof Set) {\n lossy.add('Set');\n return lossy;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n for (const t of findLossyTypes(item, seen, depth + 1)) lossy.add(t);\n if (lossy.size === LOSSY_TYPES.length) return lossy;\n }\n return lossy;\n }\n\n for (const k of Object.keys(value as Record<string, unknown>)) {\n for (const t of findLossyTypes((value as Record<string, unknown>)[k], seen, depth + 1)) {\n lossy.add(t);\n }\n if (lossy.size === LOSSY_TYPES.length) return lossy;\n }\n return lossy;\n}\n\n/** Reset warning state — for tests only. */\nexport function _resetLossyWarning(): void {\n hasWarned = false;\n}\n"],"mappings":";;AAEA,IAAM,cAAc;CAAC;CAAQ;CAAO;CAAO;AAAQ;AAEnD,IAAI,YAAY;;;;;;;;AAShB,SAAgB,mBAAmB,OAAgB,UAAwB;CACzE,IAAI,WAAW;CACf,IAAA,QAAA,IAAA,aAA6B,cAAc;CAE3C,MAAM,QAAQ,eAAe,uBAAO,IAAI,IAAI,GAAG,CAAC;CAChD,IAAI,MAAM,SAAS,GAAG;CAEtB,YAAY;CACZ,mBAAmB;EAAE;EAAU,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI;CAAE,CAAC;AAC/D;AAEA,SAAS,eAAe,OAAgB,MAAoB,OAA4B;CACtF,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI,QAAQ,KAAK,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAC/D,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,IAAI,QAAQ;EAClB,OAAO;CACT;CACA,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO;CACrE,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;CAC5B,KAAK,IAAI,KAAK;CAEd,IAAI,iBAAiB,MAAM;EACzB,MAAM,IAAI,MAAM;EAChB,OAAO;CACT;CACA,IAAI,iBAAiB,KAAK;EACxB,MAAM,IAAI,KAAK;EACf,OAAO;CACT;CACA,IAAI,iBAAiB,KAAK;EACxB,MAAM,IAAI,KAAK;EACf,OAAO;CACT;CAEA,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,KAAK,MAAM,QAAQ,OAAO;GACxB,KAAK,MAAM,KAAK,eAAe,MAAM,MAAM,QAAQ,CAAC,GAAG,MAAM,IAAI,CAAC;GAClE,IAAI,MAAM,SAAS,YAAY,QAAQ,OAAO;EAChD;EACA,OAAO;CACT;CAEA,KAAK,MAAM,KAAK,OAAO,KAAK,KAAgC,GAAG;EAC7D,KAAK,MAAM,KAAK,eAAgB,MAAkC,IAAI,MAAM,QAAQ,CAAC,GACnF,MAAM,IAAI,CAAC;EAEb,IAAI,MAAM,SAAS,YAAY,QAAQ,OAAO;CAChD;CACA,OAAO;AACT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { i as detectDirective, n as classifyModule } from "./classify-cmE0Gins.js";
|
|
2
|
+
import { n as stitchImportChains } from "./chains-BsGKkMTK.js";
|
|
3
|
+
import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "./poison-scan-CJ9QfJWb.js";
|
|
1
4
|
import { i as scanProjectSourceFiles, t as buildSourceExtensions } from "./scan-CyizcBiX.js";
|
|
2
|
-
import { i as detectDirective, n as classifyModule } from "./classify-_W0RWa5w.js";
|
|
3
|
-
import { n as stitchImportChains } from "./chains-D-RRc7CM.js";
|
|
4
|
-
import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "./poison-scan-CRSP06Es.js";
|
|
5
5
|
import { normalizePath } from "vite";
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { readFile } from "node:fs/promises";
|
|
@@ -147,4 +147,4 @@ async function classifyLiveProject(ctx) {
|
|
|
147
147
|
}
|
|
148
148
|
export { classifyLiveFile, classifyLiveProject };
|
|
149
149
|
|
|
150
|
-
//# sourceMappingURL=live-graph-
|
|
150
|
+
//# sourceMappingURL=live-graph-ChuFfmLi.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live-graph-C7-yA8W9.js","names":[],"sources":["../../src/analyze/live-graph.ts"],"sourcesContent":["/**\n * live-graph — classification from a running dev server's environment\n * module graphs (the fast path).\n *\n * When a dev server runs, the env module graphs are already resident —\n * classification is a lookup, not a crawl. This module adapts those\n * graphs to the SAME classification pipeline the cold crawl uses\n * (classify.ts + chains.ts + poison-scan.ts — design/47's \"one\n * classification module, thin frontends\" requirement), so the\n * dev-server endpoint and the CLI can never disagree about a file.\n *\n * Differences from the crawl, both inherent to the live source:\n *\n * - The browser (`client`) graph can be non-empty here (a real browser\n * has requested modules), so `envs.client` is confirmable.\n * - Rendering populates graphs lazily — only visited routes' code is\n * present, and modules behind unexecuted dynamic imports carry\n * `transformResult == null` (the §8 frontier). Those are reported as\n * `subtreeUnknown` rather than transformed on demand: a hint must\n * never mutate the dev server's graphs as a side effect of asking.\n *\n * Design docs: 47-module-environment-tooling.md §8, §\"Dev-server\n * endpoint\".\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\nimport { normalizePath } from 'vite';\nimport {\n classifyModule,\n detectDirective,\n type ClassifyContext,\n type Directive,\n} from './classify.ts';\nimport type { GraphModuleReport } from './crawl.ts';\nimport { stitchImportChains, type ChainGraph, type ImportChain } from './chains.ts';\nimport {\n collectImportSpecifiers,\n importSignals,\n poisoningsFor,\n type Poisoning,\n} from './poison-scan.ts';\nimport { buildSourceExtensions, scanProjectSourceFiles, type ScanFailure } from './scan.ts';\n\n/**\n * Duck-typed node view for liveness checks — the `transformResult`\n * member ChainModuleNode deliberately omits (§8 detection is a\n * classification concern, not a chain concern).\n */\ninterface LiveModuleNode {\n transformResult: unknown;\n}\n\nimport type { ChainModuleNode } from './chains.ts';\n\n/** Duck-typed module graph — structural supertype of Vite's. */\nexport interface LiveGraph extends ChainGraph {\n getModulesByFile(file: string): Set<ChainModuleNode & LiveModuleNode> | undefined;\n}\n\nexport interface LiveGraphContext {\n rsc: LiveGraph;\n ssr: LiveGraph;\n client: LiveGraph;\n /** Realpath'd project root. */\n root: string;\n appDir: string;\n pageExtensions?: readonly string[];\n}\n\n/**\n * Per-module answer — the crawl's shape, aliased rather than restated\n * so a field added to one frontend cannot silently miss the other.\n */\nexport type LiveModuleReport = GraphModuleReport;\n\n/** Non-empty node set for a file in one graph. */\nfunction memberOf(graph: LiveGraph, file: string): boolean {\n return (graph.getModulesByFile(file)?.size ?? 0) > 0;\n}\n\n/**\n * §8: an SSR-graph member whose every node was never transformed is a\n * module behind an unexecuted dynamic import — reachable (it ships to\n * the browser) but its subtree may be missing from the graphs.\n *\n * Live-source caveat: Vite also clears `transformResult` when a watched\n * edit invalidates a node, so on the live graphs `subtreeUnknown`\n * means \"not currently transformed\" — a freshly-edited module reads\n * the same as a dormant dynamic-import payload until the next render\n * re-transforms it. The two states are indistinguishable from the\n * graph alone, and both honestly mean the subtree is not currently\n * known; consumers refreshing on `timber:graph-update` events see the\n * flag clear once the module is re-transformed.\n */\nfunction ssrTransformed(graph: LiveGraph, file: string): boolean | undefined {\n const nodes = graph.getModulesByFile(file);\n if (!nodes || nodes.size === 0) return undefined;\n for (const node of nodes) {\n if (node.transformResult != null) return true;\n }\n return false;\n}\n\n/**\n * Classify one file from the live graphs. `file` must be an absolute\n * realpath (graph nodes carry realpaths); it is slash-normalized here\n * to match Vite's node keying.\n */\nexport async function classifyLiveFile(\n rawFile: string,\n ctx: LiveGraphContext,\n // Shared across a ?all=1 sweep (classifyLiveProject) — a per-call\n // cache would re-read every chain hop's source per target file,\n // quadratic sync IO on well-connected graphs.\n getDirective: (file: string) => Directive = makeDirectiveReader(),\n // Failures are recorded, not swallowed (crawl parity): a lost source\n // read means the directive/poisoning half of the answer is missing,\n // and consumers deserve to see that beside the classification.\n errors?: LiveGraphError[]\n): Promise<LiveModuleReport> {\n const file = normalizePath(rawFile);\n let code: string | null = null;\n try {\n code = await readFile(file, 'utf8');\n } catch (error) {\n // Unreadable (deleted mid-query): classification proceeds on graph\n // membership alone; directive/poisonings default to none.\n errors?.push({\n environment: 'scan',\n id: file,\n message: `source read failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const directive: Directive = code === null ? null : detectDirective(code, file);\n const signals = code === null ? [] : importSignals(collectImportSpecifiers(code, file));\n\n const classifyCtx: ClassifyContext = {\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n };\n const classification = classifyModule(\n {\n file,\n inRsc: memberOf(ctx.rsc, file),\n inSsr: memberOf(ctx.ssr, file),\n inClient: memberOf(ctx.client, file),\n ssrTransformed: ssrTransformed(ctx.ssr, file),\n directive,\n },\n classifyCtx\n );\n\n const chains = classification.pending\n ? []\n : stitchImportChains(file, {\n rsc: ctx.rsc,\n ssr: ctx.ssr,\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n getDirective,\n });\n\n return {\n ...classification,\n boundary: directive === 'use client',\n chains,\n poisonings: poisoningsFor(classification.kind, classification.pending, signals),\n };\n}\n\n/**\n * Synchronous directive reader with a per-call cache. chains.ts wants a\n * sync callback; node:fs readFileSync per unique hop file is acceptable\n * for a walk bounded by chain length.\n */\nfunction makeDirectiveReader(): (file: string) => Directive {\n const cache = new Map<string, Directive>();\n return (file) => {\n const hit = cache.get(file);\n if (hit !== undefined) return hit;\n let directive: Directive = null;\n try {\n directive = detectDirective(readFileSync(file, 'utf8'), file);\n } catch {\n directive = null;\n }\n cache.set(file, directive);\n return directive;\n };\n}\n\n/** Live-source error entry — the crawl's error vocabulary. */\nexport interface LiveGraphError {\n environment: 'scan';\n id: string;\n message: string;\n}\n\nexport interface LiveProjectReport {\n root: string;\n modules: LiveModuleReport[];\n errors: LiveGraphError[];\n}\n\n/**\n * Classify every project source file from the live graphs. Files on\n * disk that no graph reached get the §2 provisional/pending\n * classification — on a lazily-warmed dev server that includes routes\n * nobody has visited yet, which is honest: the graphs genuinely have\n * not confirmed them.\n */\nexport async function classifyLiveProject(ctx: LiveGraphContext): Promise<LiveProjectReport> {\n const files: string[] = [];\n const errors: LiveProjectReport['errors'] = [];\n const extensions = buildSourceExtensions(ctx.pageExtensions);\n await scanProjectSourceFiles(\n ctx.root,\n files,\n (failure: ScanFailure) =>\n errors.push({ environment: 'scan', id: failure.dir, message: failure.message }),\n 0,\n extensions\n );\n const modules: LiveModuleReport[] = [];\n const getDirective = makeDirectiveReader();\n for (const file of files) {\n modules.push(await classifyLiveFile(file, ctx, getDirective, errors));\n }\n modules.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));\n return { root: ctx.root, modules, errors };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAS,SAAS,OAAkB,MAAuB;CACzD,QAAQ,MAAM,iBAAiB,IAAI,CAAC,EAAE,QAAQ,KAAK;AACrD;;;;;;;;;;;;;;;AAgBA,SAAS,eAAe,OAAkB,MAAmC;CAC3E,MAAM,QAAQ,MAAM,iBAAiB,IAAI;CACzC,IAAI,CAAC,SAAS,MAAM,SAAS,GAAG,OAAO,KAAA;CACvC,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,mBAAmB,MAAM,OAAO;CAE3C,OAAO;AACT;;;;;;AAOA,eAAsB,iBACpB,SACA,KAIA,eAA4C,oBAAoB,GAIhE,QAC2B;CAC3B,MAAM,OA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MAAM,QAAkB,CAAC;CACzB,MAAM,SAAsC,CAAC;CAC7C,MAAM,aAAa,sBAAsB,IAAI,cAAc;CAC3D,MAAM,uBACJ,IAAI,MACJ,QACC,YACC,OAAO,KAAK;EAAE,aAAa;EAAQ,IAAI,QAAQ;EAAK,SAAS,QAAQ;CAAQ,CAAC,GAChF,GACA,UACF;CACA,MAAM,UAA8B,CAAC;CACrC,MAAM,eAAe,oBAAoB;CACzC,KAAK,MAAM,QAAQ,OACjB,QAAQ,KAAK,MAAM,iBAAiB,MAAM,KAAK,cAAc,MAAM,CAAC;CAEtE,QAAQ,MAAM,GAAG,MAAO,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAAE;CACvE,OAAO;EAAE,MAAM,IAAI;EAAM;EAAS;CAAO;AAC3C"}
|
|
1
|
+
{"version":3,"file":"live-graph-ChuFfmLi.js","names":[],"sources":["../../src/analyze/live-graph.ts"],"sourcesContent":["/**\n * live-graph — classification from a running dev server's environment\n * module graphs (the fast path).\n *\n * When a dev server runs, the env module graphs are already resident —\n * classification is a lookup, not a crawl. This module adapts those\n * graphs to the SAME classification pipeline the cold crawl uses\n * (classify.ts + chains.ts + poison-scan.ts — design/47's \"one\n * classification module, thin frontends\" requirement), so the\n * dev-server endpoint and the CLI can never disagree about a file.\n *\n * Differences from the crawl, both inherent to the live source:\n *\n * - The browser (`client`) graph can be non-empty here (a real browser\n * has requested modules), so `envs.client` is confirmable.\n * - Rendering populates graphs lazily — only visited routes' code is\n * present, and modules behind unexecuted dynamic imports carry\n * `transformResult == null` (the §8 frontier). Those are reported as\n * `subtreeUnknown` rather than transformed on demand: a hint must\n * never mutate the dev server's graphs as a side effect of asking.\n *\n * Design docs: 47-module-environment-tooling.md §8, §\"Dev-server\n * endpoint\".\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\nimport { normalizePath } from 'vite';\nimport {\n classifyModule,\n detectDirective,\n type ClassifyContext,\n type Directive,\n} from './classify.ts';\nimport type { GraphModuleReport } from './crawl.ts';\nimport { stitchImportChains, type ChainGraph, type ImportChain } from './chains.ts';\nimport {\n collectImportSpecifiers,\n importSignals,\n poisoningsFor,\n type Poisoning,\n} from './poison-scan.ts';\nimport { buildSourceExtensions, scanProjectSourceFiles, type ScanFailure } from './scan.ts';\n\n/**\n * Duck-typed node view for liveness checks — the `transformResult`\n * member ChainModuleNode deliberately omits (§8 detection is a\n * classification concern, not a chain concern).\n */\ninterface LiveModuleNode {\n transformResult: unknown;\n}\n\nimport type { ChainModuleNode } from './chains.ts';\n\n/** Duck-typed module graph — structural supertype of Vite's. */\nexport interface LiveGraph extends ChainGraph {\n getModulesByFile(file: string): Set<ChainModuleNode & LiveModuleNode> | undefined;\n}\n\nexport interface LiveGraphContext {\n rsc: LiveGraph;\n ssr: LiveGraph;\n client: LiveGraph;\n /** Realpath'd project root. */\n root: string;\n appDir: string;\n pageExtensions?: readonly string[];\n}\n\n/**\n * Per-module answer — the crawl's shape, aliased rather than restated\n * so a field added to one frontend cannot silently miss the other.\n */\nexport type LiveModuleReport = GraphModuleReport;\n\n/** Non-empty node set for a file in one graph. */\nfunction memberOf(graph: LiveGraph, file: string): boolean {\n return (graph.getModulesByFile(file)?.size ?? 0) > 0;\n}\n\n/**\n * §8: an SSR-graph member whose every node was never transformed is a\n * module behind an unexecuted dynamic import — reachable (it ships to\n * the browser) but its subtree may be missing from the graphs.\n *\n * Live-source caveat: Vite also clears `transformResult` when a watched\n * edit invalidates a node, so on the live graphs `subtreeUnknown`\n * means \"not currently transformed\" — a freshly-edited module reads\n * the same as a dormant dynamic-import payload until the next render\n * re-transforms it. The two states are indistinguishable from the\n * graph alone, and both honestly mean the subtree is not currently\n * known; consumers refreshing on `timber:graph-update` events see the\n * flag clear once the module is re-transformed.\n */\nfunction ssrTransformed(graph: LiveGraph, file: string): boolean | undefined {\n const nodes = graph.getModulesByFile(file);\n if (!nodes || nodes.size === 0) return undefined;\n for (const node of nodes) {\n if (node.transformResult != null) return true;\n }\n return false;\n}\n\n/**\n * Classify one file from the live graphs. `file` must be an absolute\n * realpath (graph nodes carry realpaths); it is slash-normalized here\n * to match Vite's node keying.\n */\nexport async function classifyLiveFile(\n rawFile: string,\n ctx: LiveGraphContext,\n // Shared across a ?all=1 sweep (classifyLiveProject) — a per-call\n // cache would re-read every chain hop's source per target file,\n // quadratic sync IO on well-connected graphs.\n getDirective: (file: string) => Directive = makeDirectiveReader(),\n // Failures are recorded, not swallowed (crawl parity): a lost source\n // read means the directive/poisoning half of the answer is missing,\n // and consumers deserve to see that beside the classification.\n errors?: LiveGraphError[]\n): Promise<LiveModuleReport> {\n const file = normalizePath(rawFile);\n let code: string | null = null;\n try {\n code = await readFile(file, 'utf8');\n } catch (error) {\n // Unreadable (deleted mid-query): classification proceeds on graph\n // membership alone; directive/poisonings default to none.\n errors?.push({\n environment: 'scan',\n id: file,\n message: `source read failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const directive: Directive = code === null ? null : detectDirective(code, file);\n const signals = code === null ? [] : importSignals(collectImportSpecifiers(code, file));\n\n const classifyCtx: ClassifyContext = {\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n };\n const classification = classifyModule(\n {\n file,\n inRsc: memberOf(ctx.rsc, file),\n inSsr: memberOf(ctx.ssr, file),\n inClient: memberOf(ctx.client, file),\n ssrTransformed: ssrTransformed(ctx.ssr, file),\n directive,\n },\n classifyCtx\n );\n\n const chains = classification.pending\n ? []\n : stitchImportChains(file, {\n rsc: ctx.rsc,\n ssr: ctx.ssr,\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n getDirective,\n });\n\n return {\n ...classification,\n boundary: directive === 'use client',\n chains,\n poisonings: poisoningsFor(classification.kind, classification.pending, signals),\n };\n}\n\n/**\n * Synchronous directive reader with a per-call cache. chains.ts wants a\n * sync callback; node:fs readFileSync per unique hop file is acceptable\n * for a walk bounded by chain length.\n */\nfunction makeDirectiveReader(): (file: string) => Directive {\n const cache = new Map<string, Directive>();\n return (file) => {\n const hit = cache.get(file);\n if (hit !== undefined) return hit;\n let directive: Directive = null;\n try {\n directive = detectDirective(readFileSync(file, 'utf8'), file);\n } catch {\n directive = null;\n }\n cache.set(file, directive);\n return directive;\n };\n}\n\n/** Live-source error entry — the crawl's error vocabulary. */\nexport interface LiveGraphError {\n environment: 'scan';\n id: string;\n message: string;\n}\n\nexport interface LiveProjectReport {\n root: string;\n modules: LiveModuleReport[];\n errors: LiveGraphError[];\n}\n\n/**\n * Classify every project source file from the live graphs. Files on\n * disk that no graph reached get the §2 provisional/pending\n * classification — on a lazily-warmed dev server that includes routes\n * nobody has visited yet, which is honest: the graphs genuinely have\n * not confirmed them.\n */\nexport async function classifyLiveProject(ctx: LiveGraphContext): Promise<LiveProjectReport> {\n const files: string[] = [];\n const errors: LiveProjectReport['errors'] = [];\n const extensions = buildSourceExtensions(ctx.pageExtensions);\n await scanProjectSourceFiles(\n ctx.root,\n files,\n (failure: ScanFailure) =>\n errors.push({ environment: 'scan', id: failure.dir, message: failure.message }),\n 0,\n extensions\n );\n const modules: LiveModuleReport[] = [];\n const getDirective = makeDirectiveReader();\n for (const file of files) {\n modules.push(await classifyLiveFile(file, ctx, getDirective, errors));\n }\n modules.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));\n return { root: ctx.root, modules, errors };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAS,SAAS,OAAkB,MAAuB;CACzD,QAAQ,MAAM,iBAAiB,IAAI,CAAC,EAAE,QAAQ,KAAK;AACrD;;;;;;;;;;;;;;;AAgBA,SAAS,eAAe,OAAkB,MAAmC;CAC3E,MAAM,QAAQ,MAAM,iBAAiB,IAAI;CACzC,IAAI,CAAC,SAAS,MAAM,SAAS,GAAG,OAAO,KAAA;CACvC,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,mBAAmB,MAAM,OAAO;CAE3C,OAAO;AACT;;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I,MAAM,SAAS;EACzB,OAAO;CACT;AACF;;;;;;;;AAsBA,eAAsB,oBAAoB,KAAmD;CAC3F,MAAM,QAAkB,CAAC;CACzB,MAAM,SAAsC,CAAC;CAC7C,MAAM,aAAa,sBAAsB,IAAI,cAAc;CAC3D,MAAM,uBACJ,IAAI,MACJ,QACC,YACC,OAAO,KAAK;EAAE,aAAa;EAAQ,IAAI,QAAQ;EAAK,SAAS,QAAQ;CAAQ,CAAC,GAChF,GACA,UACF;CACA,MAAM,UAA8B,CAAC;CACrC,MAAM,eAAe,oBAAoB;CACzC,KAAK,MAAM,QAAQ,OACjB,QAAQ,KAAK,MAAM,iBAAiB,MAAM,KAAK,cAAc,MAAM,CAAC;CAEtE,QAAQ,MAAM,GAAG,MAAO,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAAE;CACvE,OAAO;EAAE,MAAM,IAAI;EAAM;EAAS;CAAO;AAC3C"}
|
|
@@ -227,6 +227,13 @@ function settleOtelSpan(span, fn) {
|
|
|
227
227
|
endSpanWithError(span, error);
|
|
228
228
|
throw error;
|
|
229
229
|
}
|
|
230
|
+
if (isPlainPromise(result)) return result.then((value) => {
|
|
231
|
+
endSpanOk(span);
|
|
232
|
+
return value;
|
|
233
|
+
}, (error) => {
|
|
234
|
+
endSpanWithError(span, error);
|
|
235
|
+
throw error;
|
|
236
|
+
});
|
|
230
237
|
if (isPromiseLike(result)) {
|
|
231
238
|
const thenable = result;
|
|
232
239
|
return new Promise((resolve, reject) => {
|
|
@@ -247,6 +254,14 @@ function settleOtelSpan(span, fn) {
|
|
|
247
254
|
endSpanOk(span);
|
|
248
255
|
return result;
|
|
249
256
|
}
|
|
257
|
+
/**
|
|
258
|
+
* A native promise of this realm whose `then` is the built-in one: neither a
|
|
259
|
+
* subclass (its `then` may be overridden, and its `then()` constructs the
|
|
260
|
+
* subclass) nor an instance with its own `then` property.
|
|
261
|
+
*/
|
|
262
|
+
function isPlainPromise(value) {
|
|
263
|
+
return value instanceof Promise && Object.getPrototypeOf(value) === Promise.prototype && !Object.hasOwn(value, "then");
|
|
264
|
+
}
|
|
250
265
|
function isPromiseLike(value) {
|
|
251
266
|
return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
|
|
252
267
|
}
|
|
@@ -752,4 +767,4 @@ function swallow(err, reason, opts) {
|
|
|
752
767
|
}
|
|
753
768
|
export { runWithTraceId as A, addSpanEvent as C, getSpanId as D, getOtelTraceId as E, isControlFlowSignal as F, isDenySignal as I, isRedirectSignal as L, withSpan as M, DENY_BRAND as N, getTraceId as O, REDIRECT_BRAND as P, isDevMode as S, generateTraceId as T, logWaitUntilRejected as _, logKeyDisciplineViolation as a, swallow as b, logMiddlewareShortCircuit as c, logRequestCompleted as d, logRequestReceived as f, logSwrRefetchFailed as g, logSlowRequest as h, logCsrfRejected as i, setSpanAttribute as j, replaceTraceId as k, logProxyError as l, logRouteSetupError as m, logCacheMiss as n, logLossyCacheValue as o, logRouteError as p, logCacheReadFailed as r, logMiddlewareError as s, getLogger as t, logRenderError as u, logWaitUntilUnsupported as v, addSpanEventSync as w, isDebug as x, setLogger as y };
|
|
754
769
|
|
|
755
|
-
//# sourceMappingURL=logger-
|
|
770
|
+
//# sourceMappingURL=logger-DDLtp5e-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger-DDLtp5e-.js","names":[],"sources":["../../src/server/signal-identity.ts","../../src/server/tracing.ts","../../src/server/debug.ts","../../src/server/error-formatter.ts","../../src/server/default-logger.ts","../../src/server/logger.ts"],"sourcesContent":["// Signal identity — the brands framework signals carry, the predicates that\n// recognise them, and SsrStreamError.\n//\n// No runtime imports (the one import is type-only), so any environment can\n// load it. The SSR entry's import graph\n// must not reach RSC request state (`request-context.ts` and friends, held\n// to that by `tests/ssr-import-boundary.test.ts`), and the signal classes\n// in primitives.ts sit beside `deny()` and `redirect()`, which read it. SSR\n// code that has to recognise a signal (the logger skips them) imports the\n// predicates from here; the classes stamp the brands exported here.\n\nimport type { DenySignal, RedirectSignal } from './primitives.ts';\n\n// ─── Signal branding ────────────────────────────────────────────────────────\n//\n// Catch sites must NOT use `instanceof` on these classes. In dev, an HMR\n// program reload clears the RSC module cache; a request that is mid-render\n// still holds the catch sites from the old evaluation of primitives.ts while\n// user code loaded after the reload throws from the new one. The two\n// evaluations are distinct classes, so `instanceof` fails and a correct\n// deny() falls through every catch site as an unhandled 500 (TIM-1499).\n//\n// Each class stamps a `Symbol.for` brand on its instances in the constructor.\n// `Symbol.for` keys live in the realm-wide symbol registry, so every\n// evaluation of these modules — and every module graph in the same process —\n// agrees on the key. The `is*` predicates below check the brand and are the\n// only supported way to detect a signal. The classes themselves are NOT\n// anchored on globalThis: a re-evaluated module must hand out its own\n// (possibly updated) class, not a stale one.\n//\n// See design/18-build-system.md §\"Dev Mode: Signal Identity Across Program Reloads\".\n\nexport const DENY_BRAND: unique symbol = Symbol.for('timber:signal.deny');\nexport const REDIRECT_BRAND: unique symbol = Symbol.for('timber:signal.redirect');\nconst SSR_STREAM_ERROR_BRAND: unique symbol = Symbol.for('timber:signal.ssr-stream-error');\n\nfunction hasBrand(value: unknown, brand: symbol): boolean {\n return typeof value === 'object' && value !== null && brand in value;\n}\n\n/** True for any `DenySignal`, regardless of which module evaluation created it. */\nexport function isDenySignal(error: unknown): error is DenySignal {\n return hasBrand(error, DENY_BRAND);\n}\n\n/** True for any `RedirectSignal`, regardless of which module evaluation created it. */\nexport function isRedirectSignal(error: unknown): error is RedirectSignal {\n return hasBrand(error, REDIRECT_BRAND);\n}\n\n/**\n * True for any `SsrStreamError`. This one also crosses Vite environments:\n * it is thrown in SSR and caught in RSC, which are separate module graphs in\n * the same process — the brand is the only identity the two share.\n */\nexport function isSsrStreamError(error: unknown): error is SsrStreamError {\n return hasBrand(error, SSR_STREAM_ERROR_BRAND);\n}\n\n/**\n * Returns true if the error is a framework control-flow signal (RedirectSignal\n * or DenySignal) rather than a genuine application error. Works both for direct\n * instances (RSC-side) and deserialized digest errors (SSR cross-boundary).\n *\n * See also: isFrameworkSignalError() in client/browser-dev.ts (client-only).\n */\nexport function isControlFlowSignal(error: unknown): boolean {\n if (isDenySignal(error) || isRedirectSignal(error)) {\n return true;\n }\n return signalDigest(error) !== null;\n}\n\n/**\n * The HTTP status a control-flow signal answers with: a signal's own, or the\n * one its digest carries once revived on the SSR side. `undefined` for\n * anything that is not a signal.\n */\nexport function controlFlowStatus(error: unknown): number | undefined {\n if (isDenySignal(error) || isRedirectSignal(error)) return error.status;\n const status = signalDigest(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n/** A revived signal's parsed digest (`rsc-stream.ts` writes it), or null. */\nfunction signalDigest(error: unknown): { type: 'deny' | 'redirect'; status?: unknown } | null {\n if (!error || typeof error !== 'object') return null;\n const digest = (error as { digest?: unknown }).digest;\n if (typeof digest !== 'string') return null;\n try {\n const parsed = JSON.parse(digest) as { type?: unknown; status?: unknown } | null;\n if (\n parsed &&\n typeof parsed === 'object' &&\n (parsed.type === 'redirect' || parsed.type === 'deny')\n ) {\n return { type: parsed.type, status: parsed.status };\n }\n } catch {\n // Not valid digest JSON\n }\n return null;\n}\n\n// ─── SsrStreamError ─────────────────────────────────────────────────────────\n\n/**\n * Error thrown when SSR's renderToReadableStream fails due to an error\n * in the decoded RSC stream (e.g., uncontained slot errors).\n *\n * The RSC entry checks for this error type in its catch block. A captured\n * deny or redirect is rethrown to the pipeline first; with no captured\n * signal, it renders the error page for the uncontained error.\n *\n * Not defined in ssr-entry.ts because ssr-entry.ts imports react-dom/server,\n * which cannot be loaded in the RSC environment.\n *\n * Detect with `isSsrStreamError()` — it is thrown in the SSR environment and\n * caught in RSC, so `instanceof` never matches. See \"Signal branding\" above.\n */\nexport class SsrStreamError extends Error {\n readonly [SSR_STREAM_ERROR_BRAND] = true;\n override readonly cause: unknown;\n\n constructor(message: string, cause: unknown) {\n super(message);\n this.name = 'SsrStreamError';\n this.cause = cause;\n }\n}\n","/**\n * Tracing — per-request trace ID via AsyncLocalStorage, OTEL span helpers.\n *\n * getTraceId() is always available in server code (middleware, access, components, actions).\n * Returns a 32-char lowercase hex string — the OTEL trace ID when an SDK is active,\n * or a crypto.randomUUID()-derived fallback otherwise.\n *\n * See design/17-logging.md §\"trace_id is Always Set\"\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { trace, SpanStatusCode, type Span, type Tracer } from '@opentelemetry/api';\nimport { traceAls, type TraceStore } from './als-registry.ts';\nimport { controlFlowStatus, isSsrStreamError } from './signal-identity.ts';\n\n// Re-export the TraceStore type for public API consumers.\nexport type { TraceStore } from './als-registry.ts';\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Returns the current request's trace ID — always a 32-char lowercase hex string.\n *\n * With OTEL: the real OTEL trace ID (matches Jaeger/Honeycomb/Datadog).\n * Without OTEL: crypto.randomUUID() with hyphens stripped.\n *\n * Throws if called outside a request context (no ALS store).\n */\nexport function getTraceId(): string {\n const store = traceAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getTraceId() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n return store.request.traceId;\n}\n\n/**\n * Returns the current OTEL span ID if available, undefined otherwise.\n */\nexport function getSpanId(): string | undefined {\n return traceAls.getStore()?.spanId;\n}\n\n// ─── Framework-Internal Helpers ───────────────────────────────────────────\n\n/**\n * Generate a 32-char lowercase hex ID from crypto.randomUUID().\n * Same format as OTEL trace IDs — zero-friction upgrade path.\n */\nexport function generateTraceId(): string {\n return randomUUID().replace(/-/g, '');\n}\n\n/**\n * Run a callback within a trace context. Used by the pipeline to establish\n * per-request ALS scope.\n */\nexport function runWithTraceId<T>(id: string, fn: () => T): T {\n return traceAls.run({ request: { traceId: id } }, fn);\n}\n\n/**\n * Replace the request's trace ID. Used when OTEL creates the root span and\n * we want to switch from the UUID fallback to the real OTEL trace ID. Writes\n * the request's shared trace, so every scope in the request sees it —\n * including the ones outside the span this runs in.\n */\nexport function replaceTraceId(newTraceId: string): void {\n const store = traceAls.getStore();\n if (store) {\n store.request.traceId = newTraceId;\n }\n}\n\n/**\n * Run `fn` in a new trace scope for one span: the enclosing scope's request\n * trace, with this span's pointers. A scope per span, not a save/restore on\n * a shared store — spans overlap (MetadataCollector does not await\n * `timber.metadata`), and a restore that runs after a sibling's would\n * leave the sibling's pointer behind (TIM-1538).\n */\nfunction runInSpanScope<T>(\n pointers: Pick<TraceStore, 'spanId'> | Pick<TraceStore, 'platformSpan'>,\n fn: () => T\n): T {\n const store = traceAls.getStore();\n return store ? traceAls.run({ ...store, ...pointers }, fn) : fn();\n}\n\n/**\n * Get the current trace store, or undefined if outside a request context.\n * Framework-internal — use getTraceId()/getSpanId() in user code.\n */\nexport function getTraceStore(): TraceStore | undefined {\n return traceAls.getStore();\n}\n\n// ─── Dev-Mode OTEL Auto-Init ─────────────────────────────────────────────\n\n/**\n * Well-known key marking dev tracing as initialized.\n *\n * The RSC entry module re-evaluates on every HMR invalidation and calls\n * initDevTracing() again — without this guard, each call would register a\n * fresh provider/processor and duplicate every span's output. Symbol.for()\n * survives module re-evaluation. See TIM-1067, B49.\n */\nconst DEV_TRACING_INIT_KEY = Symbol.for('timber.dev.tracing-initialized');\n\n/**\n * Initialize a minimal OTEL SDK in dev mode so spans are recorded and\n * fed to the DevSpanProcessor for dev log output.\n *\n * If the user already configured an OTEL SDK in register(), we add\n * our DevSpanProcessor alongside theirs. If no SDK is configured,\n * we create a BasicTracerProvider with our processor.\n *\n * Idempotent across module re-evaluations (HMR) — only the first call\n * registers. Called in dev, and in production only when TIMBER_DEBUG is\n * set — otherwise production never loads the OTEL SDK.\n */\nexport async function initDevTracing(\n config: import('../dev-tools/logger.ts').DevLoggerConfig\n): Promise<void> {\n const globals = globalThis as Record<symbol, unknown>;\n if (globals[DEV_TRACING_INIT_KEY]) return;\n\n // Tracing is a diagnostic: any failure to load or construct the SDK\n // disables it with a warning and never fails the server's boot (TIM-1554).\n try {\n const { registerDevTracing } = await import('../dev-tools/instrumentation.ts');\n registerDevTracing(config);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(`[timber] Dev tracing disabled — failed to set up OTEL:\\n ${msg}`);\n return;\n }\n\n globals[DEV_TRACING_INIT_KEY] = true;\n}\n\n// ─── Platform Tracer ─────────────────────────────────────────────────────\n\n/**\n * A native platform span. Mirrors the subset of the Cloudflare Workers\n * `Span` API that timber uses. See design/17-logging.md §\"Cloudflare Native\n * Spans\" and TIM-1135.\n */\nexport interface PlatformSpan {\n setAttribute(key: string, value: string | number | boolean): void;\n}\n\n/**\n * Adapter-provided native tracer. Callback-scoped like Cloudflare's\n * `tracing.enterSpan()` — the span starts when the callback is invoked and\n * ends when it returns or its promise settles. Nesting follows the\n * platform's async context.\n *\n * When registered, withSpan() wraps every framework span in a native span\n * *in addition to* the OTEL emission — dual emission, so external OTEL\n * collectors keep working alongside the platform's native trace view.\n *\n * Register via setPlatformTracer(), or by writing the\n * Symbol.for('timber:platform-tracer') key on globalThis from\n * adapter-generated entry code (what the Cloudflare _worker.js does).\n */\nexport interface PlatformTracer {\n enterSpan<T>(name: string, fn: (span: PlatformSpan) => T): T;\n}\n\n// globalThis + Symbol.for so a tracer registered by adapter-generated entry\n// code (a separate module instance) is visible in both the RSC and SSR\n// environments — same pattern as the cf-bindings ALS.\nconst PLATFORM_TRACER_KEY = Symbol.for('timber:platform-tracer');\n\n/** Register (or clear) the native platform tracer for this runtime. */\nexport function setPlatformTracer(tracer: PlatformTracer | undefined): void {\n (globalThis as Record<symbol, unknown>)[PLATFORM_TRACER_KEY] = tracer;\n}\n\n/** The registered native platform tracer, if any. */\nexport function getPlatformTracer(): PlatformTracer | undefined {\n return (globalThis as Record<symbol, unknown>)[PLATFORM_TRACER_KEY] as PlatformTracer | undefined;\n}\n\n// ─── OTEL Span Helpers ───────────────────────────────────────────────────\n\n/**\n * The timber.js OTEL tracer.\n *\n * `@opentelemetry/api` is a direct dependency and a no-op until an SDK\n * registers a provider (the user's `register()`, or dev tracing). Imported\n * statically, not lazily, so `withSpan()` can invoke its callback in the\n * same synchronous frame it was called in: a server component wrapped in a\n * span (`timber.page`, `timber.layout`) must run while React's render\n * dispatcher is still set, or a synchronous component that calls `use()`\n * fails with an invalid hook call. Looked up per span — the API's proxy\n * tracer follows a provider registered after boot.\n */\nfunction getTracer(): Tracer {\n return trace.getTracer('timber.js');\n}\n\n/**\n * Run a function within a framework span. Composes two emission channels:\n *\n * - **Native platform span** — when an adapter registered a PlatformTracer\n * (Cloudflare Workers), the fn is wrapped in platformTracer.enterSpan()\n * so it appears in the platform's native trace view.\n * - **OTEL span** — when an OTEL SDK is active, the fn also runs inside an\n * OTEL span (dual emission). With no SDK the OTEL span is the API's\n * non-recording no-op.\n *\n * Automatically:\n * - Invokes fn synchronously, in the caller's frame — a wrapped server\n * component still sees React's render dispatcher (see getTracer())\n * - Creates the span as a child of the current context\n * - Runs fn in its own trace scope carrying the span's IDs, for log–trace\n * correlation and setSpanAttribute()\n * - Ends the span when the function completes\n * - Records exceptions on error (OTEL channel)\n */\nexport async function withSpan<T>(\n name: string,\n attributes: Record<string, string | number | boolean>,\n fn: () => T | PromiseLike<T>\n): Promise<T> {\n return traceCall(name, attributes, fn);\n}\n\n/**\n * The span core of {@link withSpan}, keeping the shape of the call: `fn` runs\n * synchronously, a value it returns comes back as that value, a promise as a\n * promise, and a synchronous throw is rethrown synchronously.\n *\n * For a framework wrapper that invokes a server component inside a span.\n * React drives a synchronous component through throws: `use()` on a pending\n * promise throws, and Flight retries the component once it settles. That only\n * works if the throw leaves the wrapper synchronously — `withSpan()` would\n * turn it into a rejection, which Flight reports as a render error.\n */\nexport function traceCall<T>(\n name: string,\n attributes: Record<string, string | number | boolean>,\n fn: () => T | PromiseLike<T>\n): T | Promise<T> {\n const platformTracer = getPlatformTracer();\n if (!platformTracer) {\n return runOtelSpan(name, attributes, fn);\n }\n\n // Native platform span wraps the OTEL emission (dual emission). The\n // span is tracked on its own trace scope so setSpanAttribute() can reach\n // it after creation — the platform API has no getActiveSpan() equivalent.\n return platformTracer.enterSpan(name, (span) => {\n for (const key of Object.keys(attributes)) {\n span.setAttribute(key, attributes[key]);\n }\n return runInSpanScope({ platformSpan: span }, () => runOtelSpan(name, attributes, fn));\n });\n}\n\n/**\n * The OTEL half of withSpan() — a non-recording span when no SDK is active.\n * Calls `fn` synchronously; see {@link getTracer}.\n */\nfunction runOtelSpan<T>(\n name: string,\n attributes: Record<string, string | number | boolean>,\n fn: () => T | PromiseLike<T>\n): T | Promise<T> {\n return getTracer().startActiveSpan(name, { attributes }, (span) =>\n runInSpanScope({ spanId: span.spanContext().spanId }, () => settleOtelSpan(span, fn))\n );\n}\n\n/**\n * True when `error` is a `redirect()`, or a `deny()` below 500: an outcome the\n * span observed, not a failure. Such a span ends with its status unset and no\n * exception event, so an OTEL backend does not count every 404 from an access\n * check, a page, a layout or a metadata() as an error (TIM-1597). A\n * `deny(5xx)` is a server failure by HTTP's own account and stays an error.\n *\n * SSR wraps the revived signal its shell failed on in an `SsrStreamError`;\n * the cause is the outcome, so `timber.ssr` follows the same rule.\n */\nfunction isOutcomeSignal(error: unknown): boolean {\n const status = controlFlowStatus(isSsrStreamError(error) ? error.cause : error);\n return status !== undefined && status < 500;\n}\n\n/**\n * Run `fn` and end `span` with its outcome (see {@link isOutcomeSignal}),\n * keeping the call's shape (see {@link traceCall}).\n */\nfunction settleOtelSpan<T>(span: Span, fn: () => T | PromiseLike<T>): T | Promise<T> {\n let result: T | PromiseLike<T>;\n try {\n result = fn();\n } catch (error) {\n endSpanWithError(span, error);\n throw error;\n }\n if (isPlainPromise(result)) {\n // One promise, not two: a plain native promise's `then` cannot throw or\n // run work, so the wrapper below would only add a promise. Dev tracing\n // pays for every promise made inside a render (React's async debug hook\n // captures a stack for each), ~10µs per traced call (TIM-1627).\n return result.then(\n (value) => {\n endSpanOk(span);\n return value;\n },\n (error: unknown) => {\n endSpanWithError(span, error);\n throw error;\n }\n );\n }\n if (isPromiseLike(result)) {\n // Any thenable, not only a native Promise — a custom or cross-realm one\n // must hold the span open too, as `await` would. Its `then` is called\n // here, synchronously, so a lazy thenable starts its work in this span.\n const thenable = result;\n return new Promise<T>((resolve, reject) => {\n const fail = (error: unknown) => {\n endSpanWithError(span, error);\n reject(error);\n };\n try {\n thenable.then((value) => {\n endSpanOk(span);\n resolve(value);\n }, fail);\n } catch (error) {\n // A `then` that throws is a rejection, as for `await`; end the span.\n fail(error);\n }\n });\n }\n endSpanOk(span);\n return result;\n}\n\n/**\n * A native promise of this realm whose `then` is the built-in one: neither a\n * subclass (its `then` may be overridden, and its `then()` constructs the\n * subclass) nor an instance with its own `then` property.\n */\nfunction isPlainPromise<T>(value: T | PromiseLike<T>): value is Promise<T> {\n return (\n value instanceof Promise &&\n Object.getPrototypeOf(value) === Promise.prototype &&\n !Object.hasOwn(value, 'then')\n );\n}\n\nfunction isPromiseLike<T>(value: T | PromiseLike<T>): value is PromiseLike<T> {\n return (\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n 'then' in value &&\n typeof value.then === 'function'\n );\n}\n\nfunction endSpanOk(span: Span): void {\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n}\n\n/**\n * True when `error` is React suspending the component, not failing it: a\n * thrown thenable, or the `SuspenseException` that `use()` throws on a\n * pending promise. Flight retries the component once the promise settles, so\n * a span around a synchronous component (see {@link traceCall}) that suspends\n * is not an error span — the retry's span carries the real outcome.\n *\n * React does not export `SuspenseException`; Flight recognises it by\n * identity, and its message — which React keeps stable because it is the\n * user-facing explanation when one is caught by mistake — is the only handle\n * outside React.\n */\nfunction isReactSuspension(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n if ('then' in error && typeof error.then === 'function') return true;\n return error instanceof Error && error.message.startsWith('Suspense Exception:');\n}\n\nfunction endSpanWithError(span: Span, error: unknown): void {\n if (!isOutcomeSignal(error) && !isReactSuspension(error)) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n }\n span.end();\n}\n\n/**\n * Set an attribute on the current active span (if any).\n * Used for setting span attributes after span creation (e.g. timber.result on access spans).\n */\nexport async function setSpanAttribute(\n key: string,\n value: string | number | boolean\n): Promise<void> {\n // Forward to the innermost active native platform span, if any.\n const platformSpan = traceAls.getStore()?.platformSpan;\n if (platformSpan) {\n platformSpan.setAttribute(key, value);\n }\n\n const activeSpan = trace.getActiveSpan();\n if (activeSpan?.isRecording()) {\n activeSpan.setAttribute(key, value);\n }\n}\n\n/**\n * Add a span event to the current active span (if any).\n * Used for timber.cache HIT/MISS events — recorded as span events, not child spans.\n */\nexport async function addSpanEvent(\n name: string,\n attributes?: Record<string, string | number | boolean>\n): Promise<void> {\n const activeSpan = trace.getActiveSpan();\n if (activeSpan?.isRecording()) {\n activeSpan.addEvent(name, attributes);\n }\n}\n\n/**\n * Fire-and-forget span event — no await, no microtask overhead.\n *\n * Used on the cache hot path where awaiting addSpanEvent creates an\n * unnecessary microtask per cache operation.\n *\n * See TIM-370 for perf motivation.\n */\nexport function addSpanEventSync(\n name: string,\n attributes?: Record<string, string | number | boolean>\n): void {\n const activeSpan = trace.getActiveSpan();\n if (activeSpan?.isRecording()) {\n activeSpan.addEvent(name, attributes);\n }\n}\n\n/**\n * Try to extract the OTEL trace ID from the current active span context.\n * Returns undefined if OTEL is not active or no span exists. (The span ID\n * reaches logs through the span's own trace scope, not from here.)\n */\nexport async function getOtelTraceId(): Promise<string | undefined> {\n const activeSpan = trace.getActiveSpan();\n if (!activeSpan) return undefined;\n\n const ctx = activeSpan.spanContext();\n // OTEL uses \"0000000000000000\" as invalid trace IDs\n if (!ctx.traceId || ctx.traceId === '00000000000000000000000000000000') {\n return undefined;\n }\n\n return ctx.traceId;\n}\n","/**\n * Runtime debug flag for timber.js.\n *\n * Two distinct functions for two distinct security levels:\n *\n * ## `isDebug()` — server-side logging only\n *\n * Returns true when timber's debug/warning messages should be written to\n * stderr / the server console. This NEVER affects what is sent to the\n * client (no error details, no timing headers, no stack traces).\n *\n * Active when any of:\n * - `NODE_ENV !== 'production'` (standard dev mode)\n * - `TIMBER_DEBUG` env var is set to a truthy value at runtime\n * - `timber.config.ts` has `debug: true`\n *\n * ## `isDevMode()` — client-visible dev behavior\n *\n * Returns true ONLY when `NODE_ENV !== 'production'`. This gates anything\n * that changes what clients can observe:\n * - Dev error pages with stack traces (fallback-error.ts)\n * - Detailed Server-Timing headers (pipeline.ts)\n * - Error messages in action INTERNAL_ERROR payloads (action-client.ts)\n * - Pipeline error handler wiring (Vite overlay)\n *\n * `isDevMode()` is statically replaced in production builds → the guarded\n * code is tree-shaken to zero bytes. TIMBER_DEBUG cannot enable it.\n *\n * Usage:\n * In Cloudflare Workers wrangler.toml:\n * [vars]\n * TIMBER_DEBUG = \"1\"\n *\n * In Node.js:\n * TIMBER_DEBUG=1 node server.js\n *\n * In timber.config.ts:\n * export default { debug: true }\n *\n * See design/13-security.md for the security taxonomy.\n * See design/18-build-system.md for build pipeline details.\n */\n\n// ─── Dev Mode (client-visible) ──────────────────────────────────────────────\n\n/**\n * Check if the application is running in development mode.\n *\n * This is the ONLY function that should gate client-visible dev behavior:\n * - Dev error pages with stack traces\n * - Error messages in action `INTERNAL_ERROR` payloads\n * - Pipeline error handler wiring (Vite overlay)\n *\n * Returns `process.env.NODE_ENV !== 'production'`, which is statically\n * replaced by the bundler in production builds. Code guarded by this\n * function is tree-shaken to zero bytes in production.\n *\n * TIMBER_DEBUG does NOT enable this — that would leak server internals\n * to clients. Use `isDebug()` for server-side-only logging.\n */\nexport function isDevMode(): boolean {\n return process.env.NODE_ENV !== 'production';\n}\n\n// ─── Debug Flag (server-side logging only) ──────────────────────────────────\n\n/**\n * Config-level debug override. Set via `setDebugFromConfig()` during\n * initialization when timber.config.ts has `debug: true`.\n */\nlet _configDebug = false;\n\n/**\n * Set the debug flag from timber.config.ts.\n * Called during handler initialization.\n */\nexport function setDebugFromConfig(debug: boolean): void {\n _configDebug = debug;\n}\n\n/**\n * Check if timber debug logging is active (server-side only).\n *\n * Returns true if ANY of these conditions hold:\n * - NODE_ENV is not 'production' (standard dev mode)\n * - TIMBER_DEBUG environment variable is set to a truthy value at runtime\n * - timber.config.ts has `debug: true`\n *\n * This function controls ONLY server-side logging — messages written to\n * stderr or the server console. It NEVER affects client-visible behavior\n * (error pages, response headers, action payloads). For client-visible\n * behavior, use `isDevMode()`.\n *\n * The TIMBER_DEBUG check is deliberately written as a dynamic property\n * access so bundlers cannot statically replace it.\n */\nexport function isDebug(): boolean {\n // Fast path: dev mode (statically replaced to `true` in dev, `false` in prod)\n if (process.env.NODE_ENV !== 'production') return true;\n\n // Config override\n if (_configDebug) return true;\n\n // Runtime env var check — uses dynamic access to prevent static replacement.\n // In production builds, process.env.NODE_ENV is statically replaced, but\n // TIMBER_DEBUG must survive as a runtime check. The dynamic key access\n // pattern ensures the bundler treats this as opaque.\n return _readTimberDebugEnv();\n}\n\n/**\n * Read TIMBER_DEBUG from the environment at runtime.\n *\n * Extracted to a separate function to:\n * 1. Prevent bundler inlining (cross-module function calls are not inlined)\n * 2. Handle platforms where `process` may not exist (Cloudflare Workers)\n * 3. Support globalThis.__TIMBER_DEBUG for programmatic control\n */\nfunction _readTimberDebugEnv(): boolean {\n // globalThis override — useful for programmatic control and testing\n if ((globalThis as Record<string, unknown>).__TIMBER_DEBUG) return true;\n\n // process.env — works in Node.js and platforms that polyfill process\n try {\n const key = 'TIMBER_DEBUG';\n const val =\n typeof process !== 'undefined' && process.env\n ? (process.env as Record<string, string | undefined>)[key]\n : undefined;\n if (val && val !== '0' && val !== 'false') return true;\n } catch {\n // process may not exist or env may throw — safe to ignore\n }\n\n return false;\n}\n","/**\n * Error Formatter — rewrites SSR/RSC error messages to surface user code.\n *\n * When React or Vite throw errors during SSR, stack traces reference\n * vendored dependency paths (e.g. `.vite/deps_ssr/@vitejs_plugin-rsc_vendor_...`)\n * and mangled export names (`__vite_ssr_export_default__`). This module\n * rewrites error messages and stack traces to point at user code instead.\n *\n * Dev-only — in production, errors go through the structured logger\n * without formatting.\n */\n\n// ─── Stack Trace Rewriting ──────────────────────────────────────────────────\n\n/**\n * Patterns that identify internal Vite/RSC vendor paths in stack traces.\n * These are replaced with human-readable labels.\n */\nconst VENDOR_PATH_PATTERNS: Array<{ pattern: RegExp; replacement: string }> = [\n {\n pattern: /node_modules\\/\\.vite\\/deps_ssr\\/@vitejs_plugin-rsc_vendor_react-server-dom[^\\s)]+/g,\n replacement: '<react-server-dom>',\n },\n {\n pattern: /node_modules\\/\\.vite\\/deps_ssr\\/@vitejs_plugin-rsc_vendor[^\\s)]+/g,\n replacement: '<rsc-vendor>',\n },\n {\n pattern: /node_modules\\/\\.vite\\/deps_ssr\\/[^\\s)]+/g,\n replacement: '<vite-dep>',\n },\n {\n pattern: /node_modules\\/\\.vite\\/deps\\/[^\\s)]+/g,\n replacement: '<vite-dep>',\n },\n];\n\n/**\n * Patterns that identify Vite-mangled export names in error messages.\n */\nconst MANGLED_NAME_PATTERNS: Array<{ pattern: RegExp; replacement: string }> = [\n {\n pattern: /__vite_ssr_export_default__/g,\n replacement: '<default export>',\n },\n {\n pattern: /__vite_ssr_export_(\\w+)__/g,\n replacement: '<export $1>',\n },\n];\n\n/**\n * Rewrite an error's message and stack to replace internal Vite paths\n * and mangled names with human-readable labels.\n */\nexport function formatSsrError(error: unknown): string {\n if (!(error instanceof Error)) {\n return String(error);\n }\n\n let message = error.message;\n let stack = error.stack ?? '';\n\n // Rewrite mangled names in the message\n for (const { pattern, replacement } of MANGLED_NAME_PATTERNS) {\n message = message.replace(pattern, replacement);\n }\n\n // Rewrite vendor paths in the stack\n for (const { pattern, replacement } of VENDOR_PATH_PATTERNS) {\n stack = stack.replace(pattern, replacement);\n }\n\n // Rewrite mangled names in the stack too\n for (const { pattern, replacement } of MANGLED_NAME_PATTERNS) {\n stack = stack.replace(pattern, replacement);\n }\n\n // Extract hints from React-specific error patterns\n const hint = extractErrorHint(error.message);\n\n // Build formatted output: cleaned message, hint (if any), then cleaned stack\n const parts: string[] = [];\n parts.push(message);\n if (hint) {\n parts.push(` → ${hint}`);\n }\n\n // Include only the user-code frames from the stack (skip the first line\n // which is the message itself, and filter out vendor-only frames)\n const userFrames = extractUserFrames(stack);\n if (userFrames.length > 0) {\n parts.push('');\n parts.push(' User code in stack:');\n for (const frame of userFrames) {\n parts.push(` ${frame}`);\n }\n }\n\n return parts.join('\\n');\n}\n\n// ─── Error Hint Extraction ──────────────────────────────────────────────────\n\n/**\n * Extract a human-readable hint from common React/RSC error messages.\n *\n * React error messages contain useful information but the surrounding\n * context (vendor paths, mangled names) obscures it. This extracts the\n * actionable part as a one-line hint.\n */\nfunction extractErrorHint(message: string): string | null {\n // \"Functions cannot be passed directly to Client Components\"\n // Extract the component and prop name from the JSX-like syntax in the message\n const fnPassedMatch = message.match(/Functions cannot be passed directly to Client Components/);\n if (fnPassedMatch) {\n // Try to extract the prop name from the message\n // React formats: <... propName={function ...} ...>\n const propMatch = message.match(/<[^>]*?\\s(\\w+)=\\{function/);\n if (propMatch) {\n return `Prop \"${propMatch[1]}\" is a function — mark it \"use server\" or call it before passing`;\n }\n return 'A function prop was passed to a Client Component — mark it \"use server\" or call it before passing';\n }\n\n // \"Objects are not valid as a React child\"\n if (message.includes('Objects are not valid as a React child')) {\n return 'An object was rendered as JSX children — convert to string or extract the value';\n }\n\n // \"Cannot read properties of undefined/null\"\n const nullRefMatch = message.match(\n /Cannot read propert(?:y|ies) of (undefined|null) \\(reading '(\\w+)'\\)/\n );\n if (nullRefMatch) {\n return `Accessed .${nullRefMatch[2]} on ${nullRefMatch[1]} — check that the value exists`;\n }\n\n // \"X is not a function\"\n const notFnMatch = message.match(/(\\w+) is not a function/);\n if (notFnMatch) {\n return `\"${notFnMatch[1]}\" is not a function — check imports and exports`;\n }\n\n // \"Element type is invalid\"\n if (message.includes('Element type is invalid')) {\n return 'A component resolved to undefined/null — check default exports and import paths';\n }\n\n // \"Invalid hook call\" — hooks called outside React's render context.\n // In RSC, this typically means a 'use client' component was executed as a\n // server component instead of being serialized as a client reference.\n if (message.includes('Invalid hook call')) {\n return (\n 'A hook was called outside of a React component render. ' +\n \"If this is a 'use client' component, ensure the directive is at the very top of the file \" +\n '(before any imports) and that @vitejs/plugin-rsc is loaded correctly. ' +\n \"Barrel re-exports from non-'use client' files do not propagate the directive.\"\n );\n }\n\n return null;\n}\n\n// ─── Stack Frame Filtering ──────────────────────────────────────────────────\n\n/**\n * Extract stack frames that reference user code (not node_modules,\n * not framework internals).\n *\n * Returns at most 5 frames to keep output concise.\n */\nfunction extractUserFrames(stack: string): string[] {\n const lines = stack.split('\\n');\n const userFrames: string[] = [];\n\n for (const line of lines) {\n const trimmed = line.trim();\n // Skip non-frame lines\n if (!trimmed.startsWith('at ')) continue;\n // Skip node_modules, vendor, and internal frames\n if (\n trimmed.includes('node_modules') ||\n trimmed.includes('<react-server-dom>') ||\n trimmed.includes('<rsc-vendor>') ||\n trimmed.includes('<vite-dep>') ||\n trimmed.includes('node:internal')\n ) {\n continue;\n }\n userFrames.push(trimmed);\n if (userFrames.length >= 5) break;\n }\n\n return userFrames;\n}\n","/**\n * DefaultLogger — human-readable stderr logging when no custom logger is configured.\n *\n * Ships as the fallback so production deployments always have error visibility,\n * even without an `instrumentation.ts` logger export. Output is one line per\n * event, designed for `fly logs`, `kubectl logs`, Cloudflare dashboard tails, etc.\n *\n * Format:\n * [timber] ERROR message key=value key=value trace_id=4bf92f35\n * [timber] WARN message key=value key=value trace_id=4bf92f35\n * [timber] INFO message method=GET path=/dashboard status=200 durationMs=43 trace_id=4bf92f35\n *\n * Behavior:\n * - `info` and `debug` suppressed in dev mode (dev logging handles them);\n * `warn` and `error` are always written (TIM-555)\n * - `debug` suppressed unless TIMBER_DEBUG is set\n * - Replaced entirely when a custom logger is set via `setLogger()`\n *\n * See design/17-logging.md §\"DefaultLogger\"\n */\n\nimport { isDevMode, isDebug } from './debug.ts';\nimport { formatSsrError } from './error-formatter.ts';\nimport type { TimberLogger } from './logger.ts';\n\n/**\n * Format data fields as `key=value` pairs for human-readable output.\n * - `error` key is serialized via formatSsrError for stack trace cleanup\n * - `trace_id` is truncated to 8 chars for readability (full ID in OTEL)\n * - Other values are stringified inline\n */\nfunction formatDataFields(data?: Record<string, unknown>): string {\n if (!data) return '';\n\n const parts: string[] = [];\n let traceId: string | undefined;\n\n for (const [key, value] of Object.entries(data)) {\n if (key === 'trace_id') {\n // Defer trace_id to the end\n traceId = typeof value === 'string' ? value : String(value);\n continue;\n }\n if (key === 'error') {\n // Serialize errors with formatSsrError for clean output\n parts.push(`error=${formatSsrError(value)}`);\n continue;\n }\n if (value === undefined || value === null) continue;\n parts.push(`${key}=${value}`);\n }\n\n // trace_id always last, truncated to 8 chars for readability\n if (traceId) {\n parts.push(`trace_id=${traceId.slice(0, 8)}`);\n }\n\n return parts.length > 0 ? ' ' + parts.join(' ') : '';\n}\n\n/** Pad level string to fixed width for alignment. */\nfunction padLevel(level: string): string {\n return level.padEnd(5);\n}\n\nexport function createDefaultLogger(): TimberLogger {\n return {\n error(msg: string, data?: Record<string, unknown>): void {\n // Errors are ALWAYS logged, including dev mode. Suppressing errors\n // in dev causes silent 500s with no stack trace, making route.ts\n // and render errors impossible to debug. See TIM-555.\n const fields = formatDataFields(data);\n process.stderr.write(`[timber] ${padLevel('ERROR')} ${msg}${fields}\\n`);\n },\n\n warn(msg: string, data?: Record<string, unknown>): void {\n // Warnings are always logged — same rationale as errors.\n const fields = formatDataFields(data);\n process.stderr.write(`[timber] ${padLevel('WARN')} ${msg}${fields}\\n`);\n },\n\n info(msg: string, data?: Record<string, unknown>): void {\n // info is suppressed by default — per-request lines are too noisy\n // without a custom logger. Enable with TIMBER_DEBUG.\n if (isDevMode()) return;\n if (!isDebug()) return;\n const fields = formatDataFields(data);\n process.stderr.write(`[timber] ${padLevel('INFO')} ${msg}${fields}\\n`);\n },\n\n debug(msg: string, data?: Record<string, unknown>): void {\n // debug is suppressed in dev (dev logger handles it) and in\n // production unless TIMBER_DEBUG is explicitly set.\n if (isDevMode()) return;\n if (!isDebug()) return;\n const fields = formatDataFields(data);\n process.stderr.write(`[timber] ${padLevel('DEBUG')} ${msg}${fields}\\n`);\n },\n };\n}\n","/**\n * Logger — structured logging with environment-aware formatting.\n *\n * timber.js ships a DefaultLogger that writes human-readable lines to stderr\n * in production. Users can export a custom logger from instrumentation.ts to\n * replace it with pino, winston, or any TimberLogger-compatible object.\n *\n * See design/17-logging.md §\"Production Logging\"\n */\n\nimport { generateTraceId, getTraceStore } from './tracing.ts';\nimport { createDefaultLogger } from './default-logger.ts';\nimport { isDevMode } from './debug.ts';\nimport { isControlFlowSignal } from './signal-identity.ts';\nimport type { CsrfRejectReason } from './csrf.ts';\n\n// ─── Logger Interface ─────────────────────────────────────────────────────\n\n/** Any object with standard log methods satisfies this — pino, winston, consola, console. */\nexport interface TimberLogger {\n info(msg: string, data?: Record<string, unknown>): void;\n warn(msg: string, data?: Record<string, unknown>): void;\n error(msg: string, data?: Record<string, unknown>): void;\n debug(msg: string, data?: Record<string, unknown>): void;\n}\n\n// ─── Logger Registry ──────────────────────────────────────────────────────\n\n// Initialize with DefaultLogger so production errors are never silent.\n// Replaced when setLogger() is called from instrumentation.ts.\nlet _logger: TimberLogger = createDefaultLogger();\n\n/**\n * Set the user-provided logger. Called by the instrumentation loader\n * when it finds a `logger` export in instrumentation.ts. Replaces\n * the DefaultLogger entirely.\n */\nexport function setLogger(logger: TimberLogger): void {\n _logger = logger;\n}\n\n/**\n * Get the current logger. Always non-null — returns DefaultLogger when\n * no custom logger is configured.\n */\nexport function getLogger(): TimberLogger {\n return _logger;\n}\n\n// ─── Framework Log Helpers ────────────────────────────────────────────────\n\n/**\n * Inject trace_id and span_id into log data for log–trace correlation.\n * Always injects trace_id (never undefined). Injects span_id only when OTEL is active.\n */\nfunction withTraceContext(data?: Record<string, unknown>): Record<string, unknown> {\n const store = getTraceStore();\n const enriched: Record<string, unknown> = { ...data };\n if (store) {\n enriched.trace_id = store.request.traceId;\n if (store.spanId) {\n enriched.span_id = store.spanId;\n }\n }\n return enriched;\n}\n\n// ─── Framework Event Emitters ─────────────────────────────────────────────\n\n/**\n * Log a CSRF rejection. Level: warn — the 403 body is deliberately terse,\n * so this line is the only place the rejected origin is visible (TIM-1459).\n * `detail` names the observed origin and, where one exists, the expected one.\n *\n * The gate runs inside the pipeline's trace scope, so the line carries the\n * request's `trace_id`. A caller outside any scope still gets one minted\n * here — the field is always present (design/17-logging.md §\"trace_id is\n * Always Set\").\n */\nexport function logCsrfRejected(\n detail: string,\n data: { method: string; path: string; reason: CsrfRejectReason }\n): void {\n const fields = withTraceContext(data);\n fields.trace_id ??= generateTraceId();\n _logger.warn(`CSRF origin check failed: ${detail}`, fields);\n}\n\n/** Log a completed request. Level: info. */\nexport function logRequestCompleted(data: {\n method: string;\n path: string;\n status: number;\n durationMs: number;\n /** Number of concurrent in-flight requests (including this one) at completion time. */\n concurrency?: number;\n}): void {\n _logger.info('request completed', withTraceContext(data));\n}\n\n/** Log request received. Level: debug. */\nexport function logRequestReceived(data: { method: string; path: string }): void {\n _logger.debug('request received', withTraceContext(data));\n}\n\n/** Log a slow request warning. Level: warn. */\nexport function logSlowRequest(data: {\n method: string;\n path: string;\n durationMs: number;\n threshold: number;\n /** Number of concurrent in-flight requests at the time the slow request completed. */\n concurrency?: number;\n}): void {\n _logger.warn('slow request exceeded threshold', withTraceContext(data));\n}\n\n/** Log middleware short-circuit. Level: debug. */\nexport function logMiddlewareShortCircuit(data: {\n method: string;\n path: string;\n status: number;\n}): void {\n _logger.debug('middleware short-circuited', withTraceContext(data));\n}\n\n/** Log unhandled error in middleware phase. Level: error. */\nexport function logMiddlewareError(data: { method: string; path: string; error: unknown }): void {\n if (isControlFlowSignal(data.error)) return;\n _logger.error('unhandled error in middleware phase', withTraceContext(data));\n}\n\n/** Log unhandled error in route setup (matching, param coercion). Level: error. */\nexport function logRouteSetupError(data: { method: string; path: string; error: unknown }): void {\n if (isControlFlowSignal(data.error)) return;\n _logger.error('unhandled error in route setup', withTraceContext(data));\n}\n\n/** Log unhandled render-phase error. Level: error. */\nexport function logRenderError(data: {\n method: string;\n path: string;\n error: unknown;\n errorId?: string;\n}): void {\n if (isControlFlowSignal(data.error)) return;\n _logger.error('unhandled render-phase error', withTraceContext(data));\n}\n\n/**\n * Log a status page, error page, `global-error.tsx` or fallback layout that\n * failed to load and was skipped: the next fallback tier answers in its place.\n * Level: error — a boundary that vanished is a bug in the app, even though the\n * request still gets a page. The caller writes it once per file and failure.\n */\nexport function logSkippedModule(data: {\n method: string;\n path: string;\n file: string;\n error: unknown;\n}): void {\n _logger.error('route file failed to load and was skipped', withTraceContext(data));\n}\n\n/** Log proxy.ts uncaught error. Level: error. */\nexport function logProxyError(data: { error: unknown }): void {\n _logger.error('proxy.ts threw uncaught error', withTraceContext(data));\n}\n\n/** Log unhandled error in server action. Level: error. */\nexport function logActionError(data: {\n method: string;\n path: string;\n error: unknown;\n errorId?: string;\n}): void {\n if (isControlFlowSignal(data.error)) return;\n _logger.error('unhandled server action error', withTraceContext(data));\n}\n\n/**\n * Log a server action request rejected as the client's mistake before the\n * action ran: a reference that does not exist, a body that will not decode.\n * Level: warn, with the reason but no stack — any client can send these, so\n * they must not read as server faults (TIM-1601).\n */\nexport function logActionRejected(data: {\n method: string;\n path: string;\n status: number;\n reason: string;\n}): void {\n _logger.warn('server action request rejected', withTraceContext(data));\n}\n\n/** Log unhandled error in route handler. Level: error. */\nexport function logRouteError(data: { method: string; path: string; error: unknown }): void {\n if (isControlFlowSignal(data.error)) return;\n _logger.error('unhandled route handler error', withTraceContext(data));\n}\n\n/** Log SSR streaming error (post-shell). Level: error. */\nexport function logStreamingError(data: { error: unknown }): void {\n _logger.error('SSR streaming error (post-shell)', withTraceContext(data));\n}\n\n/** Log waitUntil() adapter missing (once at startup). Level: warn. */\nexport function logWaitUntilUnsupported(): void {\n _logger.warn('adapter does not support waitUntil()');\n}\n\n/** Log waitUntil() promise rejection. Level: warn. */\nexport function logWaitUntilRejected(data: { error: unknown }): void {\n _logger.warn('waitUntil() promise rejected', withTraceContext(data));\n}\n\n/**\n * Log a cached value computed from request context its key leaves out\n * (design/45 §Enforcement). Level: error.\n */\nexport function logKeyDisciplineViolation(event: string, data: Record<string, unknown>): void {\n _logger.error(event, withTraceContext(data));\n}\n\n/** Log staleWhileRevalidate refetch failure. Level: warn. */\nexport function logSwrRefetchFailed(data: { cacheKey: string; error: unknown }): void {\n _logger.warn('staleWhileRevalidate refetch failed', withTraceContext(data));\n}\n\n/** Log a cache value that loses fidelity through JSON serialization. Level: warn. */\nexport function logLossyCacheValue(data: { cacheKey: string; types: string }): void {\n _logger.warn(\n 'cache value contains types that lose fidelity through JSON serialization in ' +\n 'Redis/KV cache handlers: Date becomes an ISO string, Map/Set become {}, BigInt throws. ' +\n 'The MemoryCacheHandler preserves them. Transform values to JSON-safe types before ' +\n 'caching, or use MemoryCacheHandler for values that require type preservation.',\n withTraceContext(data)\n );\n}\n\n/** Log cache miss. Level: debug. */\nexport function logCacheMiss(data: { cacheKey: string }): void {\n _logger.debug('timber.cache MISS', withTraceContext(data));\n}\n\n/**\n * Log a cache read that threw or timed out and was served as a miss.\n * Level: warn — the request still succeeds, but a failing store (Redis down,\n * KV erroring) means every read is paying for a live fetch.\n */\nexport function logCacheReadFailed(data: { cacheKey: string; error: unknown }): void {\n _logger.warn('cache read failed — treating as a miss', withTraceContext(data));\n}\n\n// ─── Swallow Helper ───────────────────────────────────────────────────────\n\n/**\n * Log an intentionally swallowed error. Provides observability into catch\n * blocks that are deliberately empty — the error is consumed, never rethrown.\n *\n * Default level: `warn` in dev (so the overlay surfaces patterns), `debug`\n * in production (low noise unless TIMBER_DEBUG is set). Pass `opts.level`\n * to override.\n *\n * **Infallible** — swallow() itself never throws, even if the logger is\n * broken. A thrown swallow would turn a benign catch into a crash.\n */\nexport function swallow(err: unknown, reason: string, opts?: { level?: 'debug' | 'warn' }): void {\n try {\n const level = opts?.level ?? (isDevMode() ? 'warn' : 'debug');\n _logger[level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