@timber-js/app 0.2.0-alpha.249 → 0.2.0-alpha.250

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 (100) hide show
  1. package/dist/_chunks/{actions-C7_xl9iA.js → actions-DH_TCxJb.js} +2 -2
  2. package/dist/_chunks/{actions-C7_xl9iA.js.map → actions-DH_TCxJb.js.map} +1 -1
  3. package/dist/_chunks/dev-span-0aG7Q_Ph.js.map +1 -1
  4. package/dist/_chunks/{dist-GyaJm4GA.js → dist-ob734WH3.js} +20 -19
  5. package/dist/_chunks/dist-ob734WH3.js.map +1 -0
  6. package/dist/_chunks/{error-boundary-wuNvAJ4n.js → error-boundary-BR21tTQc.js} +3 -3
  7. package/dist/_chunks/{error-boundary-wuNvAJ4n.js.map → error-boundary-BR21tTQc.js.map} +1 -1
  8. package/dist/_chunks/global-context-DbxNWeBP.js +47 -0
  9. package/dist/_chunks/global-context-DbxNWeBP.js.map +1 -0
  10. package/dist/_chunks/{navigation-root-Cvb7P1ud.js → navigation-root-AuCD35Sv.js} +42 -47
  11. package/dist/_chunks/navigation-root-AuCD35Sv.js.map +1 -0
  12. package/dist/_chunks/ssr-data-BfsCqCLl.js +47 -0
  13. package/dist/_chunks/ssr-data-BfsCqCLl.js.map +1 -0
  14. package/dist/client/browser-entry/post-hydration.d.ts +2 -2
  15. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -1
  16. package/dist/client/browser-entry/scroll.d.ts +11 -8
  17. package/dist/client/browser-entry/scroll.d.ts.map +1 -1
  18. package/dist/client/error-boundary.js +1 -1
  19. package/dist/client/index.js +12 -9
  20. package/dist/client/index.js.map +1 -1
  21. package/dist/client/internal.d.ts +0 -2
  22. package/dist/client/internal.d.ts.map +1 -1
  23. package/dist/client/internal.js +6 -6
  24. package/dist/client/internal.js.map +1 -1
  25. package/dist/client/link.d.ts.map +1 -1
  26. package/dist/client/ssr-data.d.ts +35 -38
  27. package/dist/client/ssr-data.d.ts.map +1 -1
  28. package/dist/client/state.d.ts +1 -8
  29. package/dist/client/state.d.ts.map +1 -1
  30. package/dist/client/use-cookie.d.ts.map +1 -1
  31. package/dist/client/use-search-params.d.ts.map +1 -1
  32. package/dist/cookies/index.js +3 -3
  33. package/dist/cookies/index.js.map +1 -1
  34. package/dist/native/rsc/client/global-context.js +20 -0
  35. package/dist/native/rsc/client/global-context.js.map +1 -0
  36. package/dist/native/rsc/client/ssr-data.js +9 -4
  37. package/dist/native/rsc/client/ssr-data.js.map +1 -1
  38. package/dist/native/rsc/client/use-cookie.js +4 -4
  39. package/dist/native/rsc/client/use-cookie.js.map +1 -1
  40. package/dist/native/rsc/manifest.json +1 -1
  41. package/dist/native/rsc/server/build-manifest.js +1 -4
  42. package/dist/native/rsc/server/build-manifest.js.map +1 -1
  43. package/dist/native/rsc/server/html-injectors.js +6 -7
  44. package/dist/native/rsc/server/html-injectors.js.map +1 -1
  45. package/dist/native/rsc/server/react-cache-bridge.js +2 -2
  46. package/dist/native/rsc/server/react-cache-bridge.js.map +1 -1
  47. package/dist/native/rsc/server/rsc-entry/render-route.js +3 -5
  48. package/dist/native/rsc/server/rsc-entry/render-route.js.map +1 -1
  49. package/dist/native/rsc/server/rsc-entry/ssr-renderer.js +3 -2
  50. package/dist/native/rsc/server/rsc-entry/ssr-renderer.js.map +1 -1
  51. package/dist/native/ssr/client/link.js +10 -8
  52. package/dist/native/ssr/client/link.js.map +1 -1
  53. package/dist/native/ssr/client/ssr-data.js +10 -6
  54. package/dist/native/ssr/client/ssr-data.js.map +1 -1
  55. package/dist/native/ssr/client/state.js +1 -5
  56. package/dist/native/ssr/client/state.js.map +1 -1
  57. package/dist/native/ssr/client/use-cookie.js +2 -2
  58. package/dist/native/ssr/client/use-cookie.js.map +1 -1
  59. package/dist/native/ssr/client/use-search-params.js +3 -2
  60. package/dist/native/ssr/client/use-search-params.js.map +1 -1
  61. package/dist/native/ssr/server/ssr-wrappers.js +11 -4
  62. package/dist/native/ssr/server/ssr-wrappers.js.map +1 -1
  63. package/dist/server/build-manifest.d.ts +0 -7
  64. package/dist/server/build-manifest.d.ts.map +1 -1
  65. package/dist/server/html-injectors.d.ts +5 -4
  66. package/dist/server/html-injectors.d.ts.map +1 -1
  67. package/dist/server/index.js +1 -1
  68. package/dist/server/internal.js +1 -1
  69. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  70. package/dist/server/rsc-entry/ssr-renderer.d.ts +2 -0
  71. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  72. package/dist/server/ssr-bridge-types.d.ts +6 -0
  73. package/dist/server/ssr-bridge-types.d.ts.map +1 -1
  74. package/dist/server/ssr-entry.d.ts.map +1 -1
  75. package/dist/server/ssr-wrappers.d.ts +14 -9
  76. package/dist/server/ssr-wrappers.d.ts.map +1 -1
  77. package/package.json +5 -5
  78. package/src/client/browser-entry/post-hydration.ts +27 -22
  79. package/src/client/browser-entry/scroll.ts +12 -9
  80. package/src/client/internal.ts +0 -4
  81. package/src/client/link.tsx +14 -13
  82. package/src/client/ssr-data.ts +50 -57
  83. package/src/client/state.ts +1 -14
  84. package/src/client/use-cookie.ts +4 -3
  85. package/src/client/use-search-params.ts +5 -4
  86. package/src/server/build-manifest.ts +0 -10
  87. package/src/server/html-injectors.ts +11 -13
  88. package/src/server/rsc-entry/render-route.ts +9 -8
  89. package/src/server/rsc-entry/ssr-renderer.ts +4 -1
  90. package/src/server/ssr-bridge-types.ts +6 -0
  91. package/src/server/ssr-entry.ts +180 -207
  92. package/src/server/ssr-wrappers.tsx +52 -14
  93. package/dist/_chunks/dist-GyaJm4GA.js.map +0 -1
  94. package/dist/_chunks/navigation-root-Cvb7P1ud.js.map +0 -1
  95. package/dist/_chunks/ssr-data-9hPtcNOr.js +0 -48
  96. package/dist/_chunks/ssr-data-9hPtcNOr.js.map +0 -1
  97. package/dist/_chunks/state-B-EBjeER.js +0 -49
  98. package/dist/_chunks/state-B-EBjeER.js.map +0 -1
  99. package/dist/native/rsc/client/state.js +0 -14
  100. package/dist/native/rsc/client/state.js.map +0 -1
@@ -21,7 +21,6 @@ import schemaCodecs from 'virtual:timber-schema';
21
21
  import { setSchemaCodecs } from '../params/codec-registry.ts';
22
22
  setSchemaCodecs(schemaCodecs);
23
23
  import { createFromReadableStream, createFromNodeStream } from '../rsc-runtime/ssr.ts';
24
- import { AsyncLocalStorage } from 'node:async_hooks';
25
24
 
26
25
  import {
27
26
  renderSsrStream,
@@ -34,7 +33,6 @@ import { SsrStreamError } from './signal-identity.ts';
34
33
  import { createBufferedTransformStream, injectHead, injectRscPayload } from './html-injectors.ts';
35
34
  import { wrapSsrElement } from './ssr-wrappers.tsx';
36
35
  import { withSpan } from './tracing.ts';
37
- import { registerSsrDataProvider, type SsrData } from '../client/ssr-data.ts';
38
36
  import { splitPayloadRoot } from '../shared/payload-root.ts';
39
37
  import { formStateForSsr } from './ssr-form-state.ts';
40
38
  import { resolveRenderTimeoutMs } from './render-timeout.ts';
@@ -70,19 +68,6 @@ if (useNodeStreams) {
70
68
  };
71
69
  }
72
70
 
73
- // ─── SSR Data ALS ─────────────────────────────────────────────────────────
74
- //
75
- // Per-request SSR data stored in AsyncLocalStorage, ensuring correct
76
- // isolation even when Suspense boundaries resolve asynchronously across
77
- // concurrent requests. The ALS is created here (server-only module) and
78
- // exposed to client hooks via the registration pattern — ssr-data.ts
79
- // never imports node:async_hooks directly.
80
-
81
- const ssrDataAls = new AsyncLocalStorage<SsrData>();
82
-
83
- // Register the ALS-backed provider so getSsrData() reads from ALS.
84
- registerSsrDataProvider(() => ssrDataAls.getStore());
85
-
86
71
  /**
87
72
  * Handle SSR: decode a Flight source and render it to hydration-ready HTML.
88
73
  *
@@ -116,209 +101,197 @@ export async function handleSsr(
116
101
  return withSpan('timber.ssr', { 'timber.environment': 'ssr' }, async () => {
117
102
  const _runtimeConfig = config;
118
103
 
119
- // Per-request SSR data for the client code with no React context to
120
- // read during SSR (useCookie, <Link preserveSearchParams>; useSearchParams
121
- // uses it only to detect SSR). Route params reach client components through
122
- // ParamsContext, decoded from the payload root, not through here.
123
- const ssrData: SsrData = {
104
+ // Decode the RSC stream into a React element tree.
105
+ // createFromReadableStream resolves client component references
106
+ // (from "use client" modules) using the SSR environment's module
107
+ // map, importing the actual components for server-side rendering.
108
+ const _ssrStart = performance.now();
109
+
110
+ // Decode the Flight source into a React element tree. Each platform
111
+ // renders Flight in its own stream kind (server/flight-source.ts), so
112
+ // the source matches the HTML pipeline chosen below; nothing adapts one
113
+ // kind into the other.
114
+ // - Node.js: createFromNodeStream reads the object-mode Node stream,
115
+ // string chunks included (no Web Streams hop).
116
+ // - Workers: createFromReadableStream (Web Streams are V8-native there).
117
+ //
118
+ // The request CSP nonce goes to the Flight decoder too: Flight emits
119
+ // `<script>` preinits for client-reference modules, and those need
120
+ // the nonce as much as timber's own inline tags do (TIM-1414).
121
+ const nonce = navContext.nonce;
122
+ let root: unknown;
123
+ if (_nodeStreamImports) {
124
+ if (rscSource.kind !== 'node' || !createFromNodeStream) {
125
+ throw new Error('[timber] SSR on Node received a Web Flight source');
126
+ }
127
+ root = createFromNodeStream(rscSource.stream, { nonce });
128
+ } else {
129
+ if (rscSource.kind !== 'web') {
130
+ throw new Error('[timber] SSR on Web Streams received a Node Flight source');
131
+ }
132
+ root = createFromReadableStream(rscSource.stream, { nonce });
133
+ }
134
+ // The payload root is `{ tree, params, slotParams }` — params ride
135
+ // beside the tree rather than in a provider around it (TIM-1297).
136
+ // splitPayloadRoot is the same split the browser performs: the tree
137
+ // renders, and the params half feeds PayloadRoot inside the wrapper
138
+ // chain so `useSegmentParams()` reads the identical derivation on
139
+ // both sides (TIM-1424).
140
+ const { tree, params } = splitPayloadRoot(root);
141
+ const element = tree as React.ReactNode;
142
+ const _decodeEnd = performance.now();
143
+
144
+ // Wrap with the same component tree the client hydrates —
145
+ // real NavigationProvider and PayloadRoot, not no-op mirrors —
146
+ // so hooks resolve identically and useId() matches on both sides.
147
+ // See TIM-532, TIM-1424.
148
+ const wrappedElement = wrapSsrElement(element, {
149
+ pathname: navContext.pathname,
124
150
  search: navContext.search,
151
+ paramsSource: params,
152
+ modulePreloads: navContext.modulePreloads,
153
+ // useCookie() reads these through the SSR data context, which follows
154
+ // the tree wherever Fizz resumes it (client/ssr-data.ts).
125
155
  cookies: navContext.cookies ?? new Map(),
126
- };
156
+ });
127
157
 
128
- // Run the entire render inside the SSR data ALS scope.
129
- // This ensures correct per-request isolation even when Suspense
130
- // boundaries resolve asynchronously across concurrent requests.
131
- // Client hooks read from getSsrData() which delegates to this
132
- // ALS store via the registered provider.
133
- return ssrDataAls.run(ssrData, async () => {
134
- // Decode the RSC stream into a React element tree.
135
- // createFromReadableStream resolves client component references
136
- // (from "use client" modules) using the SSR environment's module
137
- // map, importing the actual components for server-side rendering.
138
- const _ssrStart = performance.now();
158
+ // Render to HTML stream (waits for onShellReady).
159
+ //
160
+ // Two paths based on platform:
161
+ // - Node.js: renderToPipeableStream → Node Transform pipeline → NodeBodyResponse
162
+ // The document stays a Node stream all the way to the socket.
163
+ // - Workers: renderToReadableStream → Web TransformStream pipeline → Response
164
+ // Web Streams are V8-native C++ built-ins on Workers.
165
+ //
166
+ // `onFizzAllReadyResolved` fires synchronously before the render
167
+ // promise resolves, so the flag is settled once the render is awaited.
168
+ const renderTimeoutMs = _runtimeConfig.renderTimeoutMs ?? undefined;
169
+ const requestInfo = { method: 'GET', path: navContext.pathname };
170
+ // The no-JS action's form state, for Fizz and, only once it decoded,
171
+ // embedded for the browser to hydrate with (design/08 §"No-JS Result
172
+ // Round-Trip"). A page whose payload is inlined hydrates.
173
+ const { formState, script: formStateHead } = await formStateForSsr(navContext.formState, {
174
+ hydrates: navContext.rscStream !== undefined,
175
+ nonce,
176
+ decode: (stream) => createFromReadableStream(stream, { nonce }),
177
+ timeoutMs: resolveRenderTimeoutMs(renderTimeoutMs),
178
+ });
179
+ let fizzAllReadyResolved = false;
180
+ const renderOptions: SsrStreamOptions = {
181
+ bootstrapScriptContent: navContext.bootstrapScriptContent || undefined,
182
+ nonce,
183
+ formState,
184
+ deferSuspenseFor: navContext.deferSuspenseFor,
185
+ signal: navContext.signal,
186
+ renderTimeoutMs,
187
+ requestInfo,
188
+ onFizzAllReadyResolved: (resolved) => {
189
+ fizzAllReadyResolved = resolved;
190
+ },
191
+ };
192
+ // Not logged here. Fizz's onError (ssr-render.ts) has already logged a
193
+ // shell error SSR produced itself, and skips one Flight relayed,
194
+ // which the RSC onError (rsc-stream.ts) logged. Logging the rejection
195
+ // again doubled every shell failure (TIM-1537).
196
+ const renderFailed = (renderError: unknown): never => {
197
+ throw new SsrStreamError(
198
+ 'SSR renderToReadableStream failed due to RSC stream error',
199
+ renderError
200
+ );
201
+ };
139
202
 
140
- // Decode the Flight source into a React element tree. Each platform
141
- // renders Flight in its own stream kind (server/flight-source.ts), so
142
- // the source matches the HTML pipeline chosen below; nothing adapts one
143
- // kind into the other.
144
- // - Node.js: createFromNodeStream reads the object-mode Node stream,
145
- // string chunks included (no Web Streams hop).
146
- // - Workers: createFromReadableStream (Web Streams are V8-native there).
147
- //
148
- // The request CSP nonce goes to the Flight decoder too: Flight emits
149
- // `<script>` preinits for client-reference modules, and those need
150
- // the nonce as much as timber's own inline tags do (TIM-1414).
151
- const nonce = navContext.nonce;
152
- let root: unknown;
153
- if (_nodeStreamImports) {
154
- if (rscSource.kind !== 'node' || !createFromNodeStream) {
155
- throw new Error('[timber] SSR on Node received a Web Flight source');
156
- }
157
- root = createFromNodeStream(rscSource.stream, { nonce });
158
- } else {
159
- if (rscSource.kind !== 'web') {
160
- throw new Error('[timber] SSR on Web Streams received a Node Flight source');
161
- }
162
- root = createFromReadableStream(rscSource.stream, { nonce });
163
- }
164
- // The payload root is `{ tree, params, slotParams }` — params ride
165
- // beside the tree rather than in a provider around it (TIM-1297).
166
- // splitPayloadRoot is the same split the browser performs: the tree
167
- // renders, and the params half feeds PayloadRoot inside the wrapper
168
- // chain so `useSegmentParams()` reads the identical derivation on
169
- // both sides (TIM-1424).
170
- const { tree, params } = splitPayloadRoot(root);
171
- const element = tree as React.ReactNode;
172
- const _decodeEnd = performance.now();
203
+ const responseInit = ssrResponseInit(navContext.statusCode, navContext.responseHeaders);
204
+ let response: Response;
205
+ let _renderEnd: number;
206
+ if (_nodeStreamImports) {
207
+ // Node.js fast path: full pipeline in native streams
208
+ const {
209
+ createNodeBufferedTransform,
210
+ createNodeHeadInjector,
211
+ createNodeMoveSuffixTransform,
212
+ createNodeFlightInjector,
213
+ runNodePipelineWithErrorHandling,
214
+ NodeBodyResponse,
215
+ } = _nodeStreamImports;
173
216
 
174
- // Wrap with the same component tree the client hydrates —
175
- // real NavigationProvider and PayloadRoot, not no-op mirrors —
176
- // so hooks resolve identically and useId() matches on both sides.
177
- // See TIM-532, TIM-1424.
178
- const wrappedElement = wrapSsrElement(element, {
179
- pathname: navContext.pathname,
180
- search: navContext.search,
181
- paramsSource: params,
182
- });
217
+ const nodeHtmlStream = await renderSsrNodeStream(wrappedElement, renderOptions).catch(
218
+ renderFailed
219
+ );
220
+ _renderEnd = performance.now();
183
221
 
184
- // Render to HTML stream (waits for onShellReady).
222
+ // React 19.3+ emits <!DOCTYPE html> automatically when the root
223
+ // element is <html>, so no framework-level doctype prepend needed.
224
+ //
225
+ // Pipeline: buffer → headInjector → flightInjector → moveSuffix → output
185
226
  //
186
- // Two paths based on platform:
187
- // - Node.js: renderToPipeableStream → Node Transform pipeline → NodeBodyResponse
188
- // The document stays a Node stream all the way to the socket.
189
- // - Workers: renderToReadableStream → Web TransformStream pipeline → Response
190
- // Web Streams are V8-native C++ built-ins on Workers.
227
+ // 1. buffer: coalesces Fizz micro-chunks into coherent fragments (TIM-528)
228
+ // 2. headInjector: injects metadata before </head>
229
+ // 3. flightInjector: interleaves RSC scripts between HTML chunks (TIM-529)
230
+ // 4. moveSuffix: strips </body></html>, re-emits at end (TIM-530)
231
+ //
232
+ // Post-shell error handling lives in the pump, not in a stage: a
233
+ // failing stage takes the whole chain down, so only an output kept
234
+ // outside the chain can append the noindex script and close cleanly
235
+ // (TIM-1019).
236
+ // Resolve the lazy segment script now that the shell is ready
237
+ // (AccessGates have settled, ALS deny index is authoritative).
238
+ const resolvedHeadHtml =
239
+ navContext.headHtml + formStateHead + (navContext.getHeadSegmentScript?.() ?? '');
240
+ const output = runNodePipelineWithErrorHandling(
241
+ nodeHtmlStream,
242
+ [
243
+ createNodeBufferedTransform(),
244
+ createNodeHeadInjector(resolvedHeadHtml),
245
+ createNodeFlightInjector(navContext.rscStream, {
246
+ renderTimeoutMs,
247
+ errorSignal: navContext._errorSignal,
248
+ nonce,
249
+ }),
250
+ createNodeMoveSuffixTransform(),
251
+ ],
252
+ navContext.signal,
253
+ nonce
254
+ );
255
+ // The document stays a Node stream to the socket: the adapter pipes
256
+ // it (`_toNodeResponse`), with no Web Streams round trip.
257
+ response = new NodeBodyResponse(output, responseInit);
258
+ } else {
259
+ // Web Streams path (CF Workers / fallback)
260
+ const htmlStream = await renderSsrStream(wrappedElement, renderOptions).catch(renderFailed);
261
+ _renderEnd = performance.now();
262
+
263
+ // Pipeline: buffer → injectHead → injectRscPayload
191
264
  //
192
- // `onFizzAllReadyResolved` fires synchronously before the render
193
- // promise resolves, so the flag is settled once the render is awaited.
194
- const renderTimeoutMs = _runtimeConfig.renderTimeoutMs ?? undefined;
195
- const requestInfo = { method: 'GET', path: navContext.pathname };
196
- // The no-JS action's form state, for Fizz and, only once it decoded,
197
- // embedded for the browser to hydrate with (design/08 §"No-JS Result
198
- // Round-Trip"). A page whose payload is inlined hydrates.
199
- const { formState, script: formStateHead } = await formStateForSsr(navContext.formState, {
200
- hydrates: navContext.rscStream !== undefined,
265
+ // The buffered transform coalesces Fizz micro-chunks into coherent
266
+ // HTML fragments so downstream transforms never see chunk boundaries
267
+ // mid-tag. This prevents RSC script injection from breaking HTML
268
+ // structure (TIM-527).
269
+ // Resolve the lazy segment script now that the shell is ready
270
+ // (AccessGates have settled, ALS deny index is authoritative).
271
+ const resolvedHeadHtml =
272
+ navContext.headHtml + formStateHead + (navContext.getHeadSegmentScript?.() ?? '');
273
+ let outputStream = htmlStream.pipeThrough(createBufferedTransformStream());
274
+ outputStream = injectHead(outputStream, resolvedHeadHtml);
275
+ outputStream = injectRscPayload(outputStream, navContext.rscStream, {
276
+ renderTimeoutMs,
277
+ errorSignal: navContext._errorSignal,
201
278
  nonce,
202
- decode: (stream) => createFromReadableStream(stream, { nonce }),
203
- timeoutMs: resolveRenderTimeoutMs(renderTimeoutMs),
204
279
  });
205
- let fizzAllReadyResolved = false;
206
- const renderOptions: SsrStreamOptions = {
207
- bootstrapScriptContent: navContext.bootstrapScriptContent || undefined,
208
- nonce,
209
- formState,
210
- deferSuspenseFor: navContext.deferSuspenseFor,
211
- signal: navContext.signal,
212
- renderTimeoutMs,
213
- requestInfo,
214
- onFizzAllReadyResolved: (resolved) => {
215
- fizzAllReadyResolved = resolved;
216
- },
217
- };
218
- // Not logged here. Fizz's onError (ssr-render.ts) has already logged a
219
- // shell error SSR produced itself, and skips one Flight relayed,
220
- // which the RSC onError (rsc-stream.ts) logged. Logging the rejection
221
- // again doubled every shell failure (TIM-1537).
222
- const renderFailed = (renderError: unknown): never => {
223
- throw new SsrStreamError(
224
- 'SSR renderToReadableStream failed due to RSC stream error',
225
- renderError
226
- );
227
- };
280
+ response = new Response(outputStream, responseInit);
281
+ }
282
+ const _pipelineEnd = performance.now();
228
283
 
229
- const responseInit = ssrResponseInit(navContext.statusCode, navContext.responseHeaders);
230
- let response: Response;
231
- let _renderEnd: number;
232
- if (_nodeStreamImports) {
233
- // Node.js fast path: full pipeline in native streams
234
- const {
235
- createNodeBufferedTransform,
236
- createNodeHeadInjector,
237
- createNodeMoveSuffixTransform,
238
- createNodeFlightInjector,
239
- runNodePipelineWithErrorHandling,
240
- NodeBodyResponse,
241
- } = _nodeStreamImports;
242
-
243
- const nodeHtmlStream = await renderSsrNodeStream(wrappedElement, renderOptions).catch(
244
- renderFailed
245
- );
246
- _renderEnd = performance.now();
247
-
248
- // React 19.3+ emits <!DOCTYPE html> automatically when the root
249
- // element is <html>, so no framework-level doctype prepend needed.
250
- //
251
- // Pipeline: buffer → headInjector → flightInjector → moveSuffix → output
252
- //
253
- // 1. buffer: coalesces Fizz micro-chunks into coherent fragments (TIM-528)
254
- // 2. headInjector: injects metadata before </head>
255
- // 3. flightInjector: interleaves RSC scripts between HTML chunks (TIM-529)
256
- // 4. moveSuffix: strips </body></html>, re-emits at end (TIM-530)
257
- //
258
- // Post-shell error handling lives in the pump, not in a stage: a
259
- // failing stage takes the whole chain down, so only an output kept
260
- // outside the chain can append the noindex script and close cleanly
261
- // (TIM-1019).
262
- // Resolve the lazy segment script now that the shell is ready
263
- // (AccessGates have settled, ALS deny index is authoritative).
264
- const resolvedHeadHtml =
265
- navContext.headHtml + formStateHead + (navContext.getHeadSegmentScript?.() ?? '');
266
- const output = runNodePipelineWithErrorHandling(
267
- nodeHtmlStream,
268
- [
269
- createNodeBufferedTransform(),
270
- createNodeHeadInjector(resolvedHeadHtml),
271
- createNodeFlightInjector(navContext.rscStream, {
272
- renderTimeoutMs,
273
- errorSignal: navContext._errorSignal,
274
- nonce,
275
- }),
276
- createNodeMoveSuffixTransform(),
277
- ],
278
- navContext.signal,
279
- nonce
280
- );
281
- // The document stays a Node stream to the socket: the adapter pipes
282
- // it (`_toNodeResponse`), with no Web Streams round trip.
283
- response = new NodeBodyResponse(output, responseInit);
284
- } else {
285
- // Web Streams path (CF Workers / fallback)
286
- const htmlStream = await renderSsrStream(wrappedElement, renderOptions).catch(renderFailed);
287
- _renderEnd = performance.now();
288
-
289
- // Pipeline: buffer → injectHead → injectRscPayload
290
- //
291
- // The buffered transform coalesces Fizz micro-chunks into coherent
292
- // HTML fragments so downstream transforms never see chunk boundaries
293
- // mid-tag. This prevents RSC script injection from breaking HTML
294
- // structure (TIM-527).
295
- // Resolve the lazy segment script now that the shell is ready
296
- // (AccessGates have settled, ALS deny index is authoritative).
297
- const resolvedHeadHtml =
298
- navContext.headHtml + formStateHead + (navContext.getHeadSegmentScript?.() ?? '');
299
- let outputStream = htmlStream.pipeThrough(createBufferedTransformStream());
300
- outputStream = injectHead(outputStream, resolvedHeadHtml);
301
- outputStream = injectRscPayload(outputStream, navContext.rscStream, {
302
- renderTimeoutMs,
303
- errorSignal: navContext._errorSignal,
304
- nonce,
305
- });
306
- response = new Response(outputStream, responseInit);
307
- }
308
- const _pipelineEnd = performance.now();
309
-
310
- return {
311
- response,
312
- timings: {
313
- decodeMs: Math.round(_decodeEnd - _ssrStart),
314
- shellMs: Math.round(_renderEnd - _decodeEnd),
315
- pipelineMs: Math.round(_pipelineEnd - _renderEnd),
316
- totalMs: Math.round(_pipelineEnd - _ssrStart),
317
- nodeStreams: _nodeStreamImports !== null,
318
- },
319
- fizzAllReadyResolved,
320
- };
321
- });
284
+ return {
285
+ response,
286
+ timings: {
287
+ decodeMs: Math.round(_decodeEnd - _ssrStart),
288
+ shellMs: Math.round(_renderEnd - _decodeEnd),
289
+ pipelineMs: Math.round(_pipelineEnd - _renderEnd),
290
+ totalMs: Math.round(_pipelineEnd - _ssrStart),
291
+ nodeStreams: _nodeStreamImports !== null,
292
+ },
293
+ fizzAllReadyResolved,
294
+ };
322
295
  });
323
296
  }
324
297
 
@@ -30,8 +30,8 @@
30
30
  *
31
31
  * Per-request isolation is by construction: the provider values are part
32
32
  * of this request's element tree, so concurrent requests cannot observe
33
- * each other's values — stronger than the ALS path, which remains for
34
- * `useCookie()`.
33
+ * each other's values. The SSR-only SsrDataProvider (client/ssr-data.ts),
34
+ * outermost, carries the request cookies for `useCookie()` the same way.
35
35
  *
36
36
  * **What actually shifts a useId is a fork, not depth.** `useId` derives from
37
37
  * React's tree context, which only changes where a fiber has more than one
@@ -46,9 +46,11 @@
46
46
  */
47
47
 
48
48
  import { createElement, Fragment, type ReactNode } from 'react';
49
+ import { preloadModule } from 'react-dom';
49
50
  import { TimberNuqsAdapter } from '../client/nuqs-adapter.tsx';
50
51
  import { NavigationProvider } from '../client/navigation-context.ts';
51
52
  import { PayloadRoot } from '../client/params-context.ts';
53
+ import { SsrDataProvider } from '../client/ssr-data.ts';
52
54
 
53
55
  /**
54
56
  * SSR equivalent of NavigationRoot.
@@ -59,8 +61,19 @@ import { PayloadRoot } from '../client/params-context.ts';
59
61
  * is unconditional on both sides — the loader's config only decides what fills
60
62
  * the first slot.
61
63
  */
62
- function SsrNavigationRoot({ children }: { children?: ReactNode }): ReactNode {
63
- return createElement(Fragment, null, createElement(DocumentDefaults, null), children);
64
+ function SsrNavigationRoot({
65
+ children,
66
+ modulePreloads,
67
+ }: {
68
+ children?: ReactNode;
69
+ modulePreloads?: readonly string[];
70
+ }): ReactNode {
71
+ return createElement(
72
+ Fragment,
73
+ null,
74
+ createElement(DocumentDefaults, { modulePreloads }),
75
+ children
76
+ );
64
77
  }
65
78
 
66
79
  /**
@@ -76,8 +89,15 @@ function SsrNavigationRoot({ children }: { children?: ReactNode }): ReactNode {
76
89
  * Fizz collects. React writes every viewport <meta> into the head in render
77
90
  * order, and browsers apply the last one, so a viewport <meta> in the app's
78
91
  * root layout overrides this default rather than being overridden by it.
92
+ *
93
+ * The browser entry's chunks are preloaded here through React rather than
94
+ * as raw <link> tags, so Fizz writes each href once. plugin-rsc preloads
95
+ * client-reference chunks with `preloadModule(href, { fetchPriority: 'low' })`
96
+ * as they render; Fizz keeps the first call per href, and this one runs
97
+ * before any client reference, so boot chunks keep default priority.
79
98
  */
80
- function DocumentDefaults(): ReactNode {
99
+ function DocumentDefaults({ modulePreloads }: { modulePreloads?: readonly string[] }): ReactNode {
100
+ for (const href of modulePreloads ?? []) preloadModule(href);
81
101
  return createElement(
82
102
  Fragment,
83
103
  null,
@@ -102,6 +122,10 @@ export interface SsrWrapOptions {
102
122
  * hands to the same component during hydration.
103
123
  */
104
124
  paramsSource: unknown;
125
+ /** Hashed URLs of the browser entry's chunks to modulepreload (NavContext.modulePreloads). */
126
+ modulePreloads?: readonly string[];
127
+ /** The request's cookies, for `useCookie()` through the SSR data context. */
128
+ cookies: ReadonlyMap<string, string>;
105
129
  }
106
130
 
107
131
  /**
@@ -120,13 +144,14 @@ export interface SsrWrapOptions {
120
144
  * → [RSC element]
121
145
  *
122
146
  * SSR tree (this function):
123
- * SsrNavigationRoot
124
- * → Fragment(DocumentDefaults, element)
125
- * → TimberNuqsAdapter (real — same component)
126
- * → NuqsAdapterProvider
127
- * → NavigationProvider (real — same component)
128
- * → PayloadRoot → ParamsProvider (real — same components)
129
- * → [RSC element]
147
+ * SsrDataProvider (SSR only — client/ssr-data.ts)
148
+ * → SsrNavigationRoot
149
+ * → Fragment(DocumentDefaults, element)
150
+ * → TimberNuqsAdapter (real — same component)
151
+ * → NuqsAdapterProvider
152
+ * → NavigationProvider (real — same component)
153
+ * → PayloadRoot → ParamsProvider (real — same components)
154
+ * → [RSC element]
130
155
  */
131
156
  export function wrapSsrElement(element: ReactNode, opts: SsrWrapOptions): ReactNode {
132
157
  // Build inside-out to match the client's createElement chain in
@@ -145,6 +170,19 @@ export function wrapSsrElement(element: ReactNode, opts: SsrWrapOptions): ReactN
145
170
  // 3. The nuqs adapter — the browser's own; it reads search from NavigationContext.
146
171
  const withNuqs = createElement(TimberNuqsAdapter, null, withNav);
147
172
 
148
- // 4. Outermost: NavigationRoot equivalent (the TopLoader fork)
149
- return createElement(SsrNavigationRoot, null, withNuqs);
173
+ // 4. NavigationRoot equivalent (the TopLoader fork)
174
+ const withRoot = createElement(
175
+ SsrNavigationRoot,
176
+ { modulePreloads: opts.modulePreloads },
177
+ withNuqs
178
+ );
179
+
180
+ // 5. Outermost, SSR only: the request values client code reads on the
181
+ // server (client/ssr-data.ts). A single-child provider, so it shifts no
182
+ // useId below it.
183
+ return createElement(
184
+ SsrDataProvider,
185
+ { value: { search: opts.search, cookies: opts.cookies } },
186
+ withRoot
187
+ );
150
188
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"dist-GyaJm4GA.js","names":[],"sources":["../../src/shared/cookie-read-through.ts","../../src/cookies/validation.ts","../../../../node_modules/.pnpm/cookie@2.0.1/node_modules/cookie/dist/index.js"],"sourcesContent":["/**\n * How a typed cookie definition reads its raw value on the server: through\n * the cookie jar, naming the codec it parses with.\n *\n * A `'document'` segment's key holds a cookie's *parsed* value\n * (design/53-segment-lifetime.md §\"Segment keys\"), so the read rule allows a\n * keyed cookie only when it is read through the key's own definition. A raw\n * read sees differences the codec hides: `theme=purple` and `theme=light` key\n * the same, but a raw read shows them apart, so it would freeze. The jar's\n * public `get()` is that raw read; `defineCookie().get()` uses this method.\n *\n * A symbol, so it is not part of the jar's public surface. Isomorphic: no\n * server or client imports (cookies/define-cookie.ts runs in both).\n */\nexport const COOKIE_READ_THROUGH = Symbol.for('timber.cookie-read-through');\n\n/** Read a cookie's raw value for a definition that parses it with `codec`. */\nexport type CookieReadThrough = (name: string, codec: unknown) => string | undefined;\n","/**\n * Cookie name and value validation per RFC 6265 §4.1.1.\n *\n * This module is pure — no server or client imports — so it can be loaded\n * by both `server/request-context.ts` (which guards `getCookies().set()`)\n * and `client/use-cookie.ts` (which guards `useCookie()`'s setter). The\n * shared validator gives both sides identical encoding contracts:\n * **the framework never silently encodes — callers emit `cookie-octet`\n * bytes or get a developer-facing error.**\n *\n * Why this matters: see ONGOING_SECURITY.md H-3 (TIM-868) and\n * design/29-cookies.md §\"Cookie Name and Value Validation\".\n */\n\n// ─── RFC 6265 cookie-octet ────────────────────────────────────────────────\n//\n// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n//\n// Equivalently: US-ASCII printable bytes excluding whitespace, `\"` (0x22),\n// `,` (0x2C), `;` (0x3B), `\\` (0x5C), and DEL (0x7F).\n\n/**\n * RFC 7230 §3.2.6 token characters used as the cookie-name production in\n * RFC 6265 §4.1.1. Anchored, non-empty match.\n *\n * Allowed: US-ASCII letters, digits, and `!#$%&'*+-.^_` `` ` `` `|~`.\n * Disallowed: whitespace, controls, delimiters\n * (`(` `)` `<` `>` `@` `,` `;` `:` `\\` `\"` `/` `[` `]` `?` `=` `{` `}`).\n */\nconst COOKIE_NAME_RE = /^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$/;\n\n/**\n * Format a single byte for a clear error message — escape control bytes\n * and non-ASCII as `0x..` and quote printables.\n */\nfunction describeChar(value: string, index: number): string {\n const code = value.charCodeAt(index);\n if (code < 0x20 || code === 0x7f || code > 0x7e) {\n return `0x${code.toString(16).padStart(2, '0')}`;\n }\n return JSON.stringify(value[index]);\n}\n\n/**\n * Validate a cookie name against RFC 6265 §4.1.1 / RFC 7230 token rules.\n * Throws a developer-facing error naming the offending byte and its index.\n */\nexport function assertValidCookieName(name: string): void {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error('[timber] cookie name must be a non-empty string.');\n }\n if (!COOKIE_NAME_RE.test(name)) {\n for (let i = 0; i < name.length; i++) {\n if (!COOKIE_NAME_RE.test(name[i])) {\n throw new Error(\n `[timber] invalid cookie name ${JSON.stringify(name)} — ` +\n `disallowed character ${describeChar(name, i)} at index ${i}. ` +\n `Cookie names must match the RFC 6265 §4.1.1 token grammar (US-ASCII letters, digits, ` +\n `and \\`!#$%&'*+-.^_\\`|~\\`; no whitespace, controls, or delimiters).`\n );\n }\n }\n throw new Error(\n `[timber] invalid cookie name ${JSON.stringify(name)} — ` +\n `must match RFC 6265 §4.1.1 token grammar.`\n );\n }\n}\n\n/** Single-byte test for RFC 6265 §4.1.1 cookie-octet. */\nfunction isCookieOctet(code: number): boolean {\n return (\n code === 0x21 ||\n (code >= 0x23 && code <= 0x2b) ||\n (code >= 0x2d && code <= 0x3a) ||\n (code >= 0x3c && code <= 0x5b) ||\n (code >= 0x5d && code <= 0x7e)\n );\n}\n\n/**\n * Validate a cookie value against the RFC 6265 §4.1.1 `cookie-value`\n * production:\n *\n * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )\n * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n *\n * Both the bare `*cookie-octet` form and the DQUOTE-wrapped form are\n * valid. The wrapped form is common in upstream `Set-Cookie` headers\n * (e.g. `sid=\"abc\"; Path=/`) and must be forwardable through\n * `setFromHeaders` verbatim — stripping or rejecting the surrounding\n * quotes would corrupt the on-the-wire bytes and break value semantics\n * for the upstream service.\n *\n * Excluded bytes (in either form): CTL, whitespace (CR/LF/TAB/SP),\n * interior DQUOTE, comma, semicolon, backslash, DEL, and anything\n * non-ASCII. The smuggling primitive (`;`) is rejected regardless of\n * wrapping.\n *\n * Throws a developer-facing error naming the offending byte and its\n * index. Callers passing user-controlled data through the default\n * `set()` path don't need to call this — `set()` auto-encodes via\n * `encodeURIComponent`, whose output is always valid cookie-octet.\n * This validator is for the `{ raw: true }` opt-out and for\n * `setFromHeaders` forwarding.\n */\n// ─── Cookie attribute validation ──────────────────────────────────────────\n\n/**\n * Characters that must not appear in path or domain cookie attributes.\n * Semicolons delimit cookie attributes on the wire, so allowing `;` in\n * path or domain would inject extra attributes. CR/LF enable HTTP header\n * injection.\n */\nconst ATTR_INJECTION_RE = /[;\\r\\n]/;\n\nconst VALID_SAME_SITE = new Set(['strict', 'lax', 'none']);\n\n/**\n * Validate cookie option attributes at runtime to prevent Set-Cookie\n * header injection through unsanitized option values.\n *\n * TypeScript types enforce correct shapes at compile time, but at runtime\n * (e.g. from untyped libraries or user-controlled config) invalid values\n * could inject additional Set-Cookie attributes.\n */\nexport function assertValidCookieOptions(options: {\n sameSite?: string;\n path?: string;\n domain?: string;\n maxAge?: number;\n}): void {\n if (options.sameSite !== undefined) {\n const lower = options.sameSite.toLowerCase();\n if (!VALID_SAME_SITE.has(lower)) {\n throw new Error(\n `[timber] invalid cookie sameSite value ${JSON.stringify(options.sameSite)} — ` +\n `must be 'strict', 'lax', or 'none'.`\n );\n }\n }\n if (options.path !== undefined && ATTR_INJECTION_RE.test(options.path)) {\n throw new Error(\n `[timber] invalid cookie path ${JSON.stringify(options.path)} — ` +\n `path must not contain ';', CR, or LF (Set-Cookie header injection).`\n );\n }\n if (options.domain !== undefined && ATTR_INJECTION_RE.test(options.domain)) {\n throw new Error(\n `[timber] invalid cookie domain ${JSON.stringify(options.domain)} — ` +\n `domain must not contain ';', CR, or LF (Set-Cookie header injection).`\n );\n }\n if (\n options.maxAge !== undefined &&\n (typeof options.maxAge !== 'number' || !Number.isFinite(options.maxAge))\n ) {\n throw new Error(\n `[timber] invalid cookie maxAge ${JSON.stringify(options.maxAge)} — ` +\n `maxAge must be a finite number.`\n );\n }\n}\n\nexport function assertValidCookieValue(name: string, value: string): void {\n if (typeof value !== 'string') {\n throw new Error(`[timber] cookie ${JSON.stringify(name)}: cookie value must be a string.`);\n }\n // Detect the DQUOTE-wrapped form: at least two characters and both\n // endpoints are `\"`. The interior must be pure cookie-octet (no\n // interior DQUOTEs allowed — the grammar says *cookie-octet, and\n // cookie-octet excludes 0x22).\n const wrapped =\n value.length >= 2 &&\n value.charCodeAt(0) === 0x22 &&\n value.charCodeAt(value.length - 1) === 0x22;\n const start = wrapped ? 1 : 0;\n const end = wrapped ? value.length - 1 : value.length;\n for (let i = start; i < end; i++) {\n const code = value.charCodeAt(i);\n if (!isCookieOctet(code)) {\n throw new Error(\n `[timber] cookie ${JSON.stringify(name)}: invalid cookie value — ` +\n `disallowed character ${describeChar(value, i)} at index ${i}. ` +\n `Cookie values must contain only RFC 6265 §4.1.1 cookie-octet bytes ` +\n `(US-ASCII printable, excluding whitespace, \\`\"\\`, \\`,\\`, \\`;\\`, and \\`\\\\\\`), ` +\n `optionally enclosed in a single DQUOTE pair. ` +\n `Encode the value (e.g. encodeURIComponent or jsonCookieCodec) before storing it.`\n );\n }\n }\n}\n","/**\n * RegExp to match cookie-name in RFC 6265 sec 4.1.1\n * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2\n * which has been replaced by the token definition in RFC 7230 appendix B.\n *\n * cookie-name = token\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" /\n * \"*\" / \"+\" / \"-\" / \".\" / \"^\" / \"_\" /\n * \"`\" / \"|\" / \"~\" / DIGIT / ALPHA\n *\n * Note: Allowing more characters - https://github.com/jshttp/cookie/issues/191\n * Allow same range as cookie value, except `=`, which delimits end of name.\n */\nconst cookieNameRegExp = /^[\\u0021-\\u003A\\u003C\\u003E-\\u007E]+$/;\n/**\n * RegExp to match cookie-value in RFC 6265 sec 4.1.1\n *\n * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )\n * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n * ; US-ASCII characters excluding CTLs,\n * ; whitespace DQUOTE, comma, semicolon,\n * ; and backslash\n *\n * Allowing more characters: https://github.com/jshttp/cookie/issues/191\n * Comma, backslash, and DQUOTE are not part of the parsing algorithm.\n */\nconst cookieValueRegExp = /^[\\u0021-\\u003A\\u003C-\\u007E]*$/;\n/**\n * RegExp to match domain-value in RFC 6265 sec 4.1.1\n *\n * domain-value = <subdomain>\n * ; defined in [RFC1034], Section 3.5, as\n * ; enhanced by [RFC1123], Section 2.1\n * <subdomain> = <label> | <subdomain> \".\" <label>\n * <label> = <let-dig> [ [ <ldh-str> ] <let-dig> ]\n * Labels must be 63 characters or less.\n * 'let-dig' not 'letter' in the first char, per RFC1123\n * <ldh-str> = <let-dig-hyp> | <let-dig-hyp> <ldh-str>\n * <let-dig-hyp> = <let-dig> | \"-\"\n * <let-dig> = <letter> | <digit>\n * <letter> = any one of the 52 alphabetic characters A through Z in\n * upper case and a through z in lower case\n * <digit> = any one of the ten digits 0 through 9\n *\n * Keep support for leading dot: https://github.com/jshttp/cookie/issues/173\n *\n * > (Note that a leading %x2E (\".\"), if present, is ignored even though that\n * character is not permitted, but a trailing %x2E (\".\"), if present, will\n * cause the user agent to ignore the attribute.)\n */\nconst domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;\n/**\n * RegExp to match path-value in RFC 6265 sec 4.1.1\n *\n * path-value = <any CHAR except CTLs or \";\">\n * CHAR = %x01-7F\n * ; defined in RFC 5234 appendix B.1\n */\nconst pathValueRegExp = /^[\\u0020-\\u003A\\u003D-\\u007E]*$/;\n/**\n * RegExp to match max-age-value in RFC 6265 sec 5.6.2\n */\nconst maxAgeRegExp = /^-?\\d+$/;\n/**\n * RegExp to match RFC 6265 cookie-octet values (without % to preserve roundtrip) that need no URL encoding.\n */\nconst cookieOctetRegExp = /^[!#$&'()*+\\-.\\/0-9:<=>?@A-Z[\\]\\^_`a-z{|}~]*$/;\nconst NullObject = /* @__PURE__ */ (() => {\n const C = function () { };\n C.prototype = Object.create(null);\n return C;\n})();\n/**\n * Parse a `Cookie` header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n */\nexport function parseCookie(str, options) {\n const obj = new NullObject();\n const len = str.length;\n // RFC 6265 sec 4.1.1, RFC 2616 2.2 defines a cookie name consists of one char minimum, plus '='.\n if (len < 2)\n return obj;\n const dec = options?.decode || decode;\n let index = 0;\n do {\n const eqIdx = eqIndex(str, index, len);\n if (eqIdx === len)\n break; // No more cookie pairs.\n const endIdx = endIndex(str, index, len);\n if (eqIdx > endIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n continue;\n }\n const key = valueSlice(str, index, eqIdx);\n // only assign once\n if (obj[key] === undefined) {\n obj[key] = dec(valueSlice(str, eqIdx + 1, endIdx));\n }\n index = endIdx + 1;\n } while (index < len);\n return obj;\n}\n/**\n * Stringifies an object into an HTTP `Cookie` header.\n */\nexport function stringifyCookie(cookie, options) {\n const enc = options?.encode || defaultEncode;\n const keys = Object.keys(cookie);\n let str = \"\";\n for (let i = 0; i < keys.length; i++) {\n const name = keys[i];\n const val = cookie[name];\n if (val === undefined)\n continue;\n if (!cookieNameRegExp.test(name)) {\n throw new TypeError(`cookie name is invalid: ${name}`);\n }\n const value = enc(val);\n if (!cookieValueRegExp.test(value)) {\n throw new TypeError(`cookie val is invalid: ${val}`);\n }\n if (str)\n str += \"; \";\n str += name + \"=\" + value;\n }\n return str;\n}\n/**\n * Serialize data into a cookie header.\n *\n * Serialize a name value pair into a cookie string suitable for\n * http headers. An optional options object specifies cookie parameters.\n *\n * stringifySetCookie({ name: 'foo', value: 'bar', httpOnly: true })\n * => \"foo=bar; HttpOnly\"\n */\nexport function stringifySetCookie(cookie, options) {\n const enc = options?.encode || defaultEncode;\n if (!cookieNameRegExp.test(cookie.name)) {\n throw new TypeError(`argument name is invalid: ${cookie.name}`);\n }\n const value = cookie.value == null ? \"\" : enc(cookie.value);\n if (!cookieValueRegExp.test(value)) {\n throw new TypeError(`argument val is invalid: ${cookie.value}`);\n }\n let str = cookie.name + \"=\" + value;\n if (cookie.maxAge !== undefined) {\n if (!Number.isInteger(cookie.maxAge)) {\n throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);\n }\n str += \"; Max-Age=\" + cookie.maxAge;\n }\n if (cookie.domain) {\n if (!domainValueRegExp.test(cookie.domain)) {\n throw new TypeError(`option domain is invalid: ${cookie.domain}`);\n }\n str += \"; Domain=\" + cookie.domain;\n }\n if (cookie.path) {\n if (!pathValueRegExp.test(cookie.path)) {\n throw new TypeError(`option path is invalid: ${cookie.path}`);\n }\n str += \"; Path=\" + cookie.path;\n }\n if (cookie.expires) {\n if (!Number.isFinite(cookie.expires.valueOf())) {\n throw new TypeError(`option expires is invalid: ${cookie.expires}`);\n }\n str += \"; Expires=\" + cookie.expires.toUTCString();\n }\n if (cookie.httpOnly) {\n str += \"; HttpOnly\";\n }\n if (cookie.secure) {\n str += \"; Secure\";\n }\n if (cookie.partitioned) {\n str += \"; Partitioned\";\n }\n if (cookie.priority) {\n const priority = typeof cookie.priority === \"string\"\n ? cookie.priority.toLowerCase()\n : undefined;\n switch (priority) {\n case \"low\":\n str += \"; Priority=Low\";\n break;\n case \"medium\":\n str += \"; Priority=Medium\";\n break;\n case \"high\":\n str += \"; Priority=High\";\n break;\n default:\n throw new TypeError(`option priority is invalid: ${cookie.priority}`);\n }\n }\n if (cookie.sameSite) {\n const sameSite = typeof cookie.sameSite === \"string\"\n ? cookie.sameSite.toLowerCase()\n : cookie.sameSite;\n switch (sameSite) {\n case true:\n case \"strict\":\n str += \"; SameSite=Strict\";\n break;\n case \"lax\":\n str += \"; SameSite=Lax\";\n break;\n case \"none\":\n str += \"; SameSite=None\";\n break;\n default:\n throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);\n }\n }\n return str;\n}\n/**\n * Deserialize a `Set-Cookie` header into an object.\n *\n * parseSetCookie('foo=bar; HttpOnly')\n * => { name: 'foo', value: 'bar', httpOnly: true }\n */\nexport function parseSetCookie(str, options) {\n const dec = options?.decode || decode;\n const len = str.length;\n const endIdx = endIndex(str, 0, len);\n let eqIdx = eqIndex(str, 0, len);\n const setCookie = eqIdx < endIdx\n ? {\n name: valueSlice(str, 0, eqIdx),\n value: dec(valueSlice(str, eqIdx + 1, endIdx)),\n }\n : { name: \"\", value: dec(valueSlice(str, 0, endIdx)) };\n let index = endIdx + 1;\n while (index < len) {\n const endIdx = endIndex(str, index, len);\n if (eqIdx < index)\n eqIdx = eqIndex(str, index, len);\n const attr = eqIdx < endIdx\n ? valueSlice(str, index, eqIdx)\n : valueSlice(str, index, endIdx);\n const val = eqIdx < endIdx ? valueSlice(str, eqIdx + 1, endIdx) : undefined;\n switch (attr.toLowerCase()) {\n case \"httponly\":\n setCookie.httpOnly = true;\n break;\n case \"secure\":\n setCookie.secure = true;\n break;\n case \"partitioned\":\n setCookie.partitioned = true;\n break;\n case \"domain\":\n setCookie.domain = val;\n break;\n case \"path\":\n setCookie.path = val;\n break;\n case \"max-age\":\n if (val && maxAgeRegExp.test(val))\n setCookie.maxAge = Number(val);\n break;\n case \"expires\":\n if (!val)\n break;\n const date = new Date(val);\n if (Number.isFinite(date.valueOf()))\n setCookie.expires = date;\n break;\n case \"priority\":\n if (!val)\n break;\n const priority = val.toLowerCase();\n if (priority === \"low\" ||\n priority === \"medium\" ||\n priority === \"high\") {\n setCookie.priority = priority;\n }\n break;\n case \"samesite\":\n if (!val)\n break;\n const sameSite = val.toLowerCase();\n if (sameSite === \"lax\" ||\n sameSite === \"strict\" ||\n sameSite === \"none\") {\n setCookie.sameSite = sameSite;\n }\n break;\n }\n index = endIdx + 1;\n }\n return setCookie;\n}\n/**\n * Find the next `;` character, or return `len`.\n */\nfunction endIndex(str, min, len) {\n const index = str.indexOf(\";\", min);\n return index === -1 ? len : index;\n}\n/**\n * Find the next `=` character, or return `len`.\n */\nfunction eqIndex(str, min, len) {\n const index = str.indexOf(\"=\", min);\n return index === -1 ? len : index;\n}\n/**\n * Slice out a value between startPod to max.\n */\nfunction valueSlice(str, min, max) {\n if (min === max)\n return \"\";\n let start = min;\n let end = max;\n do {\n const code = str.charCodeAt(start);\n if (code !== 32 /* */ && code !== 9 /* \\t */)\n break;\n } while (++start < end);\n while (end > start) {\n const code = str.charCodeAt(end - 1);\n if (code !== 32 /* */ && code !== 9 /* \\t */)\n break;\n end--;\n }\n return str.slice(start, end);\n}\n/**\n * URL-decode string value. Optimized to skip native call when no %.\n */\nfunction decode(str) {\n if (str.indexOf(\"%\") === -1)\n return str;\n try {\n return decodeURIComponent(str);\n }\n catch (e) {\n return str;\n }\n}\n/**\n * URL-encode string value. Optimized to skip native call for roundtrip-safe cookie-octet values.\n */\nfunction defaultEncode(str) {\n return cookieOctetRegExp.test(str) ? str : encodeURIComponent(str);\n}\n//# sourceMappingURL=index.js.map"],"ignoreList":[2],"mappings":";;;;;;;;;;;;;;;AAcA,IAAa,sBAAsB,OAAO,IAAI,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;ACe1E,IAAM,iBAAiB;;;;;AAMvB,SAAS,aAAa,OAAe,OAAuB;CAC1D,MAAM,OAAO,MAAM,WAAW,KAAK;CACnC,IAAI,OAAO,MAAQ,SAAS,OAAQ,OAAO,KACzC,OAAO,KAAK,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;CAE/C,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