@teyik0/furin 0.2.0-alpha.3 → 0.2.0-alpha.4

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 (54) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/build/compile-entry.ts +109 -109
  4. package/dist/build/entry-template.ts +156 -156
  5. package/dist/build/server-routes-entry.ts +36 -36
  6. package/dist/cli/index.js +0 -0
  7. package/dist/client/link.js +163 -16
  8. package/dist/client/router/abort.d.ts +1 -0
  9. package/dist/client/router/sync-catch-up.d.ts +29 -0
  10. package/dist/furin.d.ts +1 -1
  11. package/dist/furin.js +499 -215
  12. package/dist/server/sync/adapter.d.ts +62 -0
  13. package/dist/server/sync/fingerprint.d.ts +6 -0
  14. package/dist/server/sync/index.d.ts +2 -2
  15. package/dist/server/sync/memory-adapter.d.ts +17 -0
  16. package/dist/server/sync/plugin.d.ts +12 -195
  17. package/dist/server/sync/response.d.ts +4 -0
  18. package/dist/server/sync/stream.d.ts +16 -4
  19. package/package.json +1 -1
  20. package/src/adapter/README.md +13 -13
  21. package/src/build/client.ts +152 -152
  22. package/src/build/compile-entry.ts +109 -109
  23. package/src/build/entry-template.ts +156 -156
  24. package/src/build/hydrate.ts +340 -340
  25. package/src/build/index.ts +152 -152
  26. package/src/build/route-types.ts +145 -145
  27. package/src/build/scan-server.ts +95 -95
  28. package/src/build/server-routes-entry.ts +36 -36
  29. package/src/build/shared.ts +80 -80
  30. package/src/build/ssg-cache.ts +32 -32
  31. package/src/build/types.ts +89 -89
  32. package/src/client/router/abort.ts +5 -0
  33. package/src/client/router/link-utils.ts +184 -184
  34. package/src/client/router/provider.tsx +883 -804
  35. package/src/client/router/sync-catch-up.ts +113 -0
  36. package/src/client/router/types.ts +276 -276
  37. package/src/client/sync.ts +98 -98
  38. package/src/client.ts +369 -369
  39. package/src/furin.ts +465 -465
  40. package/src/server/auto-invalidate/runtime.ts +134 -134
  41. package/src/server/dev-page-plugin.ts +454 -454
  42. package/src/server/render/assemble.ts +160 -160
  43. package/src/server/render/isr.ts +323 -323
  44. package/src/server/render/ssr.ts +591 -585
  45. package/src/server/router/plugin.ts +384 -384
  46. package/src/server/sync/adapter.ts +65 -0
  47. package/src/server/sync/config.ts +29 -29
  48. package/src/server/sync/fingerprint.ts +44 -0
  49. package/src/server/sync/index.ts +15 -14
  50. package/src/server/sync/memory-adapter.ts +196 -0
  51. package/src/server/sync/plugin.ts +200 -108
  52. package/src/server/sync/response.ts +77 -0
  53. package/src/server/sync/stream.ts +152 -144
  54. package/src/shared/deferred-ndjson.ts +7 -0
@@ -1,585 +1,591 @@
1
- // biome-ignore-all lint/correctness/useHookAtTopLevel: useLogger is not a hook attached to a react component
2
-
3
- import type { Context } from "elysia";
4
- import { createElement, type ReactNode } from "react";
5
- import { renderToReadableStream } from "react-dom/server";
6
- import { toCrossJSON, toCrossJSONAsync } from "seroval";
7
- import {
8
- normalizeHref,
9
- RouterContext,
10
- type RouterContextValue,
11
- SearchStoreContext,
12
- } from "../../client/router/index.ts";
13
- import {
14
- createSearchStore,
15
- searchSnapshotFromRouterContext,
16
- } from "../../client/router/search-store.ts";
17
- import { computeErrorDigest } from "../../shared/digest.ts";
18
- import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
19
- import { runInSyntheticRenderScope, useLogger } from "../context-logger.ts";
20
- // FurinNotFoundError is used indirectly via buildNotFoundElement in element.tsx
21
- import type { ResolvedRoute, RootLayout } from "../router/index.ts";
22
- import { IS_DEV } from "../runtime-env.ts";
23
- import {
24
- assembleHTML,
25
- buildDeferredResolution,
26
- buildDeferredScript,
27
- buildSyncRuntimeScript,
28
- resolvePath,
29
- splitTemplate,
30
- streamToString,
31
- } from "./assemble.ts";
32
- import { buildElement, buildErrorElement, buildNotFoundElement } from "./element.tsx";
33
- import { type LoaderResult, runLoaders, serializeDeferredRejection } from "./loaders.ts";
34
- import { buildHeadInjection, generateIndexHtml, safeJson } from "./shell.ts";
35
- import { getDevTemplate, getProductionTemplate } from "./template.ts";
36
-
37
- // Re-export types consumed by sibling render modules (not a public barrel).
38
- export type { LoaderContext } from "./assemble.ts";
39
- export type { LoaderResult } from "./loaders.ts";
40
-
41
- // ── Types ────────────────────────────────────────────────────────────────────
42
-
43
- export interface RenderResult {
44
- headers: Record<string, string>;
45
- html: string;
46
- /**
47
- * NDJSON payload (one CrossJSON-serialised line) carrying the loader's
48
- * resolved sync + deferred data. Identical in shape to the body the live
49
- * `/_furin/data` endpoint emits, so the SPA client can consume both
50
- * interchangeably.
51
- */
52
- ndjson: string;
53
- status: number;
54
- }
55
-
56
- export interface PreparedRender {
57
- /**
58
- * All props passed to the React component tree. For deferred renders this
59
- * includes the Promise objects (for `<Await resolve={promise}>`) alongside
60
- * the scalar sync fields. Never serialise this directly — use `syncData`.
61
- */
62
- componentProps: Record<string, unknown>;
63
- /**
64
- * Promise-valued fields from a `defer()` loader return. Undefined for normal
65
- * (non-deferred) loaders. These are streamed as late `<script>` chunks after
66
- * the React stream finishes.
67
- */
68
- deferredPromises: Record<string, Promise<unknown>> | undefined;
69
- element: ReactNode;
70
- /** Set when the prepared element is an error UI. */
71
- errorDigest?: string;
72
- headData: string;
73
- headers: Record<string, string>;
74
- loader_ms: number;
75
- /**
76
- * Populated only when the loader threw `notFound()`. Mirrored into
77
- * `__FURIN_DATA__.__furinNotFound` so the client-side can render the
78
- * not-found UI inline on SPA navigation.
79
- */
80
- notFoundError?: { data?: unknown; message?: string };
81
- ssrContext: RouterContextValue;
82
- status: number;
83
- /**
84
- * JSON-serialisable subset of `componentProps`. For deferred renders this
85
- * excludes the Promise fields (those are streamed separately).
86
- */
87
- syncData: Record<string, unknown>;
88
- template: string;
89
- }
90
-
91
- // ── Shared helpers ───────────────────────────────────────────────────────────
92
-
93
- export function withSSRRouterContext(
94
- element: ReactNode,
95
- contextValue: RouterContextValue
96
- ): ReactNode {
97
- return createElement(
98
- SearchStoreContext.Provider,
99
- { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) },
100
- createElement(RouterContext.Provider, { value: contextValue }, element)
101
- );
102
- }
103
-
104
- interface ShellFallbackResult {
105
- /**
106
- * Set when the primary element threw synchronously during render and a
107
- * fallback error UI was streamed instead. Carries the digest so the caller
108
- * can surface it in logs and the `__furinError` payload.
109
- */
110
- shellError: { digest: string } | undefined;
111
- stream: Awaited<ReturnType<typeof renderToReadableStream>>;
112
- }
113
-
114
- /**
115
- * Renders `element` to a React stream, recovering from a synchronous shell
116
- * throw with a 500 error UI. The supplied error component (route-level, else
117
- * root-level) is tried first; if it ALSO throws, the built-in error element is
118
- * used, so a broken custom error page can never take down the whole response.
119
- *
120
- * Shared by SSR (which pipes the stream) and ISR/SSG non-200 (which drains it
121
- * to a string) — both start from this same React stream and only diverge in how
122
- * they consume it and which fields they log.
123
- */
124
- export async function renderElementWithShellFallback(
125
- element: ReactNode,
126
- errorComponent: Parameters<typeof buildErrorElement>[0],
127
- ssrContext: RouterContextValue
128
- ): Promise<ShellFallbackResult> {
129
- try {
130
- return { stream: await renderToReadableStream(element), shellError: undefined };
131
- } catch (error) {
132
- const digest = computeErrorDigest(error);
133
- try {
134
- const stream = await renderToReadableStream(
135
- withSSRRouterContext(
136
- buildErrorElement(errorComponent, error, digest, undefined, 500),
137
- ssrContext
138
- )
139
- );
140
- return { stream, shellError: { digest } };
141
- } catch {
142
- const stream = await renderToReadableStream(
143
- withSSRRouterContext(
144
- buildErrorElement(undefined, error, digest, undefined, 500),
145
- ssrContext
146
- )
147
- );
148
- return { stream, shellError: { digest } };
149
- }
150
- }
151
- }
152
-
153
- /**
154
- * defer() streams data progressively — it only makes sense in SSR. In SSG/ISR
155
- * the HTML is pre-rendered and cached, so the deferred fields would be absent
156
- * from the embedded `__FURIN_DATA__` and the client `<Await>` would hydrate
157
- * with `undefined`. Fail fast at the loader boundary.
158
- */
159
- export function assertDeferredModeAllowed(
160
- route: ResolvedRoute,
161
- deferredPromises: Record<string, Promise<unknown>> | undefined
162
- ): void {
163
- if (deferredPromises !== undefined && route.mode !== "ssr") {
164
- throw new Error(
165
- `[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` +
166
- "defer() streams data progressively and is only supported in SSR. " +
167
- "Return the data directly (await it inside the loader) or switch the route to SSR mode."
168
- );
169
- }
170
- }
171
-
172
- function currentHrefFromContext(ctx: Context): string {
173
- const pathUrl = new URL(ctx.path, "http://furin.local");
174
- const requestUrl = new URL(ctx.request.url);
175
- return normalizeHref(pathUrl.pathname) + (pathUrl.search || requestUrl.search);
176
- }
177
-
178
- /**
179
- * Builds the success-path element and head injection. `head()` is user code
180
- * that runs synchronously, outside the render pipeline's shell-error handling,
181
- * so a throw is converted into a 500 error render that surfaces through the
182
- * framework error UI instead of escaping `prepareRender` and crashing the
183
- * request. Re-throws when `throwOnFailure` is set (build-time SSG) so CI fails
184
- * loudly.
185
- */
186
- function buildSuccessRender(
187
- route: ResolvedRoute,
188
- root: RootLayout,
189
- componentProps: Record<string, unknown>,
190
- throwOnFailure: boolean
191
- ): { element: ReactNode; headData: string; errorDigest: string | undefined; status: number } {
192
- try {
193
- const headData = buildHeadInjection(route.page?.head?.(componentProps));
194
- const element = buildElement(route, componentProps, root.route);
195
- return { element, headData, errorDigest: undefined, status: 200 };
196
- } catch (headError) {
197
- if (throwOnFailure) {
198
- throw headError;
199
- }
200
- const errorDigest = computeErrorDigest(headError);
201
- const element = buildErrorElement(
202
- route.error ?? root.error,
203
- headError,
204
- errorDigest,
205
- undefined,
206
- 500
207
- );
208
- return { element, headData: "", errorDigest, status: 500 };
209
- }
210
- }
211
-
212
- /**
213
- * Shared pipeline steps used by both `renderToHTML` (buffered) and `renderSSR`
214
- * (streaming). Runs loaders, builds props, head injection, resolves template,
215
- * and creates the React element.
216
- *
217
- * Returns the redirect Response directly when a loader redirects, so callers
218
- * never need try/catch for redirect handling.
219
- */
220
- export async function prepareRender(
221
- route: ResolvedRoute,
222
- ctx: Context,
223
- root: RootLayout,
224
- basePath: string | undefined,
225
- throwOnFailure: boolean,
226
- precomputedLoaderResult: LoaderResult | undefined,
227
- searchRoutes?: SearchRouteMetadata[]
228
- ): Promise<PreparedRender | Response> {
229
- const loaderStart = Date.now();
230
- const loaderResult = precomputedLoaderResult ?? (await runLoaders(route, ctx));
231
- const loader_ms = Date.now() - loaderStart;
232
-
233
- if (loaderResult.type === "redirect") {
234
- return loaderResult.response;
235
- }
236
-
237
- // Build-time paths (SSG) opt into re-throwing so CI fails loudly instead of
238
- // silently generating a 404/500 page for buggy loaders.
239
- if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
240
- throw loaderResult.error;
241
- }
242
-
243
- const isNotFound = loaderResult.type === "not-found";
244
- const isError = loaderResult.type === "error";
245
- const isFallback = isNotFound || isError;
246
- const syncData = isFallback ? {} : loaderResult.syncData;
247
- const deferredPromises =
248
- !isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
249
- assertDeferredModeAllowed(route, deferredPromises);
250
-
251
- const headers = loaderResult.headers;
252
- const componentProps = {
253
- ...syncData,
254
- ...(deferredPromises ?? {}),
255
- params: ctx.params,
256
- query: ctx.query,
257
- path: ctx.path,
258
- };
259
-
260
- const prodTemplate = getProductionTemplate();
261
- const template =
262
- prodTemplate ??
263
- (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
264
-
265
- let element: ReactNode;
266
- let headData = "";
267
- let status = 200;
268
- let errorDigest: string | undefined;
269
- let notFoundError: { data?: unknown; message?: string } | undefined;
270
- if (loaderResult.type === "not-found") {
271
- element = buildNotFoundElement(route.notFound ?? root.notFound, loaderResult.error);
272
- status = 404;
273
- notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
274
- } else if (loaderResult.type === "error") {
275
- errorDigest = computeErrorDigest(loaderResult.error);
276
- element = buildErrorElement(
277
- route.error ?? root.error,
278
- loaderResult.error,
279
- errorDigest,
280
- loaderResult.message,
281
- loaderResult.status
282
- );
283
- status = loaderResult.status;
284
- } else {
285
- const success = buildSuccessRender(route, root, componentProps, throwOnFailure);
286
- element = success.element;
287
- headData = success.headData;
288
- errorDigest = success.errorDigest;
289
- status = success.status;
290
- }
291
-
292
- const ssrContext: RouterContextValue = {
293
- basePath: basePath ?? "",
294
- currentHref: currentHrefFromContext(ctx),
295
- search: (ctx.query as SearchParamsInput | undefined) ?? {},
296
- searchRoutes: searchRoutes ?? [],
297
- navigate: (_href, _opts) => Promise.resolve(),
298
- prefetch: (_href, _opts) => {
299
- /* noop */
300
- },
301
- invalidatePrefetch: (_path, _type) => {
302
- /* noop */
303
- },
304
- refresh: (_opts) => Promise.resolve(),
305
- isNavigating: false,
306
- defaultPreload: "intent",
307
- defaultPreloadDelay: 50,
308
- defaultPreloadStaleTime: 30_000,
309
- };
310
- element = withSSRRouterContext(element, ssrContext);
311
-
312
- return {
313
- componentProps,
314
- deferredPromises,
315
- element,
316
- errorDigest,
317
- headData,
318
- headers,
319
- loader_ms,
320
- notFoundError,
321
- syncData,
322
- ssrContext,
323
- status,
324
- template,
325
- };
326
- }
327
-
328
- // ── Helpers ──────────────────────────────────────────────────────────────────
329
-
330
- export function renderForPath(
331
- route: ResolvedRoute,
332
- params: Record<string, string>,
333
- root: RootLayout,
334
- origin: string,
335
- mode: "ssg" | "isr",
336
- basePath?: string,
337
- searchRoutes?: SearchRouteMetadata[]
338
- ): Promise<RenderResult | Response> {
339
- return runInSyntheticRenderScope(
340
- async () => {
341
- const resolvedPath = resolvePath(route.pattern, params);
342
- const ctx: Context = {
343
- params,
344
- query: {},
345
- request: new Request(`${origin}${resolvedPath}`),
346
- headers: {},
347
- cookie: {},
348
- redirect: (url: string, status: number | undefined) =>
349
- new Response(null, { status: status ?? 302, headers: { Location: url } }),
350
- set: { headers: {} },
351
- path: resolvedPath,
352
- } as Context;
353
-
354
- const prepared = await prepareRender(
355
- route,
356
- ctx,
357
- root,
358
- basePath,
359
- true,
360
- undefined,
361
- searchRoutes
362
- );
363
- if (prepared instanceof Response) {
364
- return prepared;
365
- }
366
-
367
- useLogger().set({
368
- furin: {
369
- render: mode,
370
- route: route.pattern,
371
- cache: mode === "isr" ? "revalidated" : "miss",
372
- loader_ms: prepared.loader_ms,
373
- ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
374
- },
375
- });
376
-
377
- const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
378
- const stream = await renderToReadableStream(element);
379
- await stream.allReady;
380
- const reactHtml = await streamToString(stream);
381
- return {
382
- html: assembleHTML(template, headData, reactHtml, syncData),
383
- headers,
384
- ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
385
- status,
386
- };
387
- },
388
- { route: route.pattern, render: mode }
389
- );
390
- }
391
-
392
- /**
393
- * Serialises a loader's `syncData` + `deferredPromises` into the same one-line
394
- * NDJSON shape the live `/_furin/data` endpoint emits.
395
- */
396
- export async function serializeLoaderDataNdjson(
397
- syncData: Record<string, unknown>,
398
- deferredPromises: Record<string, Promise<unknown>> | undefined
399
- ): Promise<string> {
400
- const payload: Record<string, unknown> = {
401
- ...syncData,
402
- ...(deferredPromises ?? {}),
403
- };
404
- const serialized = await toCrossJSONAsync(payload);
405
- return `${JSON.stringify(serialized)}\n`;
406
- }
407
-
408
- // ── Core pipeline ────────────────────────────────────────────────────────────
409
-
410
- export async function renderToHTML(
411
- route: ResolvedRoute,
412
- ctx: Context,
413
- root: RootLayout,
414
- searchRoutes?: SearchRouteMetadata[]
415
- ): Promise<RenderResult> {
416
- const prepared = await prepareRender(route, ctx, root, undefined, false, undefined, searchRoutes);
417
-
418
- if (prepared instanceof Response) {
419
- throw prepared;
420
- }
421
-
422
- const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
423
-
424
- const stream = await renderToReadableStream(element);
425
- await stream.allReady;
426
- const reactHtml = await streamToString(stream);
427
-
428
- return {
429
- html: assembleHTML(template, headData, reactHtml, syncData),
430
- headers,
431
- ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
432
- status,
433
- };
434
- }
435
-
436
- export async function renderToStream(
437
- route: ResolvedRoute,
438
- ctx: Context,
439
- root: RootLayout
440
- ): Promise<ReadableStream | Response> {
441
- const response = await renderSSR(route, ctx, root, undefined);
442
- if (!response.ok) {
443
- return response;
444
- }
445
- return response.body ?? new ReadableStream();
446
- }
447
-
448
- export async function renderSSR(
449
- route: ResolvedRoute,
450
- ctx: Context,
451
- root: RootLayout,
452
- precomputedLoaderResult: LoaderResult | undefined,
453
- searchRoutes?: SearchRouteMetadata[]
454
- ): Promise<Response> {
455
- const prepared = await prepareRender(
456
- route,
457
- ctx,
458
- root,
459
- undefined,
460
- false,
461
- precomputedLoaderResult,
462
- searchRoutes
463
- );
464
-
465
- if (prepared instanceof Response) {
466
- return prepared;
467
- }
468
-
469
- useLogger().set({
470
- furin: {
471
- render: route.mode,
472
- route: route.pattern,
473
- loader_ms: prepared.loader_ms,
474
- ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
475
- },
476
- });
477
-
478
- const { deferredPromises, element, headData, headers, syncData, template } = prepared;
479
-
480
- const { headPre, bodyPre, bodyPost } = splitTemplate(template);
481
-
482
- const { stream: reactStream, shellError } = await renderElementWithShellFallback(
483
- element,
484
- route.error ?? root.error,
485
- prepared.ssrContext
486
- );
487
- const shellErrored = shellError !== undefined;
488
- let status = prepared.status;
489
- let finalDigest = prepared.errorDigest;
490
- if (shellError) {
491
- status = 500;
492
- finalDigest = shellError.digest;
493
- useLogger().set({
494
- furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" },
495
- });
496
- }
497
-
498
- const dataPayload: Record<string, unknown> = shellErrored ? {} : { ...syncData };
499
- if (finalDigest) {
500
- dataPayload.__furinError = { digest: finalDigest, status };
501
- }
502
- if (status === 404 && !shellErrored) {
503
- dataPayload.__furinStatus = 404;
504
- if (prepared.notFoundError) {
505
- dataPayload.__furinNotFound = prepared.notFoundError;
506
- }
507
- }
508
- if (
509
- process.env.NODE_ENV !== "production" &&
510
- dataPayload.__furinError !== undefined &&
511
- dataPayload.__furinNotFound !== undefined
512
- ) {
513
- throw new Error(
514
- "[furin] internal invariant violated: __furinError and __furinNotFound were both set on the same SSR payload."
515
- );
516
- }
517
-
518
- const hasDeferred = !shellErrored && deferredPromises !== undefined;
519
-
520
- const deferredKeys = hasDeferred ? Object.keys(deferredPromises) : [];
521
- const deferredSetupScript = hasDeferred ? buildDeferredScript(deferredKeys) : "";
522
-
523
- const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(
524
- dataPayload
525
- )}</script>`;
526
- const runtimeScripts = `${buildSyncRuntimeScript()}${dataScript}`;
527
-
528
- const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
529
- const writer = writable.getWriter();
530
- const enc = new TextEncoder();
531
-
532
- (async () => {
533
- await writer.write(enc.encode(headPre + headData + deferredSetupScript + bodyPre));
534
-
535
- const reader = reactStream.getReader();
536
- for (;;) {
537
- const { done, value } = await reader.read();
538
- if (done) {
539
- break;
540
- }
541
- await writer.write(value);
542
- }
543
-
544
- const [earlyBodyPost, finalBodyPost] = hasDeferred
545
- ? splitBeforeBodyClose(bodyPost)
546
- : ["", bodyPost];
547
- await writer.write(enc.encode(runtimeScripts + earlyBodyPost));
548
-
549
- if (hasDeferred) {
550
- await Promise.all(
551
- Object.entries(deferredPromises).map(async ([key, promise]) => {
552
- try {
553
- const resolvedValue = await promise;
554
- const chunk = toCrossJSON(resolvedValue);
555
- await writer.write(enc.encode(buildDeferredResolution(key, chunk, "resolve")));
556
- } catch (err) {
557
- const normalized = await serializeDeferredRejection(err);
558
- const chunk = toCrossJSON(normalized);
559
- await writer.write(enc.encode(buildDeferredResolution(key, chunk, "reject")));
560
- }
561
- })
562
- );
563
- }
564
-
565
- await writer.write(enc.encode(finalBodyPost));
566
- await writer.close();
567
- })().catch((err) => writer.abort(err));
568
-
569
- return new Response(readable, {
570
- status,
571
- headers: {
572
- "Content-Type": "text/html; charset=utf-8",
573
- "Cache-Control": "no-store, no-cache, must-revalidate",
574
- ...headers,
575
- },
576
- });
577
- }
578
-
579
- export function splitBeforeBodyClose(bodyPost: string): [string, string] {
580
- const index = bodyPost.toLowerCase().lastIndexOf("</body>");
581
- if (index === -1) {
582
- return [bodyPost, ""];
583
- }
584
- return [bodyPost.slice(0, index), bodyPost.slice(index)];
585
- }
1
+ // biome-ignore-all lint/correctness/useHookAtTopLevel: useLogger is not a hook attached to a react component
2
+
3
+ import type { Context } from "elysia";
4
+ import { createElement, type ReactNode } from "react";
5
+ import { renderToReadableStream } from "react-dom/server";
6
+ import { toCrossJSON, toCrossJSONAsync } from "seroval";
7
+ import {
8
+ normalizeHref,
9
+ RouterContext,
10
+ type RouterContextValue,
11
+ SearchStoreContext,
12
+ } from "../../client/router/index.ts";
13
+ import {
14
+ createSearchStore,
15
+ searchSnapshotFromRouterContext,
16
+ } from "../../client/router/search-store.ts";
17
+ import { computeErrorDigest } from "../../shared/digest.ts";
18
+ import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
19
+ import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
20
+ import { runInSyntheticRenderScope, useLogger } from "../context-logger.ts";
21
+ // FurinNotFoundError is used indirectly via buildNotFoundElement in element.tsx
22
+ import type { ResolvedRoute, RootLayout } from "../router/index.ts";
23
+ import { IS_DEV } from "../runtime-env.ts";
24
+ import {
25
+ assembleHTML,
26
+ buildDeferredResolution,
27
+ buildDeferredScript,
28
+ buildSyncRuntimeScript,
29
+ resolvePath,
30
+ splitTemplate,
31
+ streamToString,
32
+ } from "./assemble.ts";
33
+ import { buildElement, buildErrorElement, buildNotFoundElement } from "./element.tsx";
34
+ import { type LoaderResult, runLoaders, serializeDeferredRejection } from "./loaders.ts";
35
+ import { buildHeadInjection, generateIndexHtml, safeJson } from "./shell.ts";
36
+ import { getDevTemplate, getProductionTemplate } from "./template.ts";
37
+
38
+ // Re-export types consumed by sibling render modules (not a public barrel).
39
+ export type { LoaderContext } from "./assemble.ts";
40
+ export type { LoaderResult } from "./loaders.ts";
41
+
42
+ // ── Types ────────────────────────────────────────────────────────────────────
43
+
44
+ export interface RenderResult {
45
+ headers: Record<string, string>;
46
+ html: string;
47
+ /**
48
+ * NDJSON payload (one CrossJSON-serialised line) carrying the loader's
49
+ * resolved sync + deferred data. Identical in shape to the body the live
50
+ * `/_furin/data` endpoint emits, so the SPA client can consume both
51
+ * interchangeably.
52
+ */
53
+ ndjson: string;
54
+ status: number;
55
+ }
56
+
57
+ export interface PreparedRender {
58
+ /**
59
+ * All props passed to the React component tree. For deferred renders this
60
+ * includes the Promise objects (for `<Await resolve={promise}>`) alongside
61
+ * the scalar sync fields. Never serialise this directly — use `syncData`.
62
+ */
63
+ componentProps: Record<string, unknown>;
64
+ /**
65
+ * Promise-valued fields from a `defer()` loader return. Undefined for normal
66
+ * (non-deferred) loaders. These are streamed as late `<script>` chunks after
67
+ * the React stream finishes.
68
+ */
69
+ deferredPromises: Record<string, Promise<unknown>> | undefined;
70
+ element: ReactNode;
71
+ /** Set when the prepared element is an error UI. */
72
+ errorDigest?: string;
73
+ headData: string;
74
+ headers: Record<string, string>;
75
+ loader_ms: number;
76
+ /**
77
+ * Populated only when the loader threw `notFound()`. Mirrored into
78
+ * `__FURIN_DATA__.__furinNotFound` so the client-side can render the
79
+ * not-found UI inline on SPA navigation.
80
+ */
81
+ notFoundError?: { data?: unknown; message?: string };
82
+ ssrContext: RouterContextValue;
83
+ status: number;
84
+ /**
85
+ * JSON-serialisable subset of `componentProps`. For deferred renders this
86
+ * excludes the Promise fields (those are streamed separately).
87
+ */
88
+ syncData: Record<string, unknown>;
89
+ template: string;
90
+ }
91
+
92
+ // ── Shared helpers ───────────────────────────────────────────────────────────
93
+
94
+ export function withSSRRouterContext(
95
+ element: ReactNode,
96
+ contextValue: RouterContextValue
97
+ ): ReactNode {
98
+ return createElement(
99
+ SearchStoreContext.Provider,
100
+ { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) },
101
+ createElement(RouterContext.Provider, { value: contextValue }, element)
102
+ );
103
+ }
104
+
105
+ interface ShellFallbackResult {
106
+ /**
107
+ * Set when the primary element threw synchronously during render and a
108
+ * fallback error UI was streamed instead. Carries the digest so the caller
109
+ * can surface it in logs and the `__furinError` payload.
110
+ */
111
+ shellError: { digest: string } | undefined;
112
+ stream: Awaited<ReturnType<typeof renderToReadableStream>>;
113
+ }
114
+
115
+ /**
116
+ * Renders `element` to a React stream, recovering from a synchronous shell
117
+ * throw with a 500 error UI. The supplied error component (route-level, else
118
+ * root-level) is tried first; if it ALSO throws, the built-in error element is
119
+ * used, so a broken custom error page can never take down the whole response.
120
+ *
121
+ * Shared by SSR (which pipes the stream) and ISR/SSG non-200 (which drains it
122
+ * to a string) — both start from this same React stream and only diverge in how
123
+ * they consume it and which fields they log.
124
+ */
125
+ export async function renderElementWithShellFallback(
126
+ element: ReactNode,
127
+ errorComponent: Parameters<typeof buildErrorElement>[0],
128
+ ssrContext: RouterContextValue
129
+ ): Promise<ShellFallbackResult> {
130
+ try {
131
+ return { stream: await renderToReadableStream(element), shellError: undefined };
132
+ } catch (error) {
133
+ const digest = computeErrorDigest(error);
134
+ try {
135
+ const stream = await renderToReadableStream(
136
+ withSSRRouterContext(
137
+ buildErrorElement(errorComponent, error, digest, undefined, 500),
138
+ ssrContext
139
+ )
140
+ );
141
+ return { stream, shellError: { digest } };
142
+ } catch {
143
+ const stream = await renderToReadableStream(
144
+ withSSRRouterContext(
145
+ buildErrorElement(undefined, error, digest, undefined, 500),
146
+ ssrContext
147
+ )
148
+ );
149
+ return { stream, shellError: { digest } };
150
+ }
151
+ }
152
+ }
153
+
154
+ /**
155
+ * defer() streams data progressively — it only makes sense in SSR. In SSG/ISR
156
+ * the HTML is pre-rendered and cached, so the deferred fields would be absent
157
+ * from the embedded `__FURIN_DATA__` and the client `<Await>` would hydrate
158
+ * with `undefined`. Fail fast at the loader boundary.
159
+ */
160
+ export function assertDeferredModeAllowed(
161
+ route: ResolvedRoute,
162
+ deferredPromises: Record<string, Promise<unknown>> | undefined
163
+ ): void {
164
+ if (deferredPromises !== undefined && route.mode !== "ssr") {
165
+ throw new Error(
166
+ `[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` +
167
+ "defer() streams data progressively and is only supported in SSR. " +
168
+ "Return the data directly (await it inside the loader) or switch the route to SSR mode."
169
+ );
170
+ }
171
+ }
172
+
173
+ function currentHrefFromContext(ctx: Context): string {
174
+ const pathUrl = new URL(ctx.path, "http://furin.local");
175
+ const requestUrl = new URL(ctx.request.url);
176
+ return normalizeHref(pathUrl.pathname) + (pathUrl.search || requestUrl.search);
177
+ }
178
+
179
+ /**
180
+ * Builds the success-path element and head injection. `head()` is user code
181
+ * that runs synchronously, outside the render pipeline's shell-error handling,
182
+ * so a throw is converted into a 500 error render that surfaces through the
183
+ * framework error UI instead of escaping `prepareRender` and crashing the
184
+ * request. Re-throws when `throwOnFailure` is set (build-time SSG) so CI fails
185
+ * loudly.
186
+ */
187
+ function buildSuccessRender(
188
+ route: ResolvedRoute,
189
+ root: RootLayout,
190
+ componentProps: Record<string, unknown>,
191
+ throwOnFailure: boolean
192
+ ): { element: ReactNode; headData: string; errorDigest: string | undefined; status: number } {
193
+ try {
194
+ const headData = buildHeadInjection(route.page?.head?.(componentProps));
195
+ const element = buildElement(route, componentProps, root.route);
196
+ return { element, headData, errorDigest: undefined, status: 200 };
197
+ } catch (headError) {
198
+ if (throwOnFailure) {
199
+ throw headError;
200
+ }
201
+ const errorDigest = computeErrorDigest(headError);
202
+ const element = buildErrorElement(
203
+ route.error ?? root.error,
204
+ headError,
205
+ errorDigest,
206
+ undefined,
207
+ 500
208
+ );
209
+ return { element, headData: "", errorDigest, status: 500 };
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Shared pipeline steps used by both `renderToHTML` (buffered) and `renderSSR`
215
+ * (streaming). Runs loaders, builds props, head injection, resolves template,
216
+ * and creates the React element.
217
+ *
218
+ * Returns the redirect Response directly when a loader redirects, so callers
219
+ * never need try/catch for redirect handling.
220
+ */
221
+ export async function prepareRender(
222
+ route: ResolvedRoute,
223
+ ctx: Context,
224
+ root: RootLayout,
225
+ basePath: string | undefined,
226
+ throwOnFailure: boolean,
227
+ precomputedLoaderResult: LoaderResult | undefined,
228
+ searchRoutes?: SearchRouteMetadata[]
229
+ ): Promise<PreparedRender | Response> {
230
+ const loaderStart = Date.now();
231
+ const loaderResult = precomputedLoaderResult ?? (await runLoaders(route, ctx));
232
+ const loader_ms = Date.now() - loaderStart;
233
+
234
+ if (loaderResult.type === "redirect") {
235
+ return loaderResult.response;
236
+ }
237
+
238
+ // Build-time paths (SSG) opt into re-throwing so CI fails loudly instead of
239
+ // silently generating a 404/500 page for buggy loaders.
240
+ if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
241
+ throw loaderResult.error;
242
+ }
243
+
244
+ const isNotFound = loaderResult.type === "not-found";
245
+ const isError = loaderResult.type === "error";
246
+ const isFallback = isNotFound || isError;
247
+ const syncData = isFallback ? {} : loaderResult.syncData;
248
+ const deferredPromises =
249
+ !isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
250
+ assertDeferredModeAllowed(route, deferredPromises);
251
+
252
+ const headers = loaderResult.headers;
253
+ const componentProps = {
254
+ ...syncData,
255
+ ...(deferredPromises ?? {}),
256
+ params: ctx.params,
257
+ query: ctx.query,
258
+ path: ctx.path,
259
+ };
260
+
261
+ const prodTemplate = getProductionTemplate();
262
+ const template =
263
+ prodTemplate ??
264
+ (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
265
+
266
+ let element: ReactNode;
267
+ let headData = "";
268
+ let status = 200;
269
+ let errorDigest: string | undefined;
270
+ let notFoundError: { data?: unknown; message?: string } | undefined;
271
+ if (loaderResult.type === "not-found") {
272
+ element = buildNotFoundElement(route.notFound ?? root.notFound, loaderResult.error);
273
+ status = 404;
274
+ notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
275
+ } else if (loaderResult.type === "error") {
276
+ errorDigest = computeErrorDigest(loaderResult.error);
277
+ element = buildErrorElement(
278
+ route.error ?? root.error,
279
+ loaderResult.error,
280
+ errorDigest,
281
+ loaderResult.message,
282
+ loaderResult.status
283
+ );
284
+ status = loaderResult.status;
285
+ } else {
286
+ const success = buildSuccessRender(route, root, componentProps, throwOnFailure);
287
+ element = success.element;
288
+ headData = success.headData;
289
+ errorDigest = success.errorDigest;
290
+ status = success.status;
291
+ }
292
+
293
+ const ssrContext: RouterContextValue = {
294
+ basePath: basePath ?? "",
295
+ currentHref: currentHrefFromContext(ctx),
296
+ search: (ctx.query as SearchParamsInput | undefined) ?? {},
297
+ searchRoutes: searchRoutes ?? [],
298
+ navigate: (_href, _opts) => Promise.resolve(),
299
+ prefetch: (_href, _opts) => {
300
+ /* noop */
301
+ },
302
+ invalidatePrefetch: (_path, _type) => {
303
+ /* noop */
304
+ },
305
+ refresh: (_opts) => Promise.resolve(),
306
+ isNavigating: false,
307
+ defaultPreload: "intent",
308
+ defaultPreloadDelay: 50,
309
+ defaultPreloadStaleTime: 30_000,
310
+ };
311
+ element = withSSRRouterContext(element, ssrContext);
312
+
313
+ return {
314
+ componentProps,
315
+ deferredPromises,
316
+ element,
317
+ errorDigest,
318
+ headData,
319
+ headers,
320
+ loader_ms,
321
+ notFoundError,
322
+ syncData,
323
+ ssrContext,
324
+ status,
325
+ template,
326
+ };
327
+ }
328
+
329
+ // ── Helpers ──────────────────────────────────────────────────────────────────
330
+
331
+ export function renderForPath(
332
+ route: ResolvedRoute,
333
+ params: Record<string, string>,
334
+ root: RootLayout,
335
+ origin: string,
336
+ mode: "ssg" | "isr",
337
+ basePath?: string,
338
+ searchRoutes?: SearchRouteMetadata[]
339
+ ): Promise<RenderResult | Response> {
340
+ return runInSyntheticRenderScope(
341
+ async () => {
342
+ const resolvedPath = resolvePath(route.pattern, params);
343
+ const ctx: Context = {
344
+ params,
345
+ query: {},
346
+ request: new Request(`${origin}${resolvedPath}`),
347
+ headers: {},
348
+ cookie: {},
349
+ redirect: (url: string, status: number | undefined) =>
350
+ new Response(null, { status: status ?? 302, headers: { Location: url } }),
351
+ set: { headers: {} },
352
+ path: resolvedPath,
353
+ } as Context;
354
+
355
+ const prepared = await prepareRender(
356
+ route,
357
+ ctx,
358
+ root,
359
+ basePath,
360
+ true,
361
+ undefined,
362
+ searchRoutes
363
+ );
364
+ if (prepared instanceof Response) {
365
+ return prepared;
366
+ }
367
+
368
+ useLogger().set({
369
+ furin: {
370
+ render: mode,
371
+ route: route.pattern,
372
+ cache: mode === "isr" ? "revalidated" : "miss",
373
+ loader_ms: prepared.loader_ms,
374
+ ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
375
+ },
376
+ });
377
+
378
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
379
+ const stream = await renderToReadableStream(element);
380
+ await stream.allReady;
381
+ const reactHtml = await streamToString(stream);
382
+ return {
383
+ html: assembleHTML(template, headData, reactHtml, syncData),
384
+ headers,
385
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
386
+ status,
387
+ };
388
+ },
389
+ { route: route.pattern, render: mode }
390
+ );
391
+ }
392
+
393
+ /**
394
+ * Serialises a loader's `syncData` + `deferredPromises` into the same one-line
395
+ * NDJSON shape the live `/_furin/data` endpoint emits.
396
+ */
397
+ export async function serializeLoaderDataNdjson(
398
+ syncData: Record<string, unknown>,
399
+ deferredPromises: Record<string, Promise<unknown>> | undefined
400
+ ): Promise<string> {
401
+ const payload: Record<string, unknown> = {
402
+ ...syncData,
403
+ ...(deferredPromises ?? {}),
404
+ };
405
+ const serialized = await toCrossJSONAsync(payload);
406
+ return `${JSON.stringify(serialized)}\n`;
407
+ }
408
+
409
+ // ── Core pipeline ────────────────────────────────────────────────────────────
410
+
411
+ export async function renderToHTML(
412
+ route: ResolvedRoute,
413
+ ctx: Context,
414
+ root: RootLayout,
415
+ searchRoutes?: SearchRouteMetadata[]
416
+ ): Promise<RenderResult> {
417
+ const prepared = await prepareRender(route, ctx, root, undefined, false, undefined, searchRoutes);
418
+
419
+ if (prepared instanceof Response) {
420
+ throw prepared;
421
+ }
422
+
423
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
424
+
425
+ const stream = await renderToReadableStream(element);
426
+ await stream.allReady;
427
+ const reactHtml = await streamToString(stream);
428
+
429
+ return {
430
+ html: assembleHTML(template, headData, reactHtml, syncData),
431
+ headers,
432
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
433
+ status,
434
+ };
435
+ }
436
+
437
+ export async function renderToStream(
438
+ route: ResolvedRoute,
439
+ ctx: Context,
440
+ root: RootLayout
441
+ ): Promise<ReadableStream | Response> {
442
+ const response = await renderSSR(route, ctx, root, undefined);
443
+ if (!response.ok) {
444
+ return response;
445
+ }
446
+ return response.body ?? new ReadableStream();
447
+ }
448
+
449
+ export async function renderSSR(
450
+ route: ResolvedRoute,
451
+ ctx: Context,
452
+ root: RootLayout,
453
+ precomputedLoaderResult: LoaderResult | undefined,
454
+ searchRoutes?: SearchRouteMetadata[]
455
+ ): Promise<Response> {
456
+ const prepared = await prepareRender(
457
+ route,
458
+ ctx,
459
+ root,
460
+ undefined,
461
+ false,
462
+ precomputedLoaderResult,
463
+ searchRoutes
464
+ );
465
+
466
+ if (prepared instanceof Response) {
467
+ return prepared;
468
+ }
469
+
470
+ autoInvalidateRegistry.registerLoaderTags(
471
+ resolvePath(route.pattern, ctx.params ?? {}),
472
+ route.tags
473
+ );
474
+
475
+ useLogger().set({
476
+ furin: {
477
+ render: route.mode,
478
+ route: route.pattern,
479
+ loader_ms: prepared.loader_ms,
480
+ ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
481
+ },
482
+ });
483
+
484
+ const { deferredPromises, element, headData, headers, syncData, template } = prepared;
485
+
486
+ const { headPre, bodyPre, bodyPost } = splitTemplate(template);
487
+
488
+ const { stream: reactStream, shellError } = await renderElementWithShellFallback(
489
+ element,
490
+ route.error ?? root.error,
491
+ prepared.ssrContext
492
+ );
493
+ const shellErrored = shellError !== undefined;
494
+ let status = prepared.status;
495
+ let finalDigest = prepared.errorDigest;
496
+ if (shellError) {
497
+ status = 500;
498
+ finalDigest = shellError.digest;
499
+ useLogger().set({
500
+ furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" },
501
+ });
502
+ }
503
+
504
+ const dataPayload: Record<string, unknown> = shellErrored ? {} : { ...syncData };
505
+ if (finalDigest) {
506
+ dataPayload.__furinError = { digest: finalDigest, status };
507
+ }
508
+ if (status === 404 && !shellErrored) {
509
+ dataPayload.__furinStatus = 404;
510
+ if (prepared.notFoundError) {
511
+ dataPayload.__furinNotFound = prepared.notFoundError;
512
+ }
513
+ }
514
+ if (
515
+ process.env.NODE_ENV !== "production" &&
516
+ dataPayload.__furinError !== undefined &&
517
+ dataPayload.__furinNotFound !== undefined
518
+ ) {
519
+ throw new Error(
520
+ "[furin] internal invariant violated: __furinError and __furinNotFound were both set on the same SSR payload."
521
+ );
522
+ }
523
+
524
+ const hasDeferred = !shellErrored && deferredPromises !== undefined;
525
+
526
+ const deferredKeys = hasDeferred ? Object.keys(deferredPromises) : [];
527
+ const deferredSetupScript = hasDeferred ? buildDeferredScript(deferredKeys) : "";
528
+
529
+ const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(
530
+ dataPayload
531
+ )}</script>`;
532
+ const runtimeScripts = `${buildSyncRuntimeScript()}${dataScript}`;
533
+
534
+ const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
535
+ const writer = writable.getWriter();
536
+ const enc = new TextEncoder();
537
+
538
+ (async () => {
539
+ await writer.write(enc.encode(headPre + headData + deferredSetupScript + bodyPre));
540
+
541
+ const reader = reactStream.getReader();
542
+ for (;;) {
543
+ const { done, value } = await reader.read();
544
+ if (done) {
545
+ break;
546
+ }
547
+ await writer.write(value);
548
+ }
549
+
550
+ const [earlyBodyPost, finalBodyPost] = hasDeferred
551
+ ? splitBeforeBodyClose(bodyPost)
552
+ : ["", bodyPost];
553
+ await writer.write(enc.encode(runtimeScripts + earlyBodyPost));
554
+
555
+ if (hasDeferred) {
556
+ await Promise.all(
557
+ Object.entries(deferredPromises).map(async ([key, promise]) => {
558
+ try {
559
+ const resolvedValue = await promise;
560
+ const chunk = toCrossJSON(resolvedValue);
561
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "resolve")));
562
+ } catch (err) {
563
+ const normalized = await serializeDeferredRejection(err);
564
+ const chunk = toCrossJSON(normalized);
565
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "reject")));
566
+ }
567
+ })
568
+ );
569
+ }
570
+
571
+ await writer.write(enc.encode(finalBodyPost));
572
+ await writer.close();
573
+ })().catch((err) => writer.abort(err));
574
+
575
+ return new Response(readable, {
576
+ status,
577
+ headers: {
578
+ "Content-Type": "text/html; charset=utf-8",
579
+ "Cache-Control": "no-store, no-cache, must-revalidate",
580
+ ...headers,
581
+ },
582
+ });
583
+ }
584
+
585
+ export function splitBeforeBodyClose(bodyPost: string): [string, string] {
586
+ const index = bodyPost.toLowerCase().lastIndexOf("</body>");
587
+ if (index === -1) {
588
+ return [bodyPost, ""];
589
+ }
590
+ return [bodyPost.slice(0, index), bodyPost.slice(index)];
591
+ }