@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -232
- package/dist/auto-invalidate/index.d.ts +4 -0
- package/dist/auto-invalidate/plugin.d.ts +38 -0
- package/dist/auto-invalidate/registry.d.ts +9 -0
- package/dist/auto-invalidate/runtime.d.ts +9 -0
- package/dist/auto-invalidate/types.d.ts +12 -0
- package/dist/await.d.ts +67 -0
- package/dist/build/index.js +2095 -185
- package/dist/cli/index.js +2070 -182
- package/dist/client.d.ts +51 -4
- package/dist/client.js +65 -1
- package/dist/deferred-ndjson.d.ts +32 -0
- package/dist/error.d.ts +14 -0
- package/dist/furin.d.ts +8 -0
- package/dist/furin.js +2927 -319
- package/dist/lang-detect.d.ts +5 -0
- package/dist/link.d.ts +1 -0
- package/dist/link.js +1453 -95
- package/dist/plugin/index.js +96 -25
- package/dist/plugin/transform-client.d.ts +2 -1
- package/dist/render/assemble.d.ts +32 -0
- package/dist/render/cache.d.ts +7 -0
- package/dist/render/element.d.ts +17 -1
- package/dist/render/index.d.ts +10 -1
- package/dist/render/index.ts +250 -44
- package/dist/render/loaders.d.ts +46 -3
- package/dist/render/shell.d.ts +16 -6
- package/dist/render/shell.ts +27 -12
- package/dist/router-provider.d.ts +86 -18
- package/dist/router.d.ts +66 -0
- package/dist/router.js +2909 -374
- package/dist/router.ts +586 -54
- package/dist/server-error.d.ts +12 -0
- package/dist/utils.d.ts +7 -0
- package/package.json +8 -7
- package/src/adapter/bun.ts +3 -3
- package/src/adapter/static.ts +73 -31
- package/src/auto-invalidate/index.ts +10 -0
- package/src/auto-invalidate/plugin.ts +25 -0
- package/src/auto-invalidate/registry.ts +60 -0
- package/src/auto-invalidate/runtime.ts +133 -0
- package/src/auto-invalidate/types.ts +16 -0
- package/src/await.tsx +175 -0
- package/src/build/client.ts +4 -8
- package/src/build/hydrate.ts +67 -1
- package/src/build/route-types.ts +29 -3
- package/src/build/scan-server.ts +6 -23
- package/src/client.ts +80 -3
- package/src/deferred-ndjson.ts +212 -0
- package/src/dev-page-plugin.ts +2 -0
- package/src/error.ts +18 -1
- package/src/furin.ts +19 -2
- package/src/lang-detect.ts +46 -0
- package/src/link.tsx +16 -3
- package/src/plugin/index.ts +7 -8
- package/src/plugin/transform-client.ts +108 -39
- package/src/render/assemble.ts +67 -0
- package/src/render/boundaries.tsx +23 -5
- package/src/render/cache.ts +14 -0
- package/src/render/default-screens.tsx +4 -11
- package/src/render/dev-cache.ts +5 -0
- package/src/render/element.tsx +26 -3
- package/src/render/index.ts +250 -44
- package/src/render/loaders.ts +219 -18
- package/src/render/shell.ts +27 -12
- package/src/router-provider.tsx +414 -122
- package/src/router.ts +586 -54
- package/src/server-error.ts +47 -0
- package/src/utils.ts +31 -0
package/dist/render/index.ts
CHANGED
|
@@ -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 {
|
|
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,11 +32,12 @@ 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
|
|
|
30
39
|
import type { Context } from "elysia";
|
|
40
|
+
import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
|
|
31
41
|
import { createLogger, runInSyntheticRenderScope, useLogger } from "../context-logger.ts";
|
|
32
42
|
import type { ResolvedRoute } from "../router.ts";
|
|
33
43
|
import { IS_DEV } from "../runtime-env.ts";
|
|
@@ -37,13 +47,33 @@ import { generateIndexHtml } from "./shell.ts";
|
|
|
37
47
|
interface RenderResult {
|
|
38
48
|
headers: Record<string, string>;
|
|
39
49
|
html: string;
|
|
50
|
+
/**
|
|
51
|
+
* NDJSON payload (one CrossJSON-serialised line) carrying the loader's
|
|
52
|
+
* resolved sync + deferred data. Identical in shape to the body the live
|
|
53
|
+
* `/_furin/data` endpoint emits, so the SPA client can consume both
|
|
54
|
+
* interchangeably. Populated for every render, not just SSG, because the
|
|
55
|
+
* static adapter is the only consumer that persists it today but ISR
|
|
56
|
+
* may want it tomorrow for the same reason.
|
|
57
|
+
*/
|
|
58
|
+
ndjson: string;
|
|
40
59
|
status: number;
|
|
41
60
|
}
|
|
42
61
|
|
|
43
62
|
// ── Shared render preparation ────────────────────────────────────────────────
|
|
44
63
|
|
|
45
64
|
interface PreparedRender {
|
|
65
|
+
/**
|
|
66
|
+
* All props passed to the React component tree. For deferred renders this
|
|
67
|
+
* includes the Promise objects (for `<Await resolve={promise}>`) alongside
|
|
68
|
+
* the scalar sync fields. Never serialise this directly — use `syncData`.
|
|
69
|
+
*/
|
|
46
70
|
componentProps: Record<string, unknown>;
|
|
71
|
+
/**
|
|
72
|
+
* Promise-valued fields from a `defer()` loader return. Undefined for normal
|
|
73
|
+
* (non-deferred) loaders. These are streamed as late `<script>` chunks after
|
|
74
|
+
* the React stream finishes.
|
|
75
|
+
*/
|
|
76
|
+
deferredPromises: Record<string, Promise<unknown>> | undefined;
|
|
47
77
|
element: ReactNode;
|
|
48
78
|
/** Set when the prepared element is an error UI. Surfaced to the client via
|
|
49
79
|
* `__FURIN_DATA__.__furinError.digest` and logged server-side. */
|
|
@@ -60,6 +90,12 @@ interface PreparedRender {
|
|
|
60
90
|
notFoundError?: { data?: unknown; message?: string };
|
|
61
91
|
ssrContext: RouterContextValue;
|
|
62
92
|
status: number;
|
|
93
|
+
/**
|
|
94
|
+
* JSON-serialisable subset of `componentProps`. For deferred renders this
|
|
95
|
+
* excludes the Promise fields (those are streamed separately). For normal
|
|
96
|
+
* renders it equals `componentProps`.
|
|
97
|
+
*/
|
|
98
|
+
syncData: Record<string, unknown>;
|
|
63
99
|
template: string;
|
|
64
100
|
}
|
|
65
101
|
|
|
@@ -67,6 +103,26 @@ function withSSRRouterContext(element: ReactNode, contextValue: RouterContextVal
|
|
|
67
103
|
return createElement(RouterContext.Provider, { value: contextValue }, element);
|
|
68
104
|
}
|
|
69
105
|
|
|
106
|
+
/**
|
|
107
|
+
* defer() streams data progressively — it only makes sense in SSR. In SSG/ISR
|
|
108
|
+
* the HTML is pre-rendered and cached, so the deferred fields would be absent
|
|
109
|
+
* from the embedded `__FURIN_DATA__` and the client `<Await>` would hydrate
|
|
110
|
+
* with `undefined`. Fail fast at the loader boundary instead of shipping a
|
|
111
|
+
* page that crashes on hydration.
|
|
112
|
+
*/
|
|
113
|
+
function assertDeferredModeAllowed(
|
|
114
|
+
route: ResolvedRoute,
|
|
115
|
+
deferredPromises: Record<string, Promise<unknown>> | undefined
|
|
116
|
+
): void {
|
|
117
|
+
if (deferredPromises !== undefined && route.mode !== "ssr") {
|
|
118
|
+
throw new Error(
|
|
119
|
+
`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` +
|
|
120
|
+
"defer() streams data progressively and is only supported in SSR. " +
|
|
121
|
+
"Return the data directly (await it inside the loader) or switch the route to SSR mode."
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
70
126
|
/**
|
|
71
127
|
* Shared pipeline steps used by both `renderToHTML` (buffered) and `renderSSR`
|
|
72
128
|
* (streaming). Runs loaders, builds props, head injection, resolves template,
|
|
@@ -89,7 +145,7 @@ async function prepareRender(
|
|
|
89
145
|
precomputedLoaderResult: LoaderResult | undefined
|
|
90
146
|
): Promise<PreparedRender | Response> {
|
|
91
147
|
const loaderStart = Date.now();
|
|
92
|
-
const loaderResult = precomputedLoaderResult ?? (await runLoaders(route, ctx
|
|
148
|
+
const loaderResult = precomputedLoaderResult ?? (await runLoaders(route, ctx));
|
|
93
149
|
const loader_ms = Date.now() - loaderStart;
|
|
94
150
|
|
|
95
151
|
if (loaderResult.type === "redirect") {
|
|
@@ -105,10 +161,18 @@ async function prepareRender(
|
|
|
105
161
|
const isNotFound = loaderResult.type === "not-found";
|
|
106
162
|
const isError = loaderResult.type === "error";
|
|
107
163
|
const isFallback = isNotFound || isError;
|
|
108
|
-
const
|
|
164
|
+
const syncData = isFallback ? {} : loaderResult.syncData;
|
|
165
|
+
const deferredPromises =
|
|
166
|
+
!isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
|
|
167
|
+
assertDeferredModeAllowed(route, deferredPromises);
|
|
168
|
+
|
|
109
169
|
const headers = loaderResult.headers;
|
|
170
|
+
// componentProps merges sync data + Promise objects so React receives them
|
|
171
|
+
// all as props. The Promise objects are used by <Await resolve={promise}>.
|
|
172
|
+
// Serialisation always uses syncData (which excludes Promises).
|
|
110
173
|
const componentProps = {
|
|
111
|
-
...
|
|
174
|
+
...syncData,
|
|
175
|
+
...(deferredPromises ?? {}),
|
|
112
176
|
params: ctx.params,
|
|
113
177
|
query: ctx.query,
|
|
114
178
|
path: ctx.path,
|
|
@@ -134,8 +198,14 @@ async function prepareRender(
|
|
|
134
198
|
notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
|
|
135
199
|
} else if (loaderResult.type === "error") {
|
|
136
200
|
errorDigest = computeErrorDigest(loaderResult.error);
|
|
137
|
-
element = buildErrorElement(
|
|
138
|
-
|
|
201
|
+
element = buildErrorElement(
|
|
202
|
+
route.error ?? root.error,
|
|
203
|
+
loaderResult.error,
|
|
204
|
+
errorDigest,
|
|
205
|
+
loaderResult.message,
|
|
206
|
+
loaderResult.status
|
|
207
|
+
);
|
|
208
|
+
status = loaderResult.status;
|
|
139
209
|
} else {
|
|
140
210
|
element = buildElement(route, componentProps, root.route);
|
|
141
211
|
}
|
|
@@ -165,12 +235,14 @@ async function prepareRender(
|
|
|
165
235
|
|
|
166
236
|
return {
|
|
167
237
|
componentProps,
|
|
238
|
+
deferredPromises,
|
|
168
239
|
element,
|
|
169
240
|
errorDigest,
|
|
170
241
|
headData,
|
|
171
242
|
headers,
|
|
172
243
|
loader_ms,
|
|
173
244
|
notFoundError,
|
|
245
|
+
syncData,
|
|
174
246
|
ssrContext,
|
|
175
247
|
status,
|
|
176
248
|
template,
|
|
@@ -217,13 +289,14 @@ function renderForPath(
|
|
|
217
289
|
},
|
|
218
290
|
});
|
|
219
291
|
|
|
220
|
-
const {
|
|
292
|
+
const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
|
|
221
293
|
const stream = await renderToReadableStream(element);
|
|
222
294
|
await stream.allReady;
|
|
223
295
|
const reactHtml = await streamToString(stream);
|
|
224
296
|
return {
|
|
225
|
-
html: assembleHTML(template, headData, reactHtml,
|
|
297
|
+
html: assembleHTML(template, headData, reactHtml, syncData),
|
|
226
298
|
headers,
|
|
299
|
+
ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
|
|
227
300
|
status,
|
|
228
301
|
};
|
|
229
302
|
},
|
|
@@ -231,6 +304,29 @@ function renderForPath(
|
|
|
231
304
|
);
|
|
232
305
|
}
|
|
233
306
|
|
|
307
|
+
/**
|
|
308
|
+
* Serialises a loader's `syncData` + `deferredPromises` into the same one-line
|
|
309
|
+
* NDJSON shape the live `/_furin/data` endpoint emits. Used by the static
|
|
310
|
+
* adapter to persist a parseable payload at a static-friendly URL so SPA
|
|
311
|
+
* navigation works on file-server deployments (GitHub Pages, S3, …).
|
|
312
|
+
*
|
|
313
|
+
* Mirrors the body construction in `createDataEndpoint` so both code paths
|
|
314
|
+
* stay in lockstep: any future change to the on-the-wire format only needs
|
|
315
|
+
* to land in one of these two call sites and the test suite will catch the
|
|
316
|
+
* other via the `__furin_data.ndjson is parseable` regression test.
|
|
317
|
+
*/
|
|
318
|
+
async function serializeLoaderDataNdjson(
|
|
319
|
+
syncData: Record<string, unknown>,
|
|
320
|
+
deferredPromises: Record<string, Promise<unknown>> | undefined
|
|
321
|
+
): Promise<string> {
|
|
322
|
+
const payload: Record<string, unknown> = {
|
|
323
|
+
...syncData,
|
|
324
|
+
...(deferredPromises ?? {}),
|
|
325
|
+
};
|
|
326
|
+
const serialized = await toCrossJSONAsync(payload);
|
|
327
|
+
return `${JSON.stringify(serialized)}\n`;
|
|
328
|
+
}
|
|
329
|
+
|
|
234
330
|
// ── Core pipeline ────────────────────────────────────────────────────────────
|
|
235
331
|
|
|
236
332
|
export async function renderToHTML(
|
|
@@ -245,15 +341,16 @@ export async function renderToHTML(
|
|
|
245
341
|
throw prepared;
|
|
246
342
|
}
|
|
247
343
|
|
|
248
|
-
const {
|
|
344
|
+
const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
|
|
249
345
|
|
|
250
346
|
const stream = await renderToReadableStream(element);
|
|
251
347
|
await stream.allReady;
|
|
252
348
|
const reactHtml = await streamToString(stream);
|
|
253
349
|
|
|
254
350
|
return {
|
|
255
|
-
html: assembleHTML(template, headData, reactHtml,
|
|
351
|
+
html: assembleHTML(template, headData, reactHtml, syncData),
|
|
256
352
|
headers,
|
|
353
|
+
ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
|
|
257
354
|
status,
|
|
258
355
|
};
|
|
259
356
|
}
|
|
@@ -292,8 +389,14 @@ export async function prerenderSSG(
|
|
|
292
389
|
}
|
|
293
390
|
const result = renderResult;
|
|
294
391
|
|
|
295
|
-
const entry: SsgCacheEntry = {
|
|
392
|
+
const entry: SsgCacheEntry = {
|
|
393
|
+
cachedAt: Date.now(),
|
|
394
|
+
html: result.html,
|
|
395
|
+
ndjson: result.ndjson,
|
|
396
|
+
status: result.status,
|
|
397
|
+
};
|
|
296
398
|
setSSGCache(resolvedPath, entry);
|
|
399
|
+
autoInvalidateRegistry.registerLoaderTags(resolvedPath, route.tags);
|
|
297
400
|
|
|
298
401
|
return entry;
|
|
299
402
|
}
|
|
@@ -320,7 +423,7 @@ export async function renderSSR(
|
|
|
320
423
|
},
|
|
321
424
|
});
|
|
322
425
|
|
|
323
|
-
const {
|
|
426
|
+
const { deferredPromises, element, headData, headers, syncData, template } = prepared;
|
|
324
427
|
|
|
325
428
|
// Split template around placeholders
|
|
326
429
|
const { headPre, bodyPre, bodyPost } = splitTemplate(template);
|
|
@@ -346,7 +449,7 @@ export async function renderSSR(
|
|
|
346
449
|
try {
|
|
347
450
|
reactStream = await renderToReadableStream(
|
|
348
451
|
withSSRRouterContext(
|
|
349
|
-
buildErrorElement(route.error ?? root.error, shellError, finalDigest),
|
|
452
|
+
buildErrorElement(route.error ?? root.error, shellError, finalDigest, undefined, 500),
|
|
350
453
|
prepared.ssrContext
|
|
351
454
|
)
|
|
352
455
|
);
|
|
@@ -355,45 +458,79 @@ export async function renderSSR(
|
|
|
355
458
|
// pure markup and cannot crash.
|
|
356
459
|
reactStream = await renderToReadableStream(
|
|
357
460
|
withSSRRouterContext(
|
|
358
|
-
buildErrorElement(undefined, shellError, finalDigest),
|
|
461
|
+
buildErrorElement(undefined, shellError, finalDigest, undefined, 500),
|
|
359
462
|
prepared.ssrContext
|
|
360
463
|
)
|
|
361
464
|
);
|
|
362
465
|
}
|
|
363
466
|
}
|
|
364
467
|
|
|
365
|
-
//
|
|
366
|
-
//
|
|
367
|
-
//
|
|
368
|
-
//
|
|
369
|
-
//
|
|
370
|
-
|
|
468
|
+
// ── Data injection ───────────────────────────────────────────────────────────
|
|
469
|
+
//
|
|
470
|
+
// There are two modes:
|
|
471
|
+
//
|
|
472
|
+
// A) Deferred mode (deferredPromises present, no shell error):
|
|
473
|
+
// - Inject buildDeferredScript(syncData) BEFORE the React stream (so the
|
|
474
|
+
// registry is available when React hydrates the Suspense boundaries).
|
|
475
|
+
// - After the React stream, inject one late `<script>` per deferred Promise
|
|
476
|
+
// (resolve or reject based on the outcome).
|
|
477
|
+
// - __FURIN_DATA__ is still injected for the syncData + error signals.
|
|
478
|
+
//
|
|
479
|
+
// B) Normal mode (no deferredPromises, or shell errored):
|
|
480
|
+
// - Inject __FURIN_DATA__ JSON script at the end (existing behaviour).
|
|
481
|
+
//
|
|
482
|
+
// In both cases, error-recovery mode clears componentProps to avoid replaying
|
|
483
|
+
// the failing state during rehydration.
|
|
484
|
+
|
|
485
|
+
const dataPayload: Record<string, unknown> = shellErrored ? {} : { ...syncData };
|
|
371
486
|
if (finalDigest) {
|
|
372
|
-
dataPayload.__furinError = { digest: finalDigest };
|
|
487
|
+
dataPayload.__furinError = { digest: finalDigest, status };
|
|
373
488
|
}
|
|
374
|
-
// Slice 8 — SPA 404 signal.
|
|
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.
|
|
489
|
+
// Slice 8 — SPA 404 signal.
|
|
380
490
|
if (status === 404 && !shellErrored) {
|
|
381
491
|
dataPayload.__furinStatus = 404;
|
|
382
492
|
if (prepared.notFoundError) {
|
|
383
493
|
dataPayload.__furinNotFound = prepared.notFoundError;
|
|
384
494
|
}
|
|
385
495
|
}
|
|
496
|
+
// Invariant: __furinError and __furinNotFound are mutually exclusive — one is
|
|
497
|
+
// a notFound() signal (renders not-found.tsx), the other is an error.tsx
|
|
498
|
+
// signal. They are gated by distinct LoaderResult variants in prepareRender,
|
|
499
|
+
// so collisions would indicate a bug. Dev assert to lock the invariant.
|
|
500
|
+
if (
|
|
501
|
+
process.env.NODE_ENV !== "production" &&
|
|
502
|
+
dataPayload.__furinError !== undefined &&
|
|
503
|
+
dataPayload.__furinNotFound !== undefined
|
|
504
|
+
) {
|
|
505
|
+
throw new Error(
|
|
506
|
+
"[furin] internal invariant violated: __furinError and __furinNotFound were both set on the same SSR payload. Open a bug — these signals are mutually exclusive."
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const hasDeferred = !shellErrored && deferredPromises !== undefined;
|
|
511
|
+
|
|
512
|
+
// The deferred registry script is injected before the React stream so client
|
|
513
|
+
// Suspense boundaries can access `window.__FURIN_DEFERRED__` synchronously.
|
|
514
|
+
const deferredKeys = hasDeferred ? Object.keys(deferredPromises) : [];
|
|
515
|
+
const deferredSetupScript = hasDeferred ? buildDeferredScript(deferredKeys) : "";
|
|
516
|
+
|
|
517
|
+
// The standard __FURIN_DATA__ script is always injected (for SPA nav signal,
|
|
518
|
+
// error digest, and non-deferred data). It is the single source of sync
|
|
519
|
+
// loader data — the deferred registry only carries the resolve/reject API.
|
|
386
520
|
const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(
|
|
387
521
|
dataPayload
|
|
388
522
|
)}</script>`;
|
|
389
523
|
|
|
390
|
-
// Pipe head + React stream + tail into a single ReadableStream
|
|
524
|
+
// Pipe head + React stream + (late scripts) + tail into a single ReadableStream
|
|
391
525
|
const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
|
|
392
526
|
const writer = writable.getWriter();
|
|
393
527
|
const enc = new TextEncoder();
|
|
394
528
|
|
|
395
529
|
(async () => {
|
|
396
|
-
|
|
530
|
+
// Head section — includes the deferred registry if needed
|
|
531
|
+
await writer.write(enc.encode(headPre + headData + deferredSetupScript + bodyPre));
|
|
532
|
+
|
|
533
|
+
// React stream (may contain Suspense-resolved chunks)
|
|
397
534
|
const reader = reactStream.getReader();
|
|
398
535
|
for (;;) {
|
|
399
536
|
const { done, value } = await reader.read();
|
|
@@ -402,7 +539,35 @@ export async function renderSSR(
|
|
|
402
539
|
}
|
|
403
540
|
await writer.write(value);
|
|
404
541
|
}
|
|
405
|
-
|
|
542
|
+
|
|
543
|
+
const [earlyBodyPost, finalBodyPost] = hasDeferred
|
|
544
|
+
? splitBeforeBodyClose(bodyPost)
|
|
545
|
+
: ["", bodyPost];
|
|
546
|
+
await writer.write(enc.encode(dataScript + earlyBodyPost));
|
|
547
|
+
|
|
548
|
+
// After React stream and hydration script: inject late resolution scripts
|
|
549
|
+
// for each deferred Promise IN SETTLE ORDER (not insertion order). Kicking
|
|
550
|
+
// off all awaits in parallel and writing on settlement is the whole point
|
|
551
|
+
// of `defer()`: a fast field must not be held hostage by a slow sibling.
|
|
552
|
+
// The WritableStreamDefaultWriter serialises concurrent .write() calls
|
|
553
|
+
// internally, so chunks cannot interleave even though awaits race.
|
|
554
|
+
if (hasDeferred) {
|
|
555
|
+
await Promise.all(
|
|
556
|
+
Object.entries(deferredPromises).map(async ([key, promise]) => {
|
|
557
|
+
try {
|
|
558
|
+
const resolvedValue = await promise;
|
|
559
|
+
const chunk = toCrossJSON(resolvedValue);
|
|
560
|
+
await writer.write(enc.encode(buildDeferredResolution(key, chunk, "resolve")));
|
|
561
|
+
} catch (err) {
|
|
562
|
+
const normalized = await serializeDeferredRejection(err);
|
|
563
|
+
const chunk = toCrossJSON(normalized);
|
|
564
|
+
await writer.write(enc.encode(buildDeferredResolution(key, chunk, "reject")));
|
|
565
|
+
}
|
|
566
|
+
})
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
await writer.write(enc.encode(finalBodyPost));
|
|
406
571
|
await writer.close();
|
|
407
572
|
})().catch((err) => writer.abort(err));
|
|
408
573
|
|
|
@@ -416,6 +581,14 @@ export async function renderSSR(
|
|
|
416
581
|
});
|
|
417
582
|
}
|
|
418
583
|
|
|
584
|
+
function splitBeforeBodyClose(bodyPost: string): [string, string] {
|
|
585
|
+
const index = bodyPost.toLowerCase().lastIndexOf("</body>");
|
|
586
|
+
if (index === -1) {
|
|
587
|
+
return [bodyPost, ""];
|
|
588
|
+
}
|
|
589
|
+
return [bodyPost.slice(0, index), bodyPost.slice(index)];
|
|
590
|
+
}
|
|
591
|
+
|
|
419
592
|
// ── Catch-all 404 ────────────────────────────────────────────────────────────
|
|
420
593
|
|
|
421
594
|
/**
|
|
@@ -623,12 +796,12 @@ async function renderISRNon200(
|
|
|
623
796
|
phase: "shell",
|
|
624
797
|
},
|
|
625
798
|
});
|
|
626
|
-
fallbackProps.__furinError = { digest: finalDigest };
|
|
799
|
+
fallbackProps.__furinError = { digest: finalDigest, status: finalStatus };
|
|
627
800
|
fallbackProps.__furinStatus = 500;
|
|
628
801
|
try {
|
|
629
802
|
reactStream = await renderToReadableStream(
|
|
630
803
|
withSSRRouterContext(
|
|
631
|
-
buildErrorElement(route.error ?? root.error, shellError, finalDigest),
|
|
804
|
+
buildErrorElement(route.error ?? root.error, shellError, finalDigest, undefined, 500),
|
|
632
805
|
prepared.ssrContext
|
|
633
806
|
)
|
|
634
807
|
);
|
|
@@ -637,14 +810,14 @@ async function renderISRNon200(
|
|
|
637
810
|
// cannot crash).
|
|
638
811
|
reactStream = await renderToReadableStream(
|
|
639
812
|
withSSRRouterContext(
|
|
640
|
-
buildErrorElement(undefined, shellError, finalDigest),
|
|
813
|
+
buildErrorElement(undefined, shellError, finalDigest, undefined, 500),
|
|
641
814
|
prepared.ssrContext
|
|
642
815
|
)
|
|
643
816
|
);
|
|
644
817
|
}
|
|
645
818
|
}
|
|
646
819
|
if (!fallbackProps.__furinError && errorDigest) {
|
|
647
|
-
fallbackProps.__furinError = { digest: errorDigest };
|
|
820
|
+
fallbackProps.__furinError = { digest: errorDigest, status };
|
|
648
821
|
}
|
|
649
822
|
|
|
650
823
|
await reactStream.allReady;
|
|
@@ -697,7 +870,7 @@ export async function handleISR(
|
|
|
697
870
|
return prepared;
|
|
698
871
|
}
|
|
699
872
|
|
|
700
|
-
const {
|
|
873
|
+
const { element, headData, syncData, template, status, errorDigest } = prepared;
|
|
701
874
|
|
|
702
875
|
if (status !== 200) {
|
|
703
876
|
return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
|
|
@@ -706,7 +879,7 @@ export async function handleISR(
|
|
|
706
879
|
const stream = await renderToReadableStream(element);
|
|
707
880
|
await stream.allReady;
|
|
708
881
|
const reactHtml = await streamToString(stream);
|
|
709
|
-
const html = assembleHTML(template, headData, reactHtml,
|
|
882
|
+
const html = assembleHTML(template, headData, reactHtml, syncData);
|
|
710
883
|
const generatedAt = Date.now();
|
|
711
884
|
|
|
712
885
|
useLogger().set({
|
|
@@ -719,6 +892,7 @@ export async function handleISR(
|
|
|
719
892
|
});
|
|
720
893
|
|
|
721
894
|
setISRCache(cacheKey, { html, generatedAt, revalidate });
|
|
895
|
+
autoInvalidateRegistry.registerLoaderTags(cacheKey, route.tags);
|
|
722
896
|
|
|
723
897
|
const etag = buildId ? `"${buildId}:${generatedAt}"` : null;
|
|
724
898
|
ctx.set.headers["content-type"] = "text/html; charset=utf-8";
|
|
@@ -761,12 +935,42 @@ export async function warmSSGCache(
|
|
|
761
935
|
warmupLogger.emit();
|
|
762
936
|
|
|
763
937
|
// Collect all (route, params) render tasks, handling per-route errors early.
|
|
938
|
+
type StaticParamsResult =
|
|
939
|
+
| { error: unknown; route: ResolvedRoute }
|
|
940
|
+
| { paramSets: Record<string, string>[]; route: ResolvedRoute };
|
|
941
|
+
|
|
942
|
+
const staticParamsResults: StaticParamsResult[] = await mapWithConcurrency(
|
|
943
|
+
targets,
|
|
944
|
+
SSG_WARM_CONCURRENCY,
|
|
945
|
+
async (route) => {
|
|
946
|
+
try {
|
|
947
|
+
const paramSets = (await route.page.staticParams?.()) ?? [];
|
|
948
|
+
return { route, paramSets };
|
|
949
|
+
} catch (err) {
|
|
950
|
+
return { error: err, route };
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
);
|
|
954
|
+
|
|
764
955
|
const tasks: Array<() => Promise<void>> = [];
|
|
765
|
-
for (const
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
956
|
+
for (const result of staticParamsResults) {
|
|
957
|
+
if ("error" in result) {
|
|
958
|
+
const errorLogger = createLogger({});
|
|
959
|
+
errorLogger.set({
|
|
960
|
+
furin: {
|
|
961
|
+
render: "ssg",
|
|
962
|
+
action: "warmup_failed",
|
|
963
|
+
route: result.route.pattern,
|
|
964
|
+
},
|
|
965
|
+
});
|
|
966
|
+
errorLogger.error(
|
|
967
|
+
result.error instanceof Error ? result.error : new Error(String(result.error))
|
|
968
|
+
);
|
|
969
|
+
errorLogger.emit();
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
const { route, paramSets } = result;
|
|
973
|
+
if (!Array.isArray(paramSets)) {
|
|
770
974
|
const errorLogger = createLogger({});
|
|
771
975
|
errorLogger.set({
|
|
772
976
|
furin: {
|
|
@@ -775,7 +979,9 @@ export async function warmSSGCache(
|
|
|
775
979
|
route: route.pattern,
|
|
776
980
|
},
|
|
777
981
|
});
|
|
778
|
-
errorLogger.error(
|
|
982
|
+
errorLogger.error(
|
|
983
|
+
new Error(`staticParams() for "${route.pattern}" returned a non-array value`)
|
|
984
|
+
);
|
|
779
985
|
errorLogger.emit();
|
|
780
986
|
continue;
|
|
781
987
|
}
|
package/dist/render/loaders.d.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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>;
|
package/dist/render/shell.d.ts
CHANGED
|
@@ -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
|
|
24
|
-
*
|
|
25
|
-
* @param
|
|
26
|
-
*
|
|
27
|
-
*
|
|
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
|
|
39
|
+
export declare function generateProdIndexHtml(entryChunk: string, cssChunks: string[], buildId: string | undefined, faviconHref: string | undefined, staticMode: boolean): string;
|