@timber-js/app 0.2.0-alpha.221 → 0.2.0-alpha.222
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-BDqn4Oxj.js → actions-vBHr2vqd.js} +3 -3
- package/dist/_chunks/{actions-BDqn4Oxj.js.map → actions-vBHr2vqd.js.map} +1 -1
- package/dist/_chunks/{cache-api-GE4AOe2H.js → cache-api-DdcDLpBj.js} +54 -6
- package/dist/_chunks/cache-api-DdcDLpBj.js.map +1 -0
- package/dist/_chunks/chains-B8TCLved.js +1 -0
- package/dist/_chunks/{chains-e_Buf9vg.js → chains-BchW_AtW.js} +2 -2
- package/dist/_chunks/{chains-e_Buf9vg.js.map → chains-BchW_AtW.js.map} +1 -1
- package/dist/_chunks/{classify-2Yp3xJY1.js → classify-IqzMpxMs.js} +2 -2
- package/dist/_chunks/{classify-2Yp3xJY1.js.map → classify-IqzMpxMs.js.map} +1 -1
- package/dist/_chunks/{cli-check-DDwCkeDY.js → cli-check-DQne_YhU.js} +3 -3
- package/dist/_chunks/{cli-check-DDwCkeDY.js.map → cli-check-DQne_YhU.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-BdIebmk3.js → cli-schema-sync-BS-RFGE2.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-BdIebmk3.js.map → cli-schema-sync-BS-RFGE2.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-CLNfXQDK.js → cli-schema-sync-v872sHms.js} +1 -1
- package/dist/_chunks/{client-dep-entries-BOkpKjj1.js → client-dep-entries-BJyP9SIu.js} +2 -2
- package/dist/_chunks/{client-dep-entries-BOkpKjj1.js.map → client-dep-entries-BJyP9SIu.js.map} +1 -1
- package/dist/_chunks/{convention-lint-ByKJ6aqD.js → convention-lint-VwzrtjIt.js} +3 -3
- package/dist/_chunks/{convention-lint-ByKJ6aqD.js.map → convention-lint-VwzrtjIt.js.map} +1 -1
- package/dist/_chunks/{dev-server-DIy-SY-J.js → dev-server-BNr5drEO.js} +49 -5
- package/dist/_chunks/dev-server-BNr5drEO.js.map +1 -0
- package/dist/_chunks/dev-server-CUg7Mqh_.js +1 -0
- package/dist/_chunks/{flight-source-node-HptmGMT8.js → flight-source-node-BdHUOUqg.js} +3 -3
- package/dist/_chunks/{flight-source-node-HptmGMT8.js.map → flight-source-node-BdHUOUqg.js.map} +1 -1
- package/dist/_chunks/global-context-B9PFncvb.js +48 -0
- package/dist/_chunks/global-context-B9PFncvb.js.map +1 -0
- package/dist/_chunks/{json-lossy-check-C8zBY2uZ.js → json-lossy-check-C3Sht92C.js} +2 -2
- package/dist/_chunks/{json-lossy-check-C8zBY2uZ.js.map → json-lossy-check-C3Sht92C.js.map} +1 -1
- package/dist/_chunks/{live-graph-tSWrv8eH.js → live-graph-DEu_GWbc.js} +4 -4
- package/dist/_chunks/{live-graph-tSWrv8eH.js.map → live-graph-DEu_GWbc.js.map} +1 -1
- package/dist/_chunks/{logger-CbLdcy-W.js → logger-CI_hThfy.js} +10 -2
- package/dist/_chunks/{logger-CbLdcy-W.js.map → logger-CI_hThfy.js.map} +1 -1
- package/dist/_chunks/{node-response-rkQqcFGq.js → node-response-bF0bKoig.js} +2 -2
- package/dist/_chunks/{node-response-rkQqcFGq.js.map → node-response-bF0bKoig.js.map} +1 -1
- package/dist/_chunks/{poison-scan-C4FgMxFl.js → poison-scan-DTWIfNgD.js} +2 -2
- package/dist/_chunks/{poison-scan-C4FgMxFl.js.map → poison-scan-DTWIfNgD.js.map} +1 -1
- package/dist/_chunks/{render-timeout-joFhz4KH.js → render-timeout-Ln_u7fX-.js} +19 -2
- package/dist/_chunks/{render-timeout-joFhz4KH.js.map → render-timeout-Ln_u7fX-.js.map} +1 -1
- package/dist/_chunks/{resolve-schema-CBR6Lm4i.js → resolve-schema-CkAInout.js} +2 -2
- package/dist/_chunks/{resolve-schema-CBR6Lm4i.js.map → resolve-schema-CkAInout.js.map} +1 -1
- package/dist/_chunks/{scanner-Cb3fSjAC.js → scanner-C8fdKvKG.js} +2 -2
- package/dist/_chunks/{scanner-Cb3fSjAC.js.map → scanner-C8fdKvKG.js.map} +1 -1
- package/dist/_chunks/{schema-bridge-C83xa9lT.js → schema-bridge-DpOmvZlI.js} +60 -23
- package/dist/_chunks/schema-bridge-DpOmvZlI.js.map +1 -0
- package/dist/_chunks/{segment-context-xtPUGfdq.js → segment-context-D3DNxKFq.js} +4 -8
- package/dist/_chunks/segment-context-D3DNxKFq.js.map +1 -0
- package/dist/_chunks/{sizeof-QPE5nd3u.js → sizeof-CO3dk0V1.js} +2 -2
- package/dist/_chunks/{sizeof-QPE5nd3u.js.map → sizeof-CO3dk0V1.js.map} +1 -1
- package/dist/_chunks/{walkers-qu8TpiLh.js → walkers-BqzxnwGC.js} +3 -3
- package/dist/_chunks/{walkers-qu8TpiLh.js.map → walkers-BqzxnwGC.js.map} +1 -1
- package/dist/adapters/cloudflare-kv-cache.js +1 -1
- package/dist/analyze/crawl-entry.js +3 -3
- package/dist/analyze/graph-command.js +2 -2
- package/dist/cache/guarded-read.d.ts +29 -0
- package/dist/cache/guarded-read.d.ts.map +1 -0
- package/dist/cache/index.js +2 -2
- package/dist/cache/stores/memory.js +1 -1
- package/dist/cache/timber-cache.d.ts.map +1 -1
- package/dist/cli.js +3 -3
- package/dist/client/global-context.d.ts +21 -1
- package/dist/client/global-context.d.ts.map +1 -1
- package/dist/client/index.js +3 -12
- package/dist/client/index.js.map +1 -1
- package/dist/client/internal.js +1 -1
- package/dist/client/navigation-context.d.ts.map +1 -1
- package/dist/client/params-context.d.ts.map +1 -1
- package/dist/client/slot-context.d.ts +2 -2
- package/dist/client/slot-context.d.ts.map +1 -1
- package/dist/codec.js +1 -1
- package/dist/cookies/index.js +1 -1
- package/dist/index.js +7 -7
- package/dist/params/index.js +1 -1
- package/dist/plugins/dev-server.d.ts +1 -1
- package/dist/plugins/dev-server.d.ts.map +1 -1
- package/dist/plugins/dev-store-clear.d.ts +28 -0
- package/dist/plugins/dev-store-clear.d.ts.map +1 -0
- package/dist/routing/index.js +2 -2
- package/dist/schema-bridge.d.ts +28 -19
- package/dist/schema-bridge.d.ts.map +1 -1
- package/dist/search-params/define.d.ts +1 -1
- package/dist/search-params/define.d.ts.map +1 -1
- package/dist/search-params/index.js +7 -8
- package/dist/search-params/index.js.map +1 -1
- package/dist/search-params/wrappers.d.ts +3 -3
- package/dist/server/index.js +2 -2
- package/dist/server/internal.js +27 -24
- package/dist/server/internal.js.map +1 -1
- package/dist/server/logger.d.ts +9 -0
- package/dist/server/logger.d.ts.map +1 -1
- package/dist/server/prebuilt/overlay.d.ts +9 -3
- package/dist/server/prebuilt/overlay.d.ts.map +1 -1
- package/dist/server/prebuilt-runtime.d.ts.map +1 -1
- package/docs/api/33-api-search-params.mdx +3 -1
- package/docs/learn/06-typed-params.mdx +2 -2
- package/package.json +1 -1
- package/src/cache/guarded-read.ts +44 -0
- package/src/cache/timber-cache.ts +4 -2
- package/src/client/global-context.ts +42 -14
- package/src/client/navigation-context.ts +4 -11
- package/src/client/params-context.ts +5 -17
- package/src/client/segment-update-context.ts +1 -1
- package/src/client/slot-content-cache-context.ts +1 -1
- package/src/client/slot-context.ts +6 -17
- package/src/plugins/dev-server.ts +37 -3
- package/src/plugins/dev-store-clear.ts +47 -0
- package/src/rsc-runtime/vendor-types.d.ts +8 -0
- package/src/schema-bridge.ts +93 -38
- package/src/search-params/define.ts +5 -6
- package/src/search-params/wrappers.ts +3 -3
- package/src/server/action-handler.ts +18 -2
- package/src/server/logger.ts +9 -0
- package/src/server/prebuilt/overlay.ts +14 -4
- package/src/server/prebuilt-runtime.ts +20 -1
- package/dist/_chunks/cache-api-GE4AOe2H.js.map +0 -1
- package/dist/_chunks/chains-CDK1AWZQ.js +0 -1
- package/dist/_chunks/dev-server-BiWNMBVU.js +0 -1
- package/dist/_chunks/dev-server-DIy-SY-J.js.map +0 -1
- package/dist/_chunks/schema-bridge-C83xa9lT.js.map +0 -1
- package/dist/_chunks/segment-context-xtPUGfdq.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as DEFAULT_MAX_BUFFER_BYTES, d as onAbortUntil, l as teeBufferExceeded, s as createStreamTimingRecorder, t as NODE_BODY, u as wrapResponseWithStreamTiming } from "./node-response-
|
|
2
|
-
import { r as RenderTimeoutError } from "./render-timeout-
|
|
1
|
+
import { a as DEFAULT_MAX_BUFFER_BYTES, d as onAbortUntil, l as teeBufferExceeded, s as createStreamTimingRecorder, t as NODE_BODY, u as wrapResponseWithStreamTiming } from "./node-response-bF0bKoig.js";
|
|
2
|
+
import { r as RenderTimeoutError } from "./render-timeout-Ln_u7fX-.js";
|
|
3
3
|
import { Readable, Transform, pipeline } from "node:stream";
|
|
4
4
|
//#region src/server/node-body-response.ts
|
|
5
5
|
/**
|
|
@@ -515,4 +515,4 @@ function whenNodeFlightReadable(source) {
|
|
|
515
515
|
//#endregion
|
|
516
516
|
export { destroyNodeFlight, nodeFlightResponse, pipeFlightToNode, teeNodeFlight, whenNodeFlightReadable };
|
|
517
517
|
|
|
518
|
-
//# sourceMappingURL=flight-source-node-
|
|
518
|
+
//# sourceMappingURL=flight-source-node-BdHUOUqg.js.map
|
package/dist/_chunks/{flight-source-node-HptmGMT8.js.map → flight-source-node-BdHUOUqg.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flight-source-node-HptmGMT8.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';\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).\n flight.abort(error ?? undefined);\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":";;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xB,OAAO,GAAG,OAAO,KAAK;CACtB,OAAO,GAAG,SAAS,OAAO;CAC1B,OAAO,GAAG,SAAS,OAAO;CAC1B,OAAO;AACT;;;;;;AAOA,SAAS,cAAc,QAA6D;CAClF,IAAI,OAAO,eAAe,OAAO,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
|
+
{"version":3,"file":"flight-source-node-BdHUOUqg.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';\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).\n flight.abort(error ?? undefined);\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);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,OAAO,IAAI,SAAS,OAAO;CAC7B;CACA,OAAO,GAAG,QAAQ,MAAM;CACxB,OAAO,GAAG,OAAO,KAAK;CACtB,OAAO,GAAG,SAAS,OAAO;CAC1B,OAAO,GAAG,SAAS,OAAO;CAC1B,OAAO;AACT;;;;;;AAOA,SAAS,cAAc,QAA6D;CAClF,IAAI,OAAO,eAAe,OAAO,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"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
//#region src/client/global-context.ts
|
|
3
|
+
/**
|
|
4
|
+
* createGlobalContext — a React context with a process-wide singleton identity.
|
|
5
|
+
*
|
|
6
|
+
* SINGLETON GUARANTEE: Uses globalThis + Symbol.for — same pattern as
|
|
7
|
+
* NavigationContext. The RSC client bundler can duplicate a module across
|
|
8
|
+
* chunks (browser-entry graph + client-reference graph). With ESM output,
|
|
9
|
+
* each chunk gets its own module scope — a bare createContext at module
|
|
10
|
+
* level would create separate instances per chunk. globalThis guarantees a
|
|
11
|
+
* single instance regardless of duplication.
|
|
12
|
+
*
|
|
13
|
+
* One context per React instance, not per process. Duplicated chunks share
|
|
14
|
+
* one React, so they share the context. A dev SSR program reload evaluates
|
|
15
|
+
* React and react-dom/server again, in the same process: the new renderer
|
|
16
|
+
* must get a context of its own. Handed the previous one, React logs
|
|
17
|
+
* "Detected multiple renderers concurrently rendering the same context
|
|
18
|
+
* provider" on every client-component edit, and the stale context keeps a
|
|
19
|
+
* piece of the discarded copy alive (TIM-1590).
|
|
20
|
+
*
|
|
21
|
+
* See design/19-client-navigation.md §"Singleton Guarantee via globalThis"
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* The context `key` names for this React instance, created on first use.
|
|
25
|
+
* Pass the key as a `Symbol.for('…')` literal at the call site, so each key
|
|
26
|
+
* stays greppable in the build output (tests/bundle-singleton-audit.test.ts
|
|
27
|
+
* checks `__timber_nav_ctx`).
|
|
28
|
+
*/
|
|
29
|
+
function createGlobalContext(key, defaultValue) {
|
|
30
|
+
return createGlobalContextFor(React, key, defaultValue);
|
|
31
|
+
}
|
|
32
|
+
/** createGlobalContext for a given React instance. Exported for tests. */
|
|
33
|
+
function createGlobalContextFor(react, key, defaultValue) {
|
|
34
|
+
if (typeof react.createContext !== "function") return;
|
|
35
|
+
const slot = Reflect.get(globalThis, key);
|
|
36
|
+
const byReact = slot instanceof WeakMap ? slot : /* @__PURE__ */ new WeakMap();
|
|
37
|
+
if (byReact !== slot) Reflect.set(globalThis, key, byReact);
|
|
38
|
+
let ctx = byReact.get(react);
|
|
39
|
+
if (!ctx) {
|
|
40
|
+
ctx = react.createContext(defaultValue);
|
|
41
|
+
byReact.set(react, ctx);
|
|
42
|
+
}
|
|
43
|
+
return ctx;
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export { createGlobalContext as t };
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=global-context-B9PFncvb.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"global-context-B9PFncvb.js","names":[],"sources":["../../src/client/global-context.ts"],"sourcesContent":["/**\n * createGlobalContext — a React context with a process-wide singleton identity.\n *\n * SINGLETON GUARANTEE: Uses globalThis + Symbol.for — same pattern as\n * NavigationContext. The RSC client bundler can duplicate a module across\n * chunks (browser-entry graph + client-reference graph). With ESM output,\n * each chunk gets its own module scope — a bare createContext at module\n * level would create separate instances per chunk. globalThis guarantees a\n * single instance regardless of duplication.\n *\n * One context per React instance, not per process. Duplicated chunks share\n * one React, so they share the context. A dev SSR program reload evaluates\n * React and react-dom/server again, in the same process: the new renderer\n * must get a context of its own. Handed the previous one, React logs\n * \"Detected multiple renderers concurrently rendering the same context\n * provider\" on every client-component edit, and the stale context keeps a\n * piece of the discarded copy alive (TIM-1590).\n *\n * See design/19-client-navigation.md §\"Singleton Guarantee via globalThis\"\n */\n\nimport React from 'react';\n\n/** The part of a React instance a context comes from. */\nexport interface ContextFactory {\n createContext?: typeof React.createContext;\n}\n\n/**\n * The context `key` names for this React instance, created on first use.\n * Pass the key as a `Symbol.for('…')` literal at the call site, so each key\n * stays greppable in the build output (tests/bundle-singleton-audit.test.ts\n * checks `__timber_nav_ctx`).\n */\nexport function createGlobalContext<T>(key: symbol, defaultValue: T): React.Context<T> {\n return createGlobalContextFor(React, key, defaultValue);\n}\n\n/** createGlobalContext for a given React instance. Exported for tests. */\nexport function createGlobalContextFor<T>(\n react: ContextFactory,\n key: symbol,\n defaultValue: T\n): React.Context<T> {\n if (typeof react.createContext !== 'function') {\n // RSC environment — createContext not available. Return a dummy that\n // won't be used (the consumers only render on the client / during SSR).\n return undefined as unknown as React.Context<T>;\n }\n const slot: unknown = Reflect.get(globalThis, key);\n const byReact = slot instanceof WeakMap ? slot : new WeakMap<object, React.Context<T>>();\n if (byReact !== slot) Reflect.set(globalThis, key, byReact);\n let ctx: React.Context<T> | undefined = byReact.get(react);\n if (!ctx) {\n ctx = react.createContext<T>(defaultValue);\n byReact.set(react, ctx);\n }\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,oBAAuB,KAAa,cAAmC;CACrF,OAAO,uBAAuB,OAAO,KAAK,YAAY;AACxD;;AAGA,SAAgB,uBACd,OACA,KACA,cACkB;CAClB,IAAI,OAAO,MAAM,kBAAkB,YAGjC;CAEF,MAAM,OAAgB,QAAQ,IAAI,YAAY,GAAG;CACjD,MAAM,UAAU,gBAAgB,UAAU,uBAAO,IAAI,QAAkC;CACvF,IAAI,YAAY,MAAM,QAAQ,IAAI,YAAY,KAAK,OAAO;CAC1D,IAAI,MAAoC,QAAQ,IAAI,KAAK;CACzD,IAAI,CAAC,KAAK;EACR,MAAM,MAAM,cAAiB,YAAY;EACzC,QAAQ,IAAI,OAAO,GAAG;CACxB;CACA,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as logLossyCacheValue } from "./logger-CI_hThfy.js";
|
|
2
2
|
//#region src/cache/json-lossy-check.ts
|
|
3
3
|
var LOSSY_TYPES = [
|
|
4
4
|
"Date",
|
|
@@ -63,4 +63,4 @@ function findLossyTypes(value, seen, depth) {
|
|
|
63
63
|
//#endregion
|
|
64
64
|
export { warnLossyJsonValue as t };
|
|
65
65
|
|
|
66
|
-
//# sourceMappingURL=json-lossy-check-
|
|
66
|
+
//# sourceMappingURL=json-lossy-check-C3Sht92C.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-lossy-check-
|
|
1
|
+
{"version":3,"file":"json-lossy-check-C3Sht92C.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
1
|
import { i as scanProjectSourceFiles, t as buildSourceExtensions } from "./scan-BoP17W3w.js";
|
|
2
|
-
import { i as detectDirective, n as classifyModule } from "./classify-
|
|
3
|
-
import { n as stitchImportChains } from "./chains-
|
|
4
|
-
import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "./poison-scan-
|
|
2
|
+
import { i as detectDirective, n as classifyModule } from "./classify-IqzMpxMs.js";
|
|
3
|
+
import { n as stitchImportChains } from "./chains-BchW_AtW.js";
|
|
4
|
+
import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "./poison-scan-DTWIfNgD.js";
|
|
5
5
|
import { normalizePath } from "vite";
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { readFile } from "node:fs/promises";
|
|
@@ -148,4 +148,4 @@ async function classifyLiveProject(ctx) {
|
|
|
148
148
|
//#endregion
|
|
149
149
|
export { classifyLiveFile, classifyLiveProject };
|
|
150
150
|
|
|
151
|
-
//# sourceMappingURL=live-graph-
|
|
151
|
+
//# sourceMappingURL=live-graph-DEu_GWbc.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live-graph-tSWrv8eH.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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G,IAAI;EAC9D,QAAQ;GACN,YAAY;EACd;EACA,MAAM,IAAI,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"}
|
|
1
|
+
{"version":3,"file":"live-graph-DEu_GWbc.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;CAC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,OAAO;EAC9B,IAAI,YAAuB;EAC3B,IAAI;GACF,YAAY,gBAAgB,aAAa,MAAM,MAAM,GAAG,IAAI;EAC9D,QAAQ;GACN,YAAY;EACd;EACA,MAAM,IAAI,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"}
|
|
@@ -640,6 +640,14 @@ function logCacheMiss(data) {
|
|
|
640
640
|
_logger.debug("timber.cache MISS", withTraceContext(data));
|
|
641
641
|
}
|
|
642
642
|
/**
|
|
643
|
+
* Log a cache read that threw or timed out and was served as a miss.
|
|
644
|
+
* Level: warn — the request still succeeds, but a failing store (Redis down,
|
|
645
|
+
* KV erroring) means every read is paying for a live fetch.
|
|
646
|
+
*/
|
|
647
|
+
function logCacheReadFailed(data) {
|
|
648
|
+
_logger.warn("cache read failed — treating as a miss", withTraceContext(data));
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
643
651
|
* Log an intentionally swallowed error. Provides observability into catch
|
|
644
652
|
* blocks that are deliberately empty — the error is consumed, never rethrown.
|
|
645
653
|
*
|
|
@@ -657,6 +665,6 @@ function swallow(err, reason, opts) {
|
|
|
657
665
|
} catch {}
|
|
658
666
|
}
|
|
659
667
|
//#endregion
|
|
660
|
-
export {
|
|
668
|
+
export { getOtelTraceId as A, isDenySignal as C, addSpanEvent as D, isDevMode as E, setSpanAttribute as F, withSpan as I, getTraceId as M, replaceTraceId as N, addSpanEventSync as O, runWithTraceId as P, isControlFlowSignal as S, isDebug as T, logWaitUntilUnsupported as _, logLossyCacheValue as a, DENY_BRAND as b, logProxyError as c, logRequestReceived as d, logRouteError as f, logWaitUntilRejected as g, logSwrRefetchFailed as h, logCsrfRejected as i, getSpanId as j, generateTraceId as k, logRenderError as l, logSlowRequest as m, logCacheMiss as n, logMiddlewareError as o, logRouteSetupError as p, logCacheReadFailed as r, logMiddlewareShortCircuit as s, getLogger as t, logRequestCompleted as u, setLogger as v, isRedirectSignal as w, REDIRECT_BRAND as x, swallow as y };
|
|
661
669
|
|
|
662
|
-
//# sourceMappingURL=logger-
|
|
670
|
+
//# sourceMappingURL=logger-CI_hThfy.js.map
|