@timber-js/app 0.2.0-alpha.219 → 0.2.0-alpha.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/dist/_chunks/chains-CDK1AWZQ.js +1 -0
  2. package/dist/_chunks/{chains-YKZ8WpIW.js → chains-e_Buf9vg.js} +2 -7
  3. package/dist/_chunks/{chains-YKZ8WpIW.js.map → chains-e_Buf9vg.js.map} +1 -1
  4. package/dist/_chunks/{cli-check-D2WtbNqo.js → cli-check-DDwCkeDY.js} +2 -2
  5. package/dist/_chunks/{cli-check-D2WtbNqo.js.map → cli-check-DDwCkeDY.js.map} +1 -1
  6. package/dist/_chunks/cli-context-BJQB6rtF.js +1 -0
  7. package/dist/_chunks/{cli-context-By7k2xVo.js → cli-context-_mPttGGY.js} +3 -3
  8. package/dist/_chunks/{cli-context-By7k2xVo.js.map → cli-context-_mPttGGY.js.map} +1 -1
  9. package/dist/_chunks/{cli-schema-sync-CySLKrO3.js → cli-schema-sync-BdIebmk3.js} +3 -12
  10. package/dist/_chunks/{cli-schema-sync-CySLKrO3.js.map → cli-schema-sync-BdIebmk3.js.map} +1 -1
  11. package/dist/_chunks/cli-schema-sync-CLNfXQDK.js +1 -0
  12. package/dist/_chunks/dev-server-DkytOEG2.js +1 -0
  13. package/dist/_chunks/{dev-server-B8zsT-ee.js → dev-server-DnODXuNM.js} +31 -14
  14. package/dist/_chunks/{dev-server-B8zsT-ee.js.map → dev-server-DnODXuNM.js.map} +1 -1
  15. package/dist/_chunks/flight-source-node-0dE-t3kq.js +519 -0
  16. package/dist/_chunks/flight-source-node-0dE-t3kq.js.map +1 -0
  17. package/dist/_chunks/{live-graph-BhtrZpRd.js → live-graph-tSWrv8eH.js} +2 -2
  18. package/dist/_chunks/{live-graph-BhtrZpRd.js.map → live-graph-tSWrv8eH.js.map} +1 -1
  19. package/dist/_chunks/node-response-Dibufw_b.js +187 -0
  20. package/dist/_chunks/node-response-Dibufw_b.js.map +1 -0
  21. package/dist/_chunks/{plugin-context-BPBPc3lL.js → plugin-context-DxMMvjUt.js} +2 -18
  22. package/dist/_chunks/{plugin-context-BPBPc3lL.js.map → plugin-context-DxMMvjUt.js.map} +1 -1
  23. package/dist/_chunks/plugin-context-uDHFqHHJ.js +1 -0
  24. package/dist/_chunks/{walkers-Ber9bamD.js → walkers-qu8TpiLh.js} +2 -2
  25. package/dist/_chunks/{walkers-Ber9bamD.js.map → walkers-qu8TpiLh.js.map} +1 -1
  26. package/dist/adapters/nitro-preview.d.ts.map +1 -1
  27. package/dist/adapters/nitro.js +40 -1
  28. package/dist/adapters/nitro.js.map +1 -1
  29. package/dist/analyze/crawl-entry.js +2 -2
  30. package/dist/analyze/graph-command.js +3 -3
  31. package/dist/analyze/graph-command.js.map +1 -1
  32. package/dist/cli.js +5 -5
  33. package/dist/cli.js.map +1 -1
  34. package/dist/client/browser-entry/form-state.d.ts.map +1 -1
  35. package/dist/client/browser-entry/index.d.ts +1 -1
  36. package/dist/client/browser-entry/rsc-stream.d.ts +4 -1
  37. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -1
  38. package/dist/client/react-root.d.ts +6 -0
  39. package/dist/client/react-root.d.ts.map +1 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +36 -5
  42. package/dist/index.js.map +1 -1
  43. package/dist/plugins/encryption-runtime.d.ts +13 -0
  44. package/dist/plugins/encryption-runtime.d.ts.map +1 -0
  45. package/dist/plugins/entries.d.ts +1 -0
  46. package/dist/plugins/entries.d.ts.map +1 -1
  47. package/dist/plugins/server-bundle.d.ts +1 -1
  48. package/dist/plugins/server-bundle.d.ts.map +1 -1
  49. package/dist/routing/index.js +1 -1
  50. package/dist/rsc-runtime/encryption-runtime.d.ts +25 -0
  51. package/dist/rsc-runtime/encryption-runtime.d.ts.map +1 -0
  52. package/dist/rsc-runtime/render-flight.d.ts +14 -0
  53. package/dist/rsc-runtime/render-flight.d.ts.map +1 -0
  54. package/dist/rsc-runtime/rsc.d.ts +6 -2
  55. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  56. package/dist/rsc-runtime/ssr.d.ts +6 -12
  57. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  58. package/dist/server/action-handler.d.ts.map +1 -1
  59. package/dist/server/compress.d.ts +2 -0
  60. package/dist/server/compress.d.ts.map +1 -1
  61. package/dist/server/deny-renderer.d.ts +2 -1
  62. package/dist/server/deny-renderer.d.ts.map +1 -1
  63. package/dist/server/flight-injector-core.d.ts +125 -0
  64. package/dist/server/flight-injector-core.d.ts.map +1 -0
  65. package/dist/server/flight-scripts.d.ts +9 -0
  66. package/dist/server/flight-scripts.d.ts.map +1 -1
  67. package/dist/server/flight-source-node.d.ts +105 -0
  68. package/dist/server/flight-source-node.d.ts.map +1 -0
  69. package/dist/server/flight-source.d.ts +136 -0
  70. package/dist/server/flight-source.d.ts.map +1 -0
  71. package/dist/server/head-response.d.ts.map +1 -1
  72. package/dist/server/html-injector-core.d.ts +3 -91
  73. package/dist/server/html-injector-core.d.ts.map +1 -1
  74. package/dist/server/html-injectors.d.ts +5 -17
  75. package/dist/server/html-injectors.d.ts.map +1 -1
  76. package/dist/server/internal.js +78 -138
  77. package/dist/server/internal.js.map +1 -1
  78. package/dist/server/node-body-response.d.ts +55 -0
  79. package/dist/server/node-body-response.d.ts.map +1 -0
  80. package/dist/server/node-response.d.ts +62 -0
  81. package/dist/server/node-response.d.ts.map +1 -0
  82. package/dist/server/node-stream-transforms.d.ts +24 -21
  83. package/dist/server/node-stream-transforms.d.ts.map +1 -1
  84. package/dist/server/node-streams-platform.d.ts +21 -0
  85. package/dist/server/node-streams-platform.d.ts.map +1 -0
  86. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  87. package/dist/server/pipeline.d.ts.map +1 -1
  88. package/dist/server/prebuilt-runtime.d.ts +2 -3
  89. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  90. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  91. package/dist/server/rsc-entry/render-route.d.ts +4 -1
  92. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  93. package/dist/server/rsc-entry/rsc-payload.d.ts +9 -6
  94. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  95. package/dist/server/rsc-entry/rsc-stream.d.ts +9 -4
  96. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  97. package/dist/server/rsc-entry/ssr-bridge.d.ts +2 -1
  98. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  99. package/dist/server/rsc-entry/ssr-renderer.d.ts +2 -1
  100. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  101. package/dist/server/ssr-bridge-types.d.ts +9 -4
  102. package/dist/server/ssr-bridge-types.d.ts.map +1 -1
  103. package/dist/server/ssr-entry.d.ts +8 -5
  104. package/dist/server/ssr-entry.d.ts.map +1 -1
  105. package/dist/server/ssr-render.d.ts +7 -16
  106. package/dist/server/ssr-render.d.ts.map +1 -1
  107. package/dist/server/stream-utils.d.ts +44 -10
  108. package/dist/server/stream-utils.d.ts.map +1 -1
  109. package/dist/shared/flight-base64.d.ts +13 -0
  110. package/dist/shared/flight-base64.d.ts.map +1 -0
  111. package/dist/shared/flight-segment.d.ts +18 -0
  112. package/dist/shared/flight-segment.d.ts.map +1 -0
  113. package/dist/shared/form-state-flight.d.ts +0 -4
  114. package/dist/shared/form-state-flight.d.ts.map +1 -1
  115. package/docs/learn/12-error-handling.mdx +1 -1
  116. package/package.json +1 -1
  117. package/src/adapters/nitro-preview.ts +39 -0
  118. package/src/client/browser-entry/form-state.ts +3 -2
  119. package/src/client/browser-entry/index.ts +14 -8
  120. package/src/client/browser-entry/rsc-stream.ts +14 -14
  121. package/src/client/react-root.ts +25 -2
  122. package/src/index.ts +2 -0
  123. package/src/plugins/encryption-runtime.ts +31 -0
  124. package/src/plugins/entries.ts +1 -1
  125. package/src/plugins/server-bundle.ts +17 -2
  126. package/src/rsc-runtime/encryption-runtime.ts +78 -0
  127. package/src/rsc-runtime/render-flight.ts +26 -0
  128. package/src/rsc-runtime/rsc.ts +7 -4
  129. package/src/rsc-runtime/ssr.ts +10 -48
  130. package/src/rsc-runtime/vendor-types.d.ts +31 -2
  131. package/src/server/action-handler.ts +43 -44
  132. package/src/server/compress.ts +49 -12
  133. package/src/server/deny-renderer.ts +14 -7
  134. package/src/server/flight-injector-core.ts +328 -0
  135. package/src/server/flight-scripts.ts +14 -2
  136. package/src/server/flight-source-node.ts +430 -0
  137. package/src/server/flight-source.ts +288 -0
  138. package/src/server/form-state-flight.ts +4 -4
  139. package/src/server/head-response.ts +6 -10
  140. package/src/server/html-injector-core.ts +24 -216
  141. package/src/server/html-injectors.ts +12 -71
  142. package/src/server/node-body-response.ts +236 -0
  143. package/src/server/node-response.ts +93 -0
  144. package/src/server/node-stream-transforms.ts +70 -53
  145. package/src/server/node-streams-platform.ts +23 -0
  146. package/src/server/pipeline-helpers.ts +3 -1
  147. package/src/server/pipeline.ts +14 -6
  148. package/src/server/prebuilt/capture-render.ts +5 -5
  149. package/src/server/prebuilt-runtime.ts +7 -10
  150. package/src/server/rsc-entry/error-renderer.ts +8 -4
  151. package/src/server/rsc-entry/index.ts +4 -2
  152. package/src/server/rsc-entry/render-route.ts +5 -2
  153. package/src/server/rsc-entry/rsc-payload.ts +52 -73
  154. package/src/server/rsc-entry/rsc-stream.ts +102 -106
  155. package/src/server/rsc-entry/ssr-bridge.ts +32 -10
  156. package/src/server/rsc-entry/ssr-renderer.ts +15 -18
  157. package/src/server/ssr-bridge-types.ts +10 -4
  158. package/src/server/ssr-entry.ts +56 -52
  159. package/src/server/ssr-render.ts +41 -76
  160. package/src/server/stream-utils.ts +125 -70
  161. package/src/shared/flight-base64.ts +23 -0
  162. package/src/shared/flight-segment.ts +35 -0
  163. package/src/shared/form-state-flight.ts +0 -15
  164. package/dist/_chunks/rolldown-runtime-D7D4PA-g.js +0 -13
@@ -10,55 +10,17 @@
10
10
  * point, not abstraction.
11
11
  */
12
12
 
13
- export { createFromReadableStream } from '@vitejs/plugin-rsc/ssr';
14
-
15
- // ─── Node.js Stream Path ─────────────────────────────────────────────────────
16
- //
17
- // On Node.js, createFromNodeStream reads RSC Flight data from a Node.js
18
- // Readable (C++ backed) instead of a Web ReadableStream (JS reimplementation).
19
- // Eliminates Promise-per-chunk overhead on the SSR decode path.
20
- //
21
- // The plugin only exports createFromReadableStream (via client.edge.js).
22
- // createFromNodeStream lives in the vendored client.node.js. We import it
23
- // directly and wire up the same serverConsumerManifest the plugin uses.
24
-
25
- import { createServerConsumerManifest } from '@vitejs/plugin-rsc/ssr';
26
-
27
- type CreateFromNodeStreamFn = (
28
- stream: import('node:stream').Readable,
29
- manifest: ReturnType<typeof createServerConsumerManifest>,
30
- options?: Record<string, unknown>
31
- ) => React.ReactNode;
32
-
33
- let _createFromNodeStream: CreateFromNodeStreamFn | null = null;
13
+ import { nodeStreamsPlatform } from '../server/node-streams-platform.ts';
34
14
 
35
- try {
36
- if (typeof process !== 'undefined' && process.release?.name === 'node') {
37
- const clientNode = await import('@vitejs/plugin-rsc/vendor/react-server-dom/client.node');
38
- if (typeof clientNode.createFromNodeStream === 'function') {
39
- _createFromNodeStream = clientNode.createFromNodeStream;
40
- }
41
- }
42
- } catch {
43
- // Not available — fall back to createFromReadableStream
44
- }
15
+ export { createFromReadableStream } from '@vitejs/plugin-rsc/ssr';
45
16
 
46
17
  /**
47
- * Decode an RSC Flight stream from a Node.js Readable.
48
- *
49
- * Uses the vendored createFromNodeStream which reads via Node.js native
50
- * streams (C++ libuv) instead of Web ReadableStream (JS Promise per chunk).
51
- *
52
- * Returns null if createFromNodeStream isn't available (CF Workers, etc),
53
- * signaling the caller to use createFromReadableStream instead.
18
+ * Decode a Node Flight source (`server/flight-source.ts`) for SSR — plugin-rsc's
19
+ * `ssr.node` entry, which reads a Node `Readable`, string chunks included.
20
+ * `null` off Node, where every Flight source is a Web stream. Loaded behind
21
+ * the platform probe `renderFlight` (`rsc.ts`) reads, so it exists exactly
22
+ * when the RSC side renders Node sources.
54
23
  */
55
- export function createFromNodeStream(
56
- stream: import('node:stream').Readable,
57
- options?: { nonce?: string }
58
- ): React.ReactNode | null {
59
- if (!_createFromNodeStream) return null;
60
- return _createFromNodeStream(stream, createServerConsumerManifest(), options);
61
- }
62
-
63
- /** Whether the Node.js stream RSC decode path is available. */
64
- export const hasNodeStreamDecode = _createFromNodeStream !== null;
24
+ export const createFromNodeStream = nodeStreamsPlatform
25
+ ? (await import('@vitejs/plugin-rsc/ssr.node')).createFromNodeStream
26
+ : null;
@@ -1,9 +1,38 @@
1
+ // plugin-rsc's build-time encryption key (rsc:encryption-key plugin): a
2
+ // function returning the base64 AES key, read by encryption-runtime.ts.
3
+ declare module 'virtual:vite-rsc/encryption-key' {
4
+ const encryptionKey: () => string | Promise<string>;
5
+ export default encryptionKey;
6
+ }
7
+
8
+ // src renders through plugin-rsc's wrappers (rsc-runtime/rsc.ts); tests stand
9
+ // in the vendored servers for them, with an empty client manifest.
10
+ declare module '@vitejs/plugin-rsc/vendor/react-server-dom/server.node' {
11
+ export function renderToPipeableStream(
12
+ model: unknown,
13
+ manifest: unknown,
14
+ options?: {
15
+ onError?: (error: unknown) => string | void;
16
+ identifierPrefix?: string;
17
+ temporaryReferences?: unknown;
18
+ debugChannel?: import('node:stream').Readable | import('node:stream').Writable;
19
+ }
20
+ ): { pipe<T extends NodeJS.WritableStream>(destination: T): T; abort(reason?: unknown): void };
21
+ }
22
+
23
+ // src decodes Node Flight sources through plugin-rsc's ssr.node wrapper; tests
24
+ // decode them with the vendored client directly, as SSR does on Node.
1
25
  declare module '@vitejs/plugin-rsc/vendor/react-server-dom/client.node' {
2
26
  export function createFromNodeStream(
3
27
  stream: import('node:stream').Readable,
4
28
  manifest: unknown,
5
- options?: Record<string, unknown>
6
- ): React.ReactNode;
29
+ options?: {
30
+ nonce?: string;
31
+ encodeFormAction?: unknown;
32
+ unstable_allowPartialStream?: boolean;
33
+ debugChannel?: import('node:stream').Readable;
34
+ }
35
+ ): PromiseLike<unknown>;
7
36
  }
8
37
 
9
38
  declare module '@vitejs/plugin-rsc/vendor/react-server-dom/server.edge' {
@@ -19,8 +19,10 @@ import {
19
19
  decodeReply,
20
20
  decodeAction,
21
21
  decodeFormState,
22
- renderToReadableStream,
22
+ renderFlight,
23
23
  } from '../rsc-runtime/rsc.ts';
24
+ import { flightChunkBytes, flightResponse, openFlightReader } from './flight-source.ts';
25
+ import { concatBytes } from './stream-utils.ts';
24
26
 
25
27
  import { validateCsrf, csrfRejectionResponse, type CsrfConfig } from './csrf.ts';
26
28
  import { isDenySignal, isRedirectSignal } from './signal-identity.ts';
@@ -159,8 +161,11 @@ export async function handleActionRequest(
159
161
  applyReloadHeaders(reloadHeaders);
160
162
  // Return the reload signal as an RSC stream so createFromFetch can
161
163
  // decode it. The client checks X-Timber-Reload before processing.
162
- const rscStream = renderToReadableStream({ _versionSkew: true });
163
- return new Response(rscStream, { status: 200, headers: reloadHeaders });
164
+ return flightPayloadResponse(
165
+ req,
166
+ { _versionSkew: true },
167
+ { status: 200, headers: reloadHeaders }
168
+ );
164
169
  }
165
170
 
166
171
  // CSRF validation — reject cross-origin mutation requests.
@@ -308,13 +313,12 @@ async function rejectedActionResponse(req: Request, error: unknown): Promise<Res
308
313
  // Flight subscribes when it renders the root, after this tick; the no-op
309
314
  // handler keeps the rejection from being reported as unhandled first.
310
315
  rejection.catch(() => {});
311
- const rscStream = renderToReadableStream(rejection, {
312
- onError: () => encodeErrorDigest({ message: clientErrorMessage(error), errorId }),
313
- });
314
- return new Response(rscStream, {
315
- status: 500,
316
- headers: { 'Content-Type': RSC_CONTENT_TYPE },
317
- });
316
+ return flightPayloadResponse(
317
+ req,
318
+ rejection,
319
+ { status: 500, headers: { 'Content-Type': RSC_CONTENT_TYPE } },
320
+ { onError: () => encodeErrorDigest({ message: clientErrorMessage(error), errorId }) }
321
+ );
318
322
  }
319
323
 
320
324
  /**
@@ -412,7 +416,6 @@ async function handleRscAction(
412
416
  _redirect: result.redirectTo,
413
417
  _status: result.redirectStatus ?? 302,
414
418
  };
415
- const rscStream = renderToReadableStream(redirectPayload);
416
419
  const redirectHeaders: Record<string, string> = {
417
420
  'Content-Type': RSC_CONTENT_TYPE,
418
421
  'X-Timber-Redirect': result.redirectTo,
@@ -420,12 +423,12 @@ async function handleRscAction(
420
423
  if (result.onlyOtherPagesNamed) {
421
424
  redirectHeaders['X-Timber-Invalidated'] = '1';
422
425
  }
423
- return new Response(rscStream, { status: 200, headers: redirectHeaders });
426
+ return flightPayloadResponse(req, redirectPayload, { status: 200, headers: redirectHeaders });
424
427
  }
425
428
 
426
429
  // Render the action result as an RSC stream.
427
430
  // When revalidatePath was called, piggyback the revalidated element tree
428
- // alongside the action result in a single renderToReadableStream call.
431
+ // alongside the action result in a single Flight render.
429
432
  // The client detects the X-Timber-Revalidation header and unpacks both.
430
433
  const headers: Record<string, string> = {
431
434
  'Content-Type': RSC_CONTENT_TYPE,
@@ -449,7 +452,7 @@ async function handleRscAction(
449
452
  };
450
453
 
451
454
  // TIM-1366: access.ts deny signals fire during serialization (inside
452
- // AccessGate during renderToReadableStream), not during buildRouteElement.
455
+ // AccessGate during the Flight render), not during buildRouteElement.
453
456
  // Buffer the stream and track errors so we can drop the revalidation
454
457
  // cleanly instead of shipping a broken flight stream. Access runs
455
458
  // exactly once — during the real render — preserving TIM-1363.
@@ -466,7 +469,7 @@ async function handleRscAction(
466
469
  // (TIM-1529).
467
470
  const rscStream = runWithReactCacheScope(
468
471
  () =>
469
- renderToReadableStream(revalidationPayload, {
472
+ renderFlight(revalidationPayload, {
470
473
  signal: req.signal,
471
474
  onError(error: unknown) {
472
475
  // ??= keeps the first signal (shallowest AccessGate in top-down render).
@@ -495,32 +498,31 @@ async function handleRscAction(
495
498
  // overall deadline; the loop stops at the first chunk after onError
496
499
  // records a signal (the payload is dropped then); and the catch below
497
500
  // branches on RenderTimeoutError, which the helper does not throw.
498
- const reader = rscStream.getReader();
501
+ const reader = openFlightReader(rscStream);
499
502
  const chunks: Uint8Array[] = [];
500
503
  const drainTimeoutMs = DEFAULT_RENDER_TIMEOUT_MS;
501
504
  try {
502
505
  for (;;) {
503
- const { done, value } = await withTimeout(
506
+ const result = await withTimeout(
504
507
  reader.read(),
505
508
  drainTimeoutMs,
506
509
  'revalidation stream drain timed out'
507
510
  );
508
- if (done) break;
509
- chunks.push(value);
511
+ if (result.done) break;
512
+ chunks.push(flightChunkBytes(result.value));
510
513
  if (serializationSignal) {
511
- reader.cancel().catch(() => {});
514
+ reader.cancel();
512
515
  break;
513
516
  }
514
517
  }
515
518
  } catch (drainError) {
516
- reader.cancel().catch(() => {});
519
+ reader.cancel();
517
520
  if (drainError instanceof RenderTimeoutError) {
518
521
  console.error('[timber] revalidatePath dropped — stream drain timed out');
519
522
  // A revalidated tree that never finished rendering is a failure,
520
523
  // even though the action result still ships.
521
524
  await reportRevalidationErrors(req, [...serializationErrors, drainError]);
522
- const fallbackStream = renderToReadableStream(result.actionResult);
523
- return new Response(fallbackStream, { status: 200, headers });
525
+ return flightPayloadResponse(req, result.actionResult, { status: 200, headers });
524
526
  }
525
527
  await reportRevalidationErrors(req, serializationErrors);
526
528
  throw drainError;
@@ -533,8 +535,7 @@ async function handleRscAction(
533
535
  _redirect: serializationSignal.location,
534
536
  _status: serializationSignal.status,
535
537
  };
536
- const redirectStream = renderToReadableStream(redirectPayload);
537
- return new Response(redirectStream, {
538
+ return flightPayloadResponse(req, redirectPayload, {
538
539
  status: 200,
539
540
  headers: {
540
541
  'Content-Type': RSC_CONTENT_TYPE,
@@ -548,39 +549,37 @@ async function handleRscAction(
548
549
  `[timber] revalidatePath dropped — access denied during render (status ${serializationSignal.status})`
549
550
  );
550
551
  }
551
- const fallbackStream = renderToReadableStream(result.actionResult);
552
- return new Response(fallbackStream, { status: 200, headers });
552
+ return flightPayloadResponse(req, result.actionResult, { status: 200, headers });
553
553
  }
554
554
 
555
555
  // Clean serialization — return the buffered bytes with revalidation header.
556
556
  headers['X-Timber-Revalidation'] = '1';
557
- const buffered = concatUint8Arrays(chunks);
557
+ const buffered = concatBytes(chunks);
558
558
  return new Response(buffered.buffer as ArrayBuffer, {
559
559
  status: 200,
560
560
  headers,
561
561
  });
562
562
  }
563
563
 
564
- const rscStream = renderToReadableStream(result.actionResult);
565
-
566
- return new Response(rscStream, {
567
- status: 200,
568
- headers,
569
- });
564
+ return flightPayloadResponse(req, result.actionResult, { status: 200, headers });
570
565
  }
571
566
 
572
567
  // ─── Helpers ─────────────────────────────────────────────────────────────
573
568
 
574
- function concatUint8Arrays(chunks: Uint8Array[]): Uint8Array {
575
- let total = 0;
576
- for (const c of chunks) total += c.byteLength;
577
- const out = new Uint8Array(total);
578
- let offset = 0;
579
- for (const c of chunks) {
580
- out.set(c, offset);
581
- offset += c.byteLength;
582
- }
583
- return out;
569
+ /**
570
+ * A Flight payload response: the model rendered by `renderFlight`, sent
571
+ * through `flightResponse` (a Node body on Node, to the socket as is). The render
572
+ * stops when the client disconnects (`req.signal`) or, on Node, at the
573
+ * render deadline: an action result holding a promise that never settles
574
+ * would otherwise stream for as long as the client stays connected.
575
+ */
576
+ function flightPayloadResponse(
577
+ req: Request,
578
+ model: unknown,
579
+ init: ResponseInit,
580
+ options?: { onError?: (error: unknown) => string | void }
581
+ ): Response {
582
+ return flightResponse(renderFlight(model, { ...options, signal: req.signal }), init);
584
583
  }
585
584
 
586
585
  // ─── No-JS Form Action ───────────────────────────────────────────────────
@@ -1,6 +1,6 @@
1
1
  // Response compression for self-hosted deployments (dev server, Nitro preview).
2
2
  //
3
- // Uses CompressionStream (Web Platform API) for gzip. Brotli is intentionally
3
+ // Gzips with node:zlib, flushing per chunk; a Node body stays a Node stream. Brotli is intentionally
4
4
  // left to CDNs and reverse proxies — at streaming-friendly quality levels its
5
5
  // ratio advantage is marginal, and node:zlib's brotli transform buffers output
6
6
  // internally, breaking streaming. Cloudflare Workers auto-compress at the edge —
@@ -102,8 +102,11 @@ export function negotiateEncoding(acceptEncoding: string): 'gzip' | null {
102
102
  * - SSE streams (text/event-stream — must not be buffered)
103
103
  */
104
104
  export function shouldCompress(response: Response): boolean {
105
- // No body to compress
106
- if (!response.body) return false;
105
+ // No body to compress. A Node-body response is asked whether it owns one
106
+ // (a null-body status does not) without reading `.body`, which would
107
+ // convert it to a Web stream.
108
+ const nodeBody = nodeBodyThrough(response);
109
+ if (nodeBody ? !nodeBody.hasBody : !response.body) return false;
107
110
  if (NO_COMPRESS_STATUSES.has(response.status)) return false;
108
111
 
109
112
  // Already compressed
@@ -142,9 +145,6 @@ export function compressResponse(request: Request, response: Response): Response
142
145
  const encoding = negotiateEncoding(acceptEncoding);
143
146
  if (!encoding) return response;
144
147
 
145
- // Compress the body stream with gzip via the Web Platform CompressionStream API.
146
- const compressedBody = compressWithGzip(response.body!);
147
-
148
148
  // Build new headers: copy originals, add compression headers, remove Content-Length
149
149
  // (compressed size is unknown until streaming completes).
150
150
  const headers = new Headers(response.headers);
@@ -161,11 +161,43 @@ export function compressResponse(request: Request, response: Response): Response
161
161
  headers.set('Vary', 'Accept-Encoding');
162
162
  }
163
163
 
164
- return new Response(compressedBody, {
165
- status: response.status,
166
- statusText: response.statusText,
167
- headers,
168
- });
164
+ const init = { status: response.status, statusText: response.statusText, headers };
165
+ // A Node body is gzipped as a Node stream and stays one to the socket.
166
+ const nodeBody = nodeBodyThrough(response);
167
+ if (nodeBody) return nodeBody.through(createSyncFlushGzip(), init);
168
+ return new Response(compressWithGzip(response.body!), init);
169
+ }
170
+
171
+ // ─── Node bodies ──────────────────────────────────────────────────────────
172
+ //
173
+ // A response with a Node body (SSR and Flight payloads on Node) carries its
174
+ // operations under a registry symbol (server/node-response.ts). This module is
175
+ // emitted standalone and cannot import that one, so it repeats the key;
176
+ // tests/node-body-response.test.ts holds the two to the same string.
177
+
178
+ /** Registry key of the Node-body brand; must equal `NODE_BODY` in node-response.ts. */
179
+ export const NODE_BODY_KEY = 'timber.response.nodeBody';
180
+
181
+ /** The Node-body operations compression needs. */
182
+ interface NodeBodyThrough {
183
+ readonly hasBody: boolean;
184
+ through(stream: import('node:stream').Duplex, init: ResponseInit): Response;
185
+ }
186
+
187
+ function isNodeBodyThrough(value: unknown): value is NodeBodyThrough {
188
+ return (
189
+ typeof value === 'object' &&
190
+ value !== null &&
191
+ 'through' in value &&
192
+ typeof value.through === 'function' &&
193
+ 'hasBody' in value &&
194
+ typeof value.hasBody === 'boolean'
195
+ );
196
+ }
197
+
198
+ function nodeBodyThrough(response: Response): NodeBodyThrough | null {
199
+ const ops: unknown = Reflect.get(response, Symbol.for(NODE_BODY_KEY));
200
+ return isNodeBodyThrough(ops) ? ops : null;
169
201
  }
170
202
 
171
203
  // ─── Gzip (node:zlib with Z_SYNC_FLUSH) ──────────────────────────────────
@@ -184,6 +216,11 @@ export function compressResponse(request: Request, response: Response): Response
184
216
  import { createGzip, constants } from 'node:zlib';
185
217
  import { Readable, pipeline } from 'node:stream';
186
218
 
219
+ /** gzip that flushes every chunk as it arrives. */
220
+ function createSyncFlushGzip(): ReturnType<typeof createGzip> {
221
+ return createGzip({ flush: constants.Z_SYNC_FLUSH });
222
+ }
223
+
187
224
  /**
188
225
  * Compress a ReadableStream with gzip, flushing each chunk immediately.
189
226
  *
@@ -192,7 +229,7 @@ import { Readable, pipeline } from 'node:stream';
192
229
  * as soon as it's available — preserving streaming semantics.
193
230
  */
194
231
  function compressWithGzip(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {
195
- const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });
232
+ const gzip = createSyncFlushGzip();
196
233
  const nodeInput = Readable.fromWeb(body as import('stream/web').ReadableStream);
197
234
 
198
235
  // pipeline() instead of bare pipe(): pipe() does not forward source errors,
@@ -16,7 +16,7 @@
16
16
  */
17
17
 
18
18
  import { createElement, Fragment } from 'react';
19
- import { renderToReadableStream } from '../rsc-runtime/rsc.ts';
19
+ import { renderFlight } from '../rsc-runtime/rsc.ts';
20
20
 
21
21
  import { DenySignal } from './primitives.ts';
22
22
  import { appVisibleSearch } from '../shared/rsc-cache-key.ts';
@@ -39,7 +39,12 @@ import { flightInitScript } from './flight-scripts.ts';
39
39
  import { getCspNonce } from './csp-nonce.ts';
40
40
  import type { ClientBootstrapConfig } from './html-injectors.ts';
41
41
  import type { Metadata } from './types.ts';
42
- import { teeWithErrorPropagation } from './stream-utils.ts';
42
+ import {
43
+ cancelFlightSource,
44
+ flightResponse,
45
+ teeFlightSource,
46
+ type FlightSource,
47
+ } from './flight-source.ts';
43
48
  import { RSC_CONTENT_TYPE } from '../shared/rsc-media-type.ts';
44
49
 
45
50
  /** Layout component entry for deny page wrapping. */
@@ -50,7 +55,7 @@ export interface LayoutEntry {
50
55
 
51
56
  /** Callback to pass RSC stream to SSR for HTML rendering. */
52
57
  export type CallSsrFn = (
53
- rscStream: ReadableStream<Uint8Array>,
58
+ rscSource: FlightSource,
54
59
  navContext: NavContext
55
60
  ) => Promise<SsrRenderResult>;
56
61
 
@@ -207,14 +212,14 @@ export async function renderDenyPage(
207
212
  }
208
213
 
209
214
  // Render the error page to a fresh RSC Flight stream.
210
- const rscStream = renderToReadableStream(withPublishedParams(element), {
215
+ const rscStream = renderFlight(withPublishedParams(element), {
211
216
  signal: req.signal,
212
217
  onError(error: unknown) {
213
218
  reportRenderError(error, req, { segments });
214
219
  },
215
220
  });
216
221
 
217
- const [ssrStream, inlineStream] = teeWithErrorPropagation(rscStream);
222
+ const [ssrStream, inlineStream] = teeFlightSource(rscStream);
218
223
 
219
224
  const denyUrl = new URL(req.url);
220
225
  const nonce = getCspNonce();
@@ -240,6 +245,8 @@ export async function renderDenyPage(
240
245
  // go on (TIM-1258).
241
246
  return (await callSsr(ssrStream, navContext)).response;
242
247
  } catch (renderError) {
248
+ // Nothing will read the inline branch now; release the render.
249
+ cancelFlightSource(inlineStream);
243
250
  logRenderError({ method: req.method, path: new URL(req.url).pathname, error: renderError });
244
251
  return defaultStatusPageResponse(deny.status, responseHeaders);
245
252
  }
@@ -304,7 +311,7 @@ export async function renderDenyPageAsRsc(
304
311
  element = h(component, null, element);
305
312
  }
306
313
 
307
- const rscStream = renderToReadableStream(withPublishedParams(element), {
314
+ const rscStream = renderFlight(withPublishedParams(element), {
308
315
  signal: req.signal,
309
316
  onError(error: unknown) {
310
317
  reportRenderError(error, req);
@@ -316,7 +323,7 @@ export async function renderDenyPageAsRsc(
316
323
  // the client router — the only reader of this status — renders what it is
317
324
  // sent. See design/04-authorization.md §"Status codes on the RSC payload
318
325
  // path" (TIM-1495).
319
- return new Response(rscStream, {
326
+ return flightResponse(rscStream, {
320
327
  status: 200,
321
328
  headers: responseHeaders,
322
329
  });