@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
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * RSC Stream Renderer — Creates the RSC Flight stream with signal tracking.
3
3
  *
4
- * Wraps `renderToReadableStream` from `@vitejs/plugin-rsc/rsc` and captures
4
+ * Renders through `renderFlight` (`rsc-runtime/rsc.ts`) and captures
5
5
  * render-phase signals (DenySignal, RedirectSignal) thrown by
6
6
  * components during streaming. These signals are tracked in a shared
7
7
  * read-only `RenderSignals` object so the caller can decide the HTTP response.
@@ -10,7 +10,8 @@
10
10
  * 13-security.md §"Errors don't leak"
11
11
  */
12
12
 
13
- import { renderToReadableStream } from '../../rsc-runtime/rsc.ts';
13
+ import { renderFlight } from '../../rsc-runtime/rsc.ts';
14
+ import type { FlightSource } from '../flight-source.ts';
14
15
  import type { RscPayloadRoot } from '../../shared/payload-root.ts';
15
16
  import { encodeErrorDigest } from '../../shared/error-digest.ts';
16
17
 
@@ -28,12 +29,12 @@ import { createSignalRecorder, type RenderSignals } from './render-signals.ts';
28
29
  import { isDebug } from '../debug.ts';
29
30
 
30
31
  export interface RscStreamResult {
31
- rscStream: ReadableStream<Uint8Array>;
32
+ rscStream: FlightSource;
32
33
  signals: RenderSignals;
33
34
  }
34
35
 
35
36
  /**
36
- * Render a payload root (tree plus its params) to an RSC Flight stream.
37
+ * Render a payload root (tree plus its params) to a Flight source.
37
38
  *
38
39
  * The stream serializes server components as rendered output and client
39
40
  * components ("use client") as serialized references with module ID + export name.
@@ -42,122 +43,117 @@ export interface RscStreamResult {
42
43
  * handle. Every one arrives through `onError`, never as a throw from this
43
44
  * call: Flight starts rendering in a microtask after the stream is created,
44
45
  * so even a component that throws synchronously is reported asynchronously.
46
+ *
47
+ * The render is aborted when the client disconnects and, on Node, once
48
+ * `renderTimeoutMs` passes with it still running (design/02 §"Always Wire
49
+ * abort() to Both Request Signal AND Timeout").
45
50
  */
46
51
  export function renderRscStream(
47
52
  payload: RscPayloadRoot,
48
53
  req: Request,
54
+ renderTimeoutMs: number,
49
55
  leafDenyChain?: DenyPageEntry[]
50
56
  ): RscStreamResult {
51
57
  const recorder = createSignalRecorder();
52
58
 
53
- const rscStream = renderToReadableStream(
54
- payload,
55
- {
56
- signal: req.signal,
57
- onError(error: unknown) {
58
- // Connection abort (user refreshed or navigated away) — suppress.
59
- // Not an application error; no need to track or log.
60
- if (isAbortError(error) || req.signal?.aborted) return;
61
- if (isDenySignal(error)) {
62
- // Late addressing (TIM-1450): a nested-component deny escapes
63
- // all in-tree catch sites and arrives here without owners.
64
- // Resolve it against the leaf deny chain and stamp the full
65
- // candidate list so the client can find the first reachable
66
- // owner via its ancestry context.
67
- if (!error.owners && leafDenyChain) {
68
- const entries = matchDenyEntries(leafDenyChain, error.status);
69
- if (entries.length > 0) {
70
- error.owners = entries.map((e) => e.ownerKey);
71
- }
59
+ const rscStream = renderFlight(payload, {
60
+ signal: req.signal,
61
+ timeoutMs: renderTimeoutMs,
62
+ onError(error: unknown) {
63
+ // Connection abort (user refreshed or navigated away) — suppress.
64
+ // Not an application error; no need to track or log.
65
+ if (isAbortError(error) || req.signal?.aborted) return;
66
+ if (isDenySignal(error)) {
67
+ // Late addressing (TIM-1450): a nested-component deny escapes
68
+ // all in-tree catch sites and arrives here without owners.
69
+ // Resolve it against the leaf deny chain and stamp the full
70
+ // candidate list so the client can find the first reachable
71
+ // owner via its ancestry context.
72
+ if (!error.owners && leafDenyChain) {
73
+ const entries = matchDenyEntries(leafDenyChain, error.status);
74
+ if (entries.length > 0) {
75
+ error.owners = entries.map((e) => e.ownerKey);
72
76
  }
73
- recorder.deny(error);
74
- return JSON.stringify({
75
- type: 'deny',
76
- status: error.status,
77
- data: error.data,
78
- owners: error.owners,
79
- });
80
- }
81
- if (isRedirectSignal(error)) {
82
- recorder.redirect(error);
83
- return JSON.stringify({
84
- type: 'redirect',
85
- location: error.location,
86
- status: error.status,
87
- });
88
- }
89
- // Dev diagnostic: detect "Invalid hook call" errors which indicate
90
- // a 'use client' component is being executed during RSC rendering
91
- // instead of being serialized as a client reference. This happens when
92
- // the RSC plugin's transform doesn't detect the directive — e.g., the
93
- // directive isn't at the very top of the file, or the component is
94
- // re-exported through a barrel file without 'use client'.
95
- // See LOCAL-297.
96
- if (isDebug() && error instanceof Error && error.message.includes('Invalid hook call')) {
97
- console.error(
98
- '[timber] A React hook was called during RSC rendering. This usually means a ' +
99
- "'use client' component is being executed as a server component instead of " +
100
- 'being serialized as a client reference.\n\n' +
101
- 'Common causes:\n' +
102
- " 1. The 'use client' directive is not the FIRST statement in the file (before any imports)\n" +
103
- " 2. The component is re-exported through a barrel file (index.ts) that lacks 'use client'\n" +
104
- ' 3. @vitejs/plugin-rsc is not loaded or is misconfigured\n\n' +
105
- `Request: ${req.method} ${new URL(req.url).pathname}`
106
- );
107
77
  }
78
+ recorder.deny(error);
79
+ return JSON.stringify({
80
+ type: 'deny',
81
+ status: error.status,
82
+ data: error.data,
83
+ owners: error.owners,
84
+ });
85
+ }
86
+ if (isRedirectSignal(error)) {
87
+ recorder.redirect(error);
88
+ return JSON.stringify({
89
+ type: 'redirect',
90
+ location: error.location,
91
+ status: error.status,
92
+ });
93
+ }
94
+ // Dev diagnostic: detect "Invalid hook call" errors which indicate
95
+ // a 'use client' component is being executed during RSC rendering
96
+ // instead of being serialized as a client reference. This happens when
97
+ // the RSC plugin's transform doesn't detect the directive — e.g., the
98
+ // directive isn't at the very top of the file, or the component is
99
+ // re-exported through a barrel file without 'use client'.
100
+ // See LOCAL-297.
101
+ if (isDebug() && error instanceof Error && error.message.includes('Invalid hook call')) {
102
+ console.error(
103
+ '[timber] A React hook was called during RSC rendering. This usually means a ' +
104
+ "'use client' component is being executed as a server component instead of " +
105
+ 'being serialized as a client reference.\n\n' +
106
+ 'Common causes:\n' +
107
+ " 1. The 'use client' directive is not the FIRST statement in the file (before any imports)\n" +
108
+ " 2. The component is re-exported through a barrel file (index.ts) that lacks 'use client'\n" +
109
+ ' 3. @vitejs/plugin-rsc is not loaded or is misconfigured\n\n' +
110
+ `Request: ${req.method} ${new URL(req.url).pathname}`
111
+ );
112
+ }
108
113
 
109
- // Dev-mode: detect non-serializable RSC props and provide
110
- // actionable fix suggestions (TIM-358).
111
- // checkAndWarnRscPropError no-ops in production internally.
112
- if (error instanceof Error) {
113
- checkAndWarnRscPropError(error, new URL(req.url).pathname);
114
- }
114
+ // Dev-mode: detect non-serializable RSC props and provide
115
+ // actionable fix suggestions (TIM-358).
116
+ // checkAndWarnRscPropError no-ops in production internally.
117
+ if (error instanceof Error) {
118
+ checkAndWarnRscPropError(error, new URL(req.url).pathname);
119
+ }
115
120
 
116
- // Log the error but do NOT track it as a page-level signal. If this
117
- // error is inside a <Suspense> boundary, React will emit an error
118
- // row in the Flight stream and the nearest error boundary renders
119
- // it on the client; treating it as page-level would turn a page
120
- // whose shell rendered into a 500. See TIM-524. An error no
121
- // boundary contains fails SSR's shell instead, and the SSR renderer
122
- // answers that with the error page.
123
- recorder.unhandledError();
121
+ // Log the error but do NOT track it as a page-level signal. If this
122
+ // error is inside a <Suspense> boundary, React will emit an error
123
+ // row in the Flight stream and the nearest error boundary renders
124
+ // it on the client; treating it as page-level would turn a page
125
+ // whose shell rendered into a 500. See TIM-524. An error no
126
+ // boundary contains fails SSR's shell instead, and the SSR renderer
127
+ // answers that with the error page.
128
+ recorder.unhandledError();
124
129
 
125
- // Return a digest so React emits a per-row error in the Flight
126
- // stream instead of leaving the lazy reference unresolved.
127
- //
128
- // SECURITY: Never include error.message in the digest — it may
129
- // contain SQL queries, filesystem paths, secret fragments, or
130
- // internal IDs. Use a generic message with a correlation ID so
131
- // the error can be matched to server logs. The ID is the `digest`
132
- // prop error pages receive (shared/error-digest.ts).
133
- // See design/13-security.md §"Errors don't leak".
134
- //
135
- // This is the error's one log and one `onRequestError` report,
136
- // whether a Suspense boundary contains it or it crashes the shell
137
- // and the renderer answers with the error page (design/49
138
- // §"Deferred: render-error handoff").
139
- //
140
- // The one exception is a no-JS action's error, rendered in place of
141
- // the page (route-element-builder.ts): the action already logged and
142
- // reported it, so it keeps that log line's ID and is not reported
143
- // twice.
144
- const actionError = getActionErrorForRender();
145
- const errorId =
146
- actionError && actionError.error === error
147
- ? actionError.errorId
148
- : reportedErrorId(error, req);
149
- return encodeErrorDigest({ message: clientErrorMessage(error), errorId });
150
- },
130
+ // Return a digest so React emits a per-row error in the Flight
131
+ // stream instead of leaving the lazy reference unresolved.
132
+ //
133
+ // SECURITY: Never include error.message in the digest — it may
134
+ // contain SQL queries, filesystem paths, secret fragments, or
135
+ // internal IDs. Use a generic message with a correlation ID so
136
+ // the error can be matched to server logs. The ID is the `digest`
137
+ // prop error pages receive (shared/error-digest.ts).
138
+ // See design/13-security.md §"Errors don't leak".
139
+ //
140
+ // This is the error's one log and one `onRequestError` report,
141
+ // whether a Suspense boundary contains it or it crashes the shell
142
+ // and the renderer answers with the error page (design/49
143
+ // §"Deferred: render-error handoff").
144
+ //
145
+ // The one exception is a no-JS action's error, rendered in place of
146
+ // the page (route-element-builder.ts): the action already logged and
147
+ // reported it, so it keeps that log line's ID and is not reported
148
+ // twice.
149
+ const actionError = getActionErrorForRender();
150
+ const errorId =
151
+ actionError && actionError.error === error
152
+ ? actionError.errorId
153
+ : reportedErrorId(error, req);
154
+ return encodeErrorDigest({ message: clientErrorMessage(error), errorId });
151
155
  },
152
- {
153
- onClientReference(info: { id: string; name: string; deps: unknown }) {
154
- // Client reference callback — invoked when a "use client"
155
- // component is serialized into the RSC stream. Can be extended
156
- // for CSS dep collection and Early Hints.
157
- void info;
158
- },
159
- }
160
- );
156
+ });
161
157
 
162
158
  return { rscStream, signals: recorder.signals };
163
159
  }
@@ -7,19 +7,35 @@
7
7
  */
8
8
 
9
9
  /// <reference types="@vitejs/plugin-rsc/types" />
10
+ /// <reference types="vite/client" />
10
11
 
12
+ import type { FlightSource } from '../flight-source.ts';
11
13
  import type { NavContext, SsrRenderResult } from '../ssr-bridge-types.ts';
12
14
 
13
- export async function callSsr(
14
- rscStream: ReadableStream<Uint8Array>,
15
- navContext: NavContext
16
- ): Promise<SsrRenderResult> {
17
- let ssrEntry: typeof import('../ssr-entry.ts');
15
+ type SsrEntry = typeof import('../ssr-entry.ts');
16
+
17
+ /**
18
+ * The SSR entry, loaded once per process in production. Each
19
+ * `import.meta.viteRsc.import()` is a dynamic `import()` whose module
20
+ * resolution showed in per-request profiles (LOCAL-1476); the built entry
21
+ * never changes. Under a dev server (`import.meta.hot` exists: HMR can swap
22
+ * SSR modules) it imports per call, whatever NODE_ENV says. A failed load is
23
+ * not kept: the next request tries again, as before.
24
+ */
25
+ let ssrEntry: Promise<SsrEntry> | null = null;
26
+
27
+ function loadSsrEntry(): Promise<SsrEntry> {
28
+ if (import.meta.hot) return importSsrEntry();
29
+ ssrEntry ??= importSsrEntry().catch((error: unknown) => {
30
+ ssrEntry = null;
31
+ throw error;
32
+ });
33
+ return ssrEntry;
34
+ }
35
+
36
+ async function importSsrEntry(): Promise<SsrEntry> {
18
37
  try {
19
- ssrEntry = await import.meta.viteRsc.import<typeof import('../ssr-entry.ts')>(
20
- '../ssr-entry.js',
21
- { environment: 'ssr' }
22
- );
38
+ return await import.meta.viteRsc.import<SsrEntry>('../ssr-entry.js', { environment: 'ssr' });
23
39
  } catch (error) {
24
40
  const original = error instanceof Error ? error.message : String(error);
25
41
  throw new Error(
@@ -27,5 +43,11 @@ export async function callSsr(
27
43
  { cause: error }
28
44
  );
29
45
  }
30
- return ssrEntry.handleSsr(rscStream, navContext);
46
+ }
47
+
48
+ export async function callSsr(
49
+ rscSource: FlightSource,
50
+ navContext: NavContext
51
+ ): Promise<SsrRenderResult> {
52
+ return (await loadSsrEntry()).handleSsr(rscSource, navContext);
31
53
  }
@@ -34,10 +34,10 @@ import { callSsr } from './ssr-bridge.ts';
34
34
  import type { RenderSignals } from './render-signals.ts';
35
35
  import type { DenySignal, RedirectSignal } from '../primitives.ts';
36
36
  import { recordTiming } from '../server-timing.ts';
37
- import { teeWithErrorPropagation } from '../stream-utils.ts';
37
+ import { cancelFlightSource, teeFlightSource, type FlightSource } from '../flight-source.ts';
38
38
  import { addSpanEventSync } from '../tracing.ts';
39
39
  import { isDevMode } from '../debug.ts';
40
- import { swallow } from '../logger.ts';
40
+ import { discardResponseBody, withResponseInit } from '../node-response.ts';
41
41
 
42
42
  /**
43
43
  * Maximum number of queueMicrotask yields during signal promotion.
@@ -88,7 +88,7 @@ export const __test_only_signalPromotionCapHit: { value: boolean } = { value: fa
88
88
 
89
89
  interface SsrRenderOptions {
90
90
  req: Request;
91
- rscStream: ReadableStream<Uint8Array>;
91
+ rscStream: FlightSource;
92
92
  signals: RenderSignals;
93
93
  segments: ManifestSegmentNode[];
94
94
  layoutComponents: LayoutComponentEntry[];
@@ -149,22 +149,23 @@ export async function renderSsrResponse(opts: SsrRenderOptions): Promise<Respons
149
149
  formState,
150
150
  } = opts;
151
151
 
152
- // Tee the RSC stream — one copy goes to SSR for HTML rendering,
153
- // the other is inlined in the HTML for client-side hydration.
154
- // Uses teeWithErrorPropagation to ensure errors on either branch
155
- // cancel the other (preventing hung responses) and to monitor
156
- // buffer divergence between SSR and inline consumers.
152
+ // Tee the Flight source — one copy goes to SSR for HTML rendering,
153
+ // the other is inlined in the HTML for client-side hydration. Each branch
154
+ // is the source's own kind (a Node stream on Node). The tee propagates an
155
+ // error or cancel on either branch to the other (preventing hung
156
+ // responses) and bounds the buffer divergence between SSR and inline
157
+ // consumers (design/02 §"Stream Tee").
157
158
  //
158
159
  // When client JS is disabled, skip the tee — the inline stream would
159
160
  // never be consumed, causing monotonic buffer divergence that eventually
160
161
  // triggers the 5MB guard and cancels the SSR stream.
161
- let ssrStream: ReadableStream<Uint8Array>;
162
- let inlineStream: ReadableStream<Uint8Array> | undefined;
162
+ let ssrStream: FlightSource;
163
+ let inlineStream: FlightSource | undefined;
163
164
  if (clientJsDisabled) {
164
165
  ssrStream = rscStream;
165
166
  inlineStream = undefined;
166
167
  } else {
167
- [ssrStream, inlineStream] = teeWithErrorPropagation(rscStream);
168
+ [ssrStream, inlineStream] = teeFlightSource(rscStream);
168
169
  }
169
170
 
170
171
  // Segment metadata for initial hydration: deferred to shell-flush time.
@@ -240,9 +241,7 @@ export async function renderSsrResponse(opts: SsrRenderOptions): Promise<Respons
240
241
  // below renders its own streams or none. Without explicit cancellation
241
242
  // the orphaned tee branch keeps the RSC source stream alive, preventing
242
243
  // garbage collection — so release it before anything returns or throws.
243
- inlineStream
244
- ?.cancel()
245
- .catch((err: unknown) => swallow(err, 'orphaned RSC inline stream did not cancel'));
244
+ if (inlineStream) cancelFlightSource(inlineStream);
246
245
 
247
246
  // Connection abort — the client disconnected (page refresh, navigation
248
247
  // away). No response needed; return empty 499 (client closed request).
@@ -383,9 +382,7 @@ export async function renderSsrResponse(opts: SsrRenderOptions): Promise<Respons
383
382
  // A captured signal replaces this document, so its body is never read.
384
383
  const promoted = capturedSignal();
385
384
  if (promoted) {
386
- ssrResponse.body
387
- ?.cancel()
388
- .catch((err: unknown) => swallow(err, 'discarded SSR document body did not cancel'));
385
+ discardResponseBody(ssrResponse);
389
386
  throw promoted;
390
387
  }
391
388
 
@@ -397,7 +394,7 @@ export async function renderSsrResponse(opts: SsrRenderOptions): Promise<Respons
397
394
  // too, with the status its catch site recorded (see the detection phase).
398
395
  const denyStatus = getDenyStatus();
399
396
  if (denyStatus) {
400
- return new Response(ssrResponse.body, {
397
+ return withResponseInit(ssrResponse, {
401
398
  status: denyStatus,
402
399
  headers: ssrResponse.headers,
403
400
  });
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * This file defines what crosses the RSC ↔ SSR environment boundary: the
5
5
  * `NavContext` input and the `SsrRenderResult` output. The RSC
6
- * environment calls `handleSsr(rscStream, navContext)`
6
+ * environment calls `handleSsr(rscSource, navContext)`
7
7
  * in the SSR environment via `import.meta.viteRsc.import(...)` (see
8
8
  * `rsc-entry/ssr-bridge.ts`). RSC and SSR are separate Vite module graphs
9
9
  * with separate module instances, so every per-request field that SSR
@@ -23,7 +23,8 @@
23
23
  *
24
24
  * 1. **Structurally serializable shape.** Fields must be values that can
25
25
  * cross the environment boundary as plain data or as platform-neutral
26
- * primitives (`Headers`, `ReadableStream`, `AbortSignal`, `Map`). Do
26
+ * primitives (`Headers`, `ReadableStream`, `AbortSignal`, `Map`, and a
27
+ * `FlightSource`'s Node `Readable` — both environments share a process). Do
27
28
  * not add closures, class instances tied to RSC-only modules, or
28
29
  * anything whose identity must be preserved across the bridge. The one
29
30
  * sanctioned exception is `NavContext.getHeadSegmentScript`.
@@ -50,6 +51,8 @@
50
51
  * and `CLAUDE.md` §"RSC and SSR Are Separate Vite Environments".
51
52
  */
52
53
 
54
+ import type { FlightSource } from './flight-source.ts';
55
+
53
56
  /**
54
57
  * Navigation context passed from the RSC environment to SSR.
55
58
  *
@@ -89,8 +92,11 @@ export interface NavContext {
89
92
  * See design/13-security.md §"Content Security Policy" (TIM-1414).
90
93
  */
91
94
  nonce?: string;
92
- /** Tee'd RSC stream for client-side hydration (inlined into HTML) */
93
- rscStream?: ReadableStream<Uint8Array>;
95
+ /**
96
+ * The tee'd Flight source inlined into the HTML for client-side hydration.
97
+ * A Node stream on Node, a Web stream elsewhere (`flight-source.ts`).
98
+ */
99
+ rscStream?: FlightSource;
94
100
  /** Max Suspense hold window (ms). SSR delays the first flush by this
95
101
  * duration, racing allReady so that fast-resolving boundaries render inline
96
102
  * without ever showing a fallback. Derived from route `deferSuspenseFor` exports.