@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.14

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 (58) hide show
  1. package/README.md +14 -232
  2. package/dist/await.d.ts +67 -0
  3. package/dist/build/index.js +2013 -191
  4. package/dist/cli/index.js +2007 -190
  5. package/dist/client.d.ts +33 -2
  6. package/dist/client.js +65 -1
  7. package/dist/deferred-ndjson.d.ts +32 -0
  8. package/dist/error.d.ts +14 -0
  9. package/dist/furin.d.ts +3 -0
  10. package/dist/furin.js +2684 -318
  11. package/dist/lang-detect.d.ts +5 -0
  12. package/dist/link.d.ts +1 -0
  13. package/dist/link.js +1453 -95
  14. package/dist/plugin/index.js +96 -25
  15. package/dist/plugin/transform-client.d.ts +2 -1
  16. package/dist/render/assemble.d.ts +32 -0
  17. package/dist/render/cache.d.ts +7 -0
  18. package/dist/render/element.d.ts +17 -1
  19. package/dist/render/index.d.ts +10 -1
  20. package/dist/render/index.ts +247 -44
  21. package/dist/render/loaders.d.ts +46 -3
  22. package/dist/render/shell.d.ts +16 -6
  23. package/dist/render/shell.ts +27 -12
  24. package/dist/router-provider.d.ts +86 -18
  25. package/dist/router.d.ts +63 -0
  26. package/dist/router.js +2768 -317
  27. package/dist/router.ts +543 -54
  28. package/dist/server-error.d.ts +12 -0
  29. package/dist/utils.d.ts +7 -0
  30. package/package.json +8 -7
  31. package/src/adapter/bun.ts +3 -3
  32. package/src/adapter/static.ts +73 -31
  33. package/src/await.tsx +175 -0
  34. package/src/build/client.ts +4 -8
  35. package/src/build/hydrate.ts +67 -1
  36. package/src/build/route-types.ts +5 -1
  37. package/src/build/scan-server.ts +6 -23
  38. package/src/client.ts +58 -1
  39. package/src/deferred-ndjson.ts +212 -0
  40. package/src/dev-page-plugin.ts +2 -0
  41. package/src/error.ts +18 -1
  42. package/src/furin.ts +12 -2
  43. package/src/lang-detect.ts +46 -0
  44. package/src/link.tsx +16 -3
  45. package/src/plugin/index.ts +7 -8
  46. package/src/plugin/transform-client.ts +108 -39
  47. package/src/render/assemble.ts +67 -0
  48. package/src/render/boundaries.tsx +23 -5
  49. package/src/render/cache.ts +7 -0
  50. package/src/render/default-screens.tsx +4 -11
  51. package/src/render/element.tsx +26 -3
  52. package/src/render/index.ts +247 -44
  53. package/src/render/loaders.ts +221 -18
  54. package/src/render/shell.ts +27 -12
  55. package/src/router-provider.tsx +414 -122
  56. package/src/router.ts +543 -54
  57. package/src/server-error.ts +47 -0
  58. package/src/utils.ts +31 -0
@@ -1,10 +1,19 @@
1
1
  // biome-ignore-all lint/correctness/useHookAtTopLevel: useLogger is not a hook attached to a react component
2
2
  import { createElement, type ReactNode } from "react";
3
3
  import { renderToReadableStream } from "react-dom/server";
4
+ import { toCrossJSON, toCrossJSONAsync } from "seroval";
4
5
  import { FurinNotFoundError } from "../not-found.ts";
5
6
  import type { RootLayout } from "../router.ts";
6
7
  import { normalizeHref, RouterContext, type RouterContextValue } from "../router-provider.tsx";
7
- import { assembleHTML, resolvePath, splitTemplate, streamToString } from "./assemble.ts";
8
+ import { mapWithConcurrency } from "../utils.ts";
9
+ import {
10
+ assembleHTML,
11
+ buildDeferredResolution,
12
+ buildDeferredScript,
13
+ resolvePath,
14
+ splitTemplate,
15
+ streamToString,
16
+ } from "./assemble.ts";
8
17
  import {
9
18
  getISRCache,
10
19
  getSSGCache,
@@ -15,7 +24,7 @@ import {
15
24
  } from "./cache.ts";
16
25
  import { computeErrorDigest } from "./digest.ts";
17
26
  import { buildElement, buildErrorElement, buildNotFoundElement } from "./element.tsx";
18
- import { type LoaderResult, runLoaders } from "./loaders.ts";
27
+ import { type LoaderResult, runLoaders, serializeDeferredRejection } from "./loaders.ts";
19
28
  import { buildHeadInjection, safeJson } from "./shell.ts";
20
29
  import { getDevTemplate, getProductionTemplate } from "./template.ts";
21
30
 
@@ -23,7 +32,7 @@ import { getDevTemplate, getProductionTemplate } from "./template.ts";
23
32
  // biome-ignore lint/performance/noBarrelFile: acnowledged
24
33
  export { type LoaderContext, streamToString } from "./assemble.ts";
25
34
  export { buildElement } from "./element.tsx";
26
- export { type LoaderResult, runLoaders } from "./loaders.ts";
35
+ export { type LoaderResult, runLoaders, serializeDeferredRejection } from "./loaders.ts";
27
36
 
28
37
  // ── Types ────────────────────────────────────────────────────────────────────
29
38
 
@@ -37,13 +46,33 @@ import { generateIndexHtml } from "./shell.ts";
37
46
  interface RenderResult {
38
47
  headers: Record<string, string>;
39
48
  html: string;
49
+ /**
50
+ * NDJSON payload (one CrossJSON-serialised line) carrying the loader's
51
+ * resolved sync + deferred data. Identical in shape to the body the live
52
+ * `/_furin/data` endpoint emits, so the SPA client can consume both
53
+ * interchangeably. Populated for every render, not just SSG, because the
54
+ * static adapter is the only consumer that persists it today but ISR
55
+ * may want it tomorrow for the same reason.
56
+ */
57
+ ndjson: string;
40
58
  status: number;
41
59
  }
42
60
 
43
61
  // ── Shared render preparation ────────────────────────────────────────────────
44
62
 
45
63
  interface PreparedRender {
64
+ /**
65
+ * All props passed to the React component tree. For deferred renders this
66
+ * includes the Promise objects (for `<Await resolve={promise}>`) alongside
67
+ * the scalar sync fields. Never serialise this directly — use `syncData`.
68
+ */
46
69
  componentProps: Record<string, unknown>;
70
+ /**
71
+ * Promise-valued fields from a `defer()` loader return. Undefined for normal
72
+ * (non-deferred) loaders. These are streamed as late `<script>` chunks after
73
+ * the React stream finishes.
74
+ */
75
+ deferredPromises: Record<string, Promise<unknown>> | undefined;
47
76
  element: ReactNode;
48
77
  /** Set when the prepared element is an error UI. Surfaced to the client via
49
78
  * `__FURIN_DATA__.__furinError.digest` and logged server-side. */
@@ -60,6 +89,12 @@ interface PreparedRender {
60
89
  notFoundError?: { data?: unknown; message?: string };
61
90
  ssrContext: RouterContextValue;
62
91
  status: number;
92
+ /**
93
+ * JSON-serialisable subset of `componentProps`. For deferred renders this
94
+ * excludes the Promise fields (those are streamed separately). For normal
95
+ * renders it equals `componentProps`.
96
+ */
97
+ syncData: Record<string, unknown>;
63
98
  template: string;
64
99
  }
65
100
 
@@ -67,6 +102,26 @@ function withSSRRouterContext(element: ReactNode, contextValue: RouterContextVal
67
102
  return createElement(RouterContext.Provider, { value: contextValue }, element);
68
103
  }
69
104
 
105
+ /**
106
+ * defer() streams data progressively — it only makes sense in SSR. In SSG/ISR
107
+ * the HTML is pre-rendered and cached, so the deferred fields would be absent
108
+ * from the embedded `__FURIN_DATA__` and the client `<Await>` would hydrate
109
+ * with `undefined`. Fail fast at the loader boundary instead of shipping a
110
+ * page that crashes on hydration.
111
+ */
112
+ function assertDeferredModeAllowed(
113
+ route: ResolvedRoute,
114
+ deferredPromises: Record<string, Promise<unknown>> | undefined
115
+ ): void {
116
+ if (deferredPromises !== undefined && route.mode !== "ssr") {
117
+ throw new Error(
118
+ `[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` +
119
+ "defer() streams data progressively and is only supported in SSR. " +
120
+ "Return the data directly (await it inside the loader) or switch the route to SSR mode."
121
+ );
122
+ }
123
+ }
124
+
70
125
  /**
71
126
  * Shared pipeline steps used by both `renderToHTML` (buffered) and `renderSSR`
72
127
  * (streaming). Runs loaders, builds props, head injection, resolves template,
@@ -89,7 +144,7 @@ async function prepareRender(
89
144
  precomputedLoaderResult: LoaderResult | undefined
90
145
  ): Promise<PreparedRender | Response> {
91
146
  const loaderStart = Date.now();
92
- const loaderResult = precomputedLoaderResult ?? (await runLoaders(route, ctx, root.route));
147
+ const loaderResult = precomputedLoaderResult ?? (await runLoaders(route, ctx));
93
148
  const loader_ms = Date.now() - loaderStart;
94
149
 
95
150
  if (loaderResult.type === "redirect") {
@@ -105,10 +160,18 @@ async function prepareRender(
105
160
  const isNotFound = loaderResult.type === "not-found";
106
161
  const isError = loaderResult.type === "error";
107
162
  const isFallback = isNotFound || isError;
108
- const data = isFallback ? {} : loaderResult.data;
163
+ const syncData = isFallback ? {} : loaderResult.syncData;
164
+ const deferredPromises =
165
+ !isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
166
+ assertDeferredModeAllowed(route, deferredPromises);
167
+
109
168
  const headers = loaderResult.headers;
169
+ // componentProps merges sync data + Promise objects so React receives them
170
+ // all as props. The Promise objects are used by <Await resolve={promise}>.
171
+ // Serialisation always uses syncData (which excludes Promises).
110
172
  const componentProps = {
111
- ...data,
173
+ ...syncData,
174
+ ...(deferredPromises ?? {}),
112
175
  params: ctx.params,
113
176
  query: ctx.query,
114
177
  path: ctx.path,
@@ -134,8 +197,14 @@ async function prepareRender(
134
197
  notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
135
198
  } else if (loaderResult.type === "error") {
136
199
  errorDigest = computeErrorDigest(loaderResult.error);
137
- element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
138
- status = 500;
200
+ element = buildErrorElement(
201
+ route.error ?? root.error,
202
+ loaderResult.error,
203
+ errorDigest,
204
+ loaderResult.message,
205
+ loaderResult.status
206
+ );
207
+ status = loaderResult.status;
139
208
  } else {
140
209
  element = buildElement(route, componentProps, root.route);
141
210
  }
@@ -165,12 +234,14 @@ async function prepareRender(
165
234
 
166
235
  return {
167
236
  componentProps,
237
+ deferredPromises,
168
238
  element,
169
239
  errorDigest,
170
240
  headData,
171
241
  headers,
172
242
  loader_ms,
173
243
  notFoundError,
244
+ syncData,
174
245
  ssrContext,
175
246
  status,
176
247
  template,
@@ -217,13 +288,14 @@ function renderForPath(
217
288
  },
218
289
  });
219
290
 
220
- const { componentProps, element, headData, headers, status, template } = prepared;
291
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
221
292
  const stream = await renderToReadableStream(element);
222
293
  await stream.allReady;
223
294
  const reactHtml = await streamToString(stream);
224
295
  return {
225
- html: assembleHTML(template, headData, reactHtml, componentProps),
296
+ html: assembleHTML(template, headData, reactHtml, syncData),
226
297
  headers,
298
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
227
299
  status,
228
300
  };
229
301
  },
@@ -231,6 +303,29 @@ function renderForPath(
231
303
  );
232
304
  }
233
305
 
306
+ /**
307
+ * Serialises a loader's `syncData` + `deferredPromises` into the same one-line
308
+ * NDJSON shape the live `/_furin/data` endpoint emits. Used by the static
309
+ * adapter to persist a parseable payload at a static-friendly URL so SPA
310
+ * navigation works on file-server deployments (GitHub Pages, S3, …).
311
+ *
312
+ * Mirrors the body construction in `createDataEndpoint` so both code paths
313
+ * stay in lockstep: any future change to the on-the-wire format only needs
314
+ * to land in one of these two call sites and the test suite will catch the
315
+ * other via the `__furin_data.ndjson is parseable` regression test.
316
+ */
317
+ async function serializeLoaderDataNdjson(
318
+ syncData: Record<string, unknown>,
319
+ deferredPromises: Record<string, Promise<unknown>> | undefined
320
+ ): Promise<string> {
321
+ const payload: Record<string, unknown> = {
322
+ ...syncData,
323
+ ...(deferredPromises ?? {}),
324
+ };
325
+ const serialized = await toCrossJSONAsync(payload);
326
+ return `${JSON.stringify(serialized)}\n`;
327
+ }
328
+
234
329
  // ── Core pipeline ────────────────────────────────────────────────────────────
235
330
 
236
331
  export async function renderToHTML(
@@ -245,15 +340,16 @@ export async function renderToHTML(
245
340
  throw prepared;
246
341
  }
247
342
 
248
- const { componentProps, element, headData, headers, status, template } = prepared;
343
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
249
344
 
250
345
  const stream = await renderToReadableStream(element);
251
346
  await stream.allReady;
252
347
  const reactHtml = await streamToString(stream);
253
348
 
254
349
  return {
255
- html: assembleHTML(template, headData, reactHtml, componentProps),
350
+ html: assembleHTML(template, headData, reactHtml, syncData),
256
351
  headers,
352
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
257
353
  status,
258
354
  };
259
355
  }
@@ -292,7 +388,12 @@ export async function prerenderSSG(
292
388
  }
293
389
  const result = renderResult;
294
390
 
295
- const entry: SsgCacheEntry = { html: result.html, cachedAt: Date.now(), status: result.status };
391
+ const entry: SsgCacheEntry = {
392
+ cachedAt: Date.now(),
393
+ html: result.html,
394
+ ndjson: result.ndjson,
395
+ status: result.status,
396
+ };
296
397
  setSSGCache(resolvedPath, entry);
297
398
 
298
399
  return entry;
@@ -320,7 +421,7 @@ export async function renderSSR(
320
421
  },
321
422
  });
322
423
 
323
- const { componentProps, element, headData, headers, template } = prepared;
424
+ const { deferredPromises, element, headData, headers, syncData, template } = prepared;
324
425
 
325
426
  // Split template around placeholders
326
427
  const { headPre, bodyPre, bodyPost } = splitTemplate(template);
@@ -346,7 +447,7 @@ export async function renderSSR(
346
447
  try {
347
448
  reactStream = await renderToReadableStream(
348
449
  withSSRRouterContext(
349
- buildErrorElement(route.error ?? root.error, shellError, finalDigest),
450
+ buildErrorElement(route.error ?? root.error, shellError, finalDigest, undefined, 500),
350
451
  prepared.ssrContext
351
452
  )
352
453
  );
@@ -355,45 +456,79 @@ export async function renderSSR(
355
456
  // pure markup and cannot crash.
356
457
  reactStream = await renderToReadableStream(
357
458
  withSSRRouterContext(
358
- buildErrorElement(undefined, shellError, finalDigest),
459
+ buildErrorElement(undefined, shellError, finalDigest, undefined, 500),
359
460
  prepared.ssrContext
360
461
  )
361
462
  );
362
463
  }
363
464
  }
364
465
 
365
- // In error-recovery mode, don't inject loader data (it may contain the
366
- // failing state that caused the crash). Use an empty payload so rehydration
367
- // is a no-op rather than repeating the error. When we DO have a digest
368
- // (either from loader error or shell recovery), expose it under __furinError
369
- // so the client-side ErrorBoundary can surface the same id on rehydrate.
370
- const dataPayload: Record<string, unknown> = shellErrored ? {} : { ...componentProps };
466
+ // ── Data injection ───────────────────────────────────────────────────────────
467
+ //
468
+ // There are two modes:
469
+ //
470
+ // A) Deferred mode (deferredPromises present, no shell error):
471
+ // - Inject buildDeferredScript(syncData) BEFORE the React stream (so the
472
+ // registry is available when React hydrates the Suspense boundaries).
473
+ // - After the React stream, inject one late `<script>` per deferred Promise
474
+ // (resolve or reject based on the outcome).
475
+ // - __FURIN_DATA__ is still injected for the syncData + error signals.
476
+ //
477
+ // B) Normal mode (no deferredPromises, or shell errored):
478
+ // - Inject __FURIN_DATA__ JSON script at the end (existing behaviour).
479
+ //
480
+ // In both cases, error-recovery mode clears componentProps to avoid replaying
481
+ // the failing state during rehydration.
482
+
483
+ const dataPayload: Record<string, unknown> = shellErrored ? {} : { ...syncData };
371
484
  if (finalDigest) {
372
- dataPayload.__furinError = { digest: finalDigest };
485
+ dataPayload.__furinError = { digest: finalDigest, status };
373
486
  }
374
- // Slice 8 — SPA 404 signal. When the loader threw `notFound()`, the response
375
- // status is 404 and the body contains the rendered not-found UI. We ALSO
376
- // embed a machine-readable signal in __FURIN_DATA__ so that a mid-SPA-nav
377
- // client can detect the case without guessing from the HTML, and render the
378
- // not-found component inline instead of performing a jarring full-page
379
- // reload. Mirrors the existing `__furinError.digest` channel for 500s.
487
+ // Slice 8 — SPA 404 signal.
380
488
  if (status === 404 && !shellErrored) {
381
489
  dataPayload.__furinStatus = 404;
382
490
  if (prepared.notFoundError) {
383
491
  dataPayload.__furinNotFound = prepared.notFoundError;
384
492
  }
385
493
  }
494
+ // Invariant: __furinError and __furinNotFound are mutually exclusive — one is
495
+ // a notFound() signal (renders not-found.tsx), the other is an error.tsx
496
+ // signal. They are gated by distinct LoaderResult variants in prepareRender,
497
+ // so collisions would indicate a bug. Dev assert to lock the invariant.
498
+ if (
499
+ process.env.NODE_ENV !== "production" &&
500
+ dataPayload.__furinError !== undefined &&
501
+ dataPayload.__furinNotFound !== undefined
502
+ ) {
503
+ throw new Error(
504
+ "[furin] internal invariant violated: __furinError and __furinNotFound were both set on the same SSR payload. Open a bug — these signals are mutually exclusive."
505
+ );
506
+ }
507
+
508
+ const hasDeferred = !shellErrored && deferredPromises !== undefined;
509
+
510
+ // The deferred registry script is injected before the React stream so client
511
+ // Suspense boundaries can access `window.__FURIN_DEFERRED__` synchronously.
512
+ const deferredKeys = hasDeferred ? Object.keys(deferredPromises) : [];
513
+ const deferredSetupScript = hasDeferred ? buildDeferredScript(deferredKeys) : "";
514
+
515
+ // The standard __FURIN_DATA__ script is always injected (for SPA nav signal,
516
+ // error digest, and non-deferred data). It is the single source of sync
517
+ // loader data — the deferred registry only carries the resolve/reject API.
386
518
  const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(
387
519
  dataPayload
388
520
  )}</script>`;
389
521
 
390
- // Pipe head + React stream + tail into a single ReadableStream
522
+ // Pipe head + React stream + (late scripts) + tail into a single ReadableStream
391
523
  const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
392
524
  const writer = writable.getWriter();
393
525
  const enc = new TextEncoder();
394
526
 
395
527
  (async () => {
396
- await writer.write(enc.encode(headPre + headData + bodyPre));
528
+ // Head section — includes the deferred registry if needed
529
+ await writer.write(enc.encode(headPre + headData + deferredSetupScript + bodyPre));
530
+
531
+ // React stream (may contain Suspense-resolved chunks)
397
532
  const reader = reactStream.getReader();
398
533
  for (;;) {
399
534
  const { done, value } = await reader.read();
@@ -402,7 +537,35 @@ export async function renderSSR(
402
537
  }
403
538
  await writer.write(value);
404
539
  }
405
- await writer.write(enc.encode(dataScript + bodyPost));
540
+
541
+ const [earlyBodyPost, finalBodyPost] = hasDeferred
542
+ ? splitBeforeBodyClose(bodyPost)
543
+ : ["", bodyPost];
544
+ await writer.write(enc.encode(dataScript + earlyBodyPost));
545
+
546
+ // After React stream and hydration script: inject late resolution scripts
547
+ // for each deferred Promise IN SETTLE ORDER (not insertion order). Kicking
548
+ // off all awaits in parallel and writing on settlement is the whole point
549
+ // of `defer()`: a fast field must not be held hostage by a slow sibling.
550
+ // The WritableStreamDefaultWriter serialises concurrent .write() calls
551
+ // internally, so chunks cannot interleave even though awaits race.
552
+ if (hasDeferred) {
553
+ await Promise.all(
554
+ Object.entries(deferredPromises).map(async ([key, promise]) => {
555
+ try {
556
+ const resolvedValue = await promise;
557
+ const chunk = toCrossJSON(resolvedValue);
558
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "resolve")));
559
+ } catch (err) {
560
+ const normalized = await serializeDeferredRejection(err);
561
+ const chunk = toCrossJSON(normalized);
562
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "reject")));
563
+ }
564
+ })
565
+ );
566
+ }
567
+
568
+ await writer.write(enc.encode(finalBodyPost));
406
569
  await writer.close();
407
570
  })().catch((err) => writer.abort(err));
408
571
 
@@ -416,6 +579,14 @@ export async function renderSSR(
416
579
  });
417
580
  }
418
581
 
582
+ function splitBeforeBodyClose(bodyPost: string): [string, string] {
583
+ const index = bodyPost.toLowerCase().lastIndexOf("</body>");
584
+ if (index === -1) {
585
+ return [bodyPost, ""];
586
+ }
587
+ return [bodyPost.slice(0, index), bodyPost.slice(index)];
588
+ }
589
+
419
590
  // ── Catch-all 404 ────────────────────────────────────────────────────────────
420
591
 
421
592
  /**
@@ -623,12 +794,12 @@ async function renderISRNon200(
623
794
  phase: "shell",
624
795
  },
625
796
  });
626
- fallbackProps.__furinError = { digest: finalDigest };
797
+ fallbackProps.__furinError = { digest: finalDigest, status: finalStatus };
627
798
  fallbackProps.__furinStatus = 500;
628
799
  try {
629
800
  reactStream = await renderToReadableStream(
630
801
  withSSRRouterContext(
631
- buildErrorElement(route.error ?? root.error, shellError, finalDigest),
802
+ buildErrorElement(route.error ?? root.error, shellError, finalDigest, undefined, 500),
632
803
  prepared.ssrContext
633
804
  )
634
805
  );
@@ -637,14 +808,14 @@ async function renderISRNon200(
637
808
  // cannot crash).
638
809
  reactStream = await renderToReadableStream(
639
810
  withSSRRouterContext(
640
- buildErrorElement(undefined, shellError, finalDigest),
811
+ buildErrorElement(undefined, shellError, finalDigest, undefined, 500),
641
812
  prepared.ssrContext
642
813
  )
643
814
  );
644
815
  }
645
816
  }
646
817
  if (!fallbackProps.__furinError && errorDigest) {
647
- fallbackProps.__furinError = { digest: errorDigest };
818
+ fallbackProps.__furinError = { digest: errorDigest, status };
648
819
  }
649
820
 
650
821
  await reactStream.allReady;
@@ -697,7 +868,7 @@ export async function handleISR(
697
868
  return prepared;
698
869
  }
699
870
 
700
- const { componentProps, element, headData, template, status, errorDigest } = prepared;
871
+ const { element, headData, syncData, template, status, errorDigest } = prepared;
701
872
 
702
873
  if (status !== 200) {
703
874
  return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
@@ -706,7 +877,7 @@ export async function handleISR(
706
877
  const stream = await renderToReadableStream(element);
707
878
  await stream.allReady;
708
879
  const reactHtml = await streamToString(stream);
709
- const html = assembleHTML(template, headData, reactHtml, componentProps);
880
+ const html = assembleHTML(template, headData, reactHtml, syncData);
710
881
  const generatedAt = Date.now();
711
882
 
712
883
  useLogger().set({
@@ -761,12 +932,42 @@ export async function warmSSGCache(
761
932
  warmupLogger.emit();
762
933
 
763
934
  // Collect all (route, params) render tasks, handling per-route errors early.
935
+ type StaticParamsResult =
936
+ | { error: unknown; route: ResolvedRoute }
937
+ | { paramSets: Record<string, string>[]; route: ResolvedRoute };
938
+
939
+ const staticParamsResults: StaticParamsResult[] = await mapWithConcurrency(
940
+ targets,
941
+ SSG_WARM_CONCURRENCY,
942
+ async (route) => {
943
+ try {
944
+ const paramSets = (await route.page.staticParams?.()) ?? [];
945
+ return { route, paramSets };
946
+ } catch (err) {
947
+ return { error: err, route };
948
+ }
949
+ }
950
+ );
951
+
764
952
  const tasks: Array<() => Promise<void>> = [];
765
- for (const route of targets) {
766
- let paramSets: Record<string, string>[];
767
- try {
768
- paramSets = (await route.page.staticParams?.()) ?? [];
769
- } catch (err) {
953
+ for (const result of staticParamsResults) {
954
+ if ("error" in result) {
955
+ const errorLogger = createLogger({});
956
+ errorLogger.set({
957
+ furin: {
958
+ render: "ssg",
959
+ action: "warmup_failed",
960
+ route: result.route.pattern,
961
+ },
962
+ });
963
+ errorLogger.error(
964
+ result.error instanceof Error ? result.error : new Error(String(result.error))
965
+ );
966
+ errorLogger.emit();
967
+ continue;
968
+ }
969
+ const { route, paramSets } = result;
970
+ if (!Array.isArray(paramSets)) {
770
971
  const errorLogger = createLogger({});
771
972
  errorLogger.set({
772
973
  furin: {
@@ -775,7 +976,9 @@ export async function warmSSGCache(
775
976
  route: route.pattern,
776
977
  },
777
978
  });
778
- errorLogger.error(err instanceof Error ? err : new Error(String(err)));
979
+ errorLogger.error(
980
+ new Error(`staticParams() for "${route.pattern}" returned a non-array value`)
981
+ );
779
982
  errorLogger.emit();
780
983
  continue;
781
984
  }
@@ -1,10 +1,19 @@
1
1
  import type { Context } from "elysia";
2
- import type { RuntimeRoute } from "../client";
3
2
  import { type FurinNotFoundError } from "../not-found.ts";
4
3
  import type { ResolvedRoute } from "../router";
5
4
  export type LoaderResult = {
6
5
  type: "data";
7
- data: Record<string, unknown>;
6
+ /**
7
+ * Synchronous (JSON-serialisable) loader fields. Injected into the initial
8
+ * HTML shell as `__FURIN_DATA__` / the deferred registry's `_data` object.
9
+ */
10
+ syncData: Record<string, unknown>;
11
+ /**
12
+ * Promise-valued fields from a `defer()` return. `undefined` when the page
13
+ * loader did not call `defer()`. Streamed as late `<script>` resolution
14
+ * chunks (SSR) or as NDJSON chunks via `/_furin/data` (SPA nav).
15
+ */
16
+ deferredPromises: Record<string, Promise<unknown>> | undefined;
8
17
  headers: Record<string, string>;
9
18
  } | {
10
19
  type: "redirect";
@@ -15,7 +24,41 @@ export type LoaderResult = {
15
24
  headers: Record<string, string>;
16
25
  } | {
17
26
  type: "error";
27
+ /**
28
+ * Original thrown value, kept for digest computation and server logging.
29
+ * For thrown `Response` objects this is the Response instance whose body
30
+ * has already been consumed by `runLoaders` (do NOT read it again).
31
+ */
18
32
  error: unknown;
33
+ /** HTTP status to return. Default 500; sourced from `Response.status` for thrown Response objects. */
34
+ status: number;
35
+ /**
36
+ * Safe public message extracted at the loader boundary. For thrown
37
+ * `Response` objects: response body or `statusText`. For thrown `Error`
38
+ * / non-Error values: a generic "Something went wrong" string (the raw
39
+ * error/message is never leaked here — `errorMessageOf` decides what to
40
+ * surface from the original `error` value when an `error.tsx` fallback
41
+ * exists).
42
+ */
43
+ message: string;
19
44
  headers: Record<string, string>;
20
45
  };
21
- export declare function runLoaders(route: ResolvedRoute, ctx: Context, _rootLayout: RuntimeRoute): Promise<LoaderResult>;
46
+ /**
47
+ * Normalises an error thrown inside a deferred Promise into a value that is
48
+ * safe to send through `toCrossJSON` and that preserves the original semantics
49
+ * after `fromCrossJSON` on the client.
50
+ *
51
+ * Symmetric to the rejection handling in `runLoaders` (lines 247-272) but for
52
+ * the *deferred* path, where the rejection is delivered to a client-side
53
+ * `<Await>` instead of becoming a top-level response.
54
+ *
55
+ * - `notFound()` → `Error` carrying `__furinBrand` + `data` so the
56
+ * client-side `isNotFoundError()` (duck-typed)
57
+ * recognises the rejection.
58
+ * - `Response(status, body)` → `Error` carrying `__furinStatus` and the
59
+ * body/statusText as `message`.
60
+ * - `Error` → returned unchanged.
61
+ * - anything else → wrapped in `new Error(String(value))`.
62
+ */
63
+ export declare function serializeDeferredRejection(err: unknown): Promise<unknown>;
64
+ export declare function runLoaders(route: ResolvedRoute, ctx: Context): Promise<LoaderResult>;
@@ -20,10 +20,20 @@ export declare function generateIndexHtml(): string;
20
20
  * Called after Bun.build() completes so we can inject the correct entry chunk
21
21
  * and CSS paths derived from result.outputs.
22
22
  *
23
- * @param buildId - Short hash identifying this specific build. Injected as a
24
- * `<meta name="furin-build-id">` tag so the client can detect stale deploys.
25
- * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico").
26
- * When provided, a `<link rel="icon">` tag is injected so browsers can locate
27
- * the favicon even when the site is served from a sub-path.
23
+ * @param entryChunk - Hashed URL of the client entry script.
24
+ * @param cssChunks - Hashed URLs of the CSS chunks to inject as `<link>`s.
25
+ * @param buildId - Short hash identifying this specific build (or `undefined`
26
+ * for static exports where stale-deploy detection is not applicable).
27
+ * Injected as a `<meta name="furin-build-id">` tag so the client can
28
+ * detect stale deploys.
29
+ * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico"),
30
+ * or `undefined` when no favicon is provided. When set, a `<link rel="icon">`
31
+ * tag is injected so browsers can locate the favicon even when the site is
32
+ * served from a sub-path.
33
+ * @param staticMode - `true` for static exports, `false` for SSR/ISR. When
34
+ * `true`, a `<meta name="furin-mode" content="static">` tag is injected so
35
+ * the SPA client knows to fetch loader data from the per-route
36
+ * `__furin_data.ndjson` file instead of the runtime `/_furin/data` endpoint
37
+ * (which doesn't exist on a static host).
28
38
  */
29
- export declare function generateProdIndexHtml(entryChunk: string, cssChunks: string[], buildId?: string, faviconHref?: string): string;
39
+ export declare function generateProdIndexHtml(entryChunk: string, cssChunks: string[], buildId: string | undefined, faviconHref: string | undefined, staticMode: boolean): string;