@teyik0/furin 0.1.0-alpha.10

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 (87) hide show
  1. package/dist/adapter/bun.d.ts +3 -0
  2. package/dist/adapter/static.d.ts +3 -0
  3. package/dist/build/client.d.ts +25 -0
  4. package/dist/build/compile-entry.d.ts +35 -0
  5. package/dist/build/entry-template.d.ts +26 -0
  6. package/dist/build/hydrate.d.ts +24 -0
  7. package/dist/build/index.d.ts +7 -0
  8. package/dist/build/index.js +4716 -0
  9. package/dist/build/route-types.d.ts +21 -0
  10. package/dist/build/scan-server.d.ts +8 -0
  11. package/dist/build/server-routes-entry.d.ts +35 -0
  12. package/dist/build/shared.d.ts +11 -0
  13. package/dist/build/types.d.ts +76 -0
  14. package/dist/cli/config.d.ts +9 -0
  15. package/dist/cli/index.d.ts +2 -0
  16. package/dist/cli/index.js +4751 -0
  17. package/dist/client.d.ts +195 -0
  18. package/dist/client.js +20 -0
  19. package/dist/config.d.ts +50 -0
  20. package/dist/config.js +28 -0
  21. package/dist/context-logger.d.ts +28 -0
  22. package/dist/dev-page-plugin.d.ts +109 -0
  23. package/dist/error.d.ts +23 -0
  24. package/dist/furin.d.ts +52 -0
  25. package/dist/furin.js +3948 -0
  26. package/dist/internal.d.ts +33 -0
  27. package/dist/link.d.ts +454 -0
  28. package/dist/link.js +1790 -0
  29. package/dist/not-found.d.ts +19 -0
  30. package/dist/plugin/index.d.ts +20 -0
  31. package/dist/plugin/index.js +1408 -0
  32. package/dist/plugin/transform-client.d.ts +9 -0
  33. package/dist/render/assemble.d.ts +15 -0
  34. package/dist/render/boundaries.d.ts +79 -0
  35. package/dist/render/cache.d.ts +96 -0
  36. package/dist/render/default-screens.d.ts +11 -0
  37. package/dist/render/digest.d.ts +16 -0
  38. package/dist/render/element.d.ts +8 -0
  39. package/dist/render/index.d.ts +53 -0
  40. package/dist/render/loaders.d.ts +21 -0
  41. package/dist/render/shell.d.ts +29 -0
  42. package/dist/render/template.d.ts +6 -0
  43. package/dist/router.d.ts +96 -0
  44. package/dist/router.js +2693 -0
  45. package/dist/runtime-env.d.ts +3 -0
  46. package/dist/utils.d.ts +6 -0
  47. package/package.json +77 -0
  48. package/src/adapter/README.md +13 -0
  49. package/src/adapter/bun.ts +239 -0
  50. package/src/adapter/static.ts +341 -0
  51. package/src/build/client.ts +153 -0
  52. package/src/build/compile-entry.ts +129 -0
  53. package/src/build/entry-template.ts +126 -0
  54. package/src/build/hydrate.ts +250 -0
  55. package/src/build/index.ts +151 -0
  56. package/src/build/route-types.ts +89 -0
  57. package/src/build/scan-server.ts +110 -0
  58. package/src/build/server-routes-entry.ts +55 -0
  59. package/src/build/shared.ts +78 -0
  60. package/src/build/types.ts +85 -0
  61. package/src/cli/config.ts +68 -0
  62. package/src/cli/index.ts +115 -0
  63. package/src/client.ts +278 -0
  64. package/src/config.ts +66 -0
  65. package/src/context-logger.ts +74 -0
  66. package/src/dev-page-plugin.ts +434 -0
  67. package/src/env.d.ts +49 -0
  68. package/src/error.ts +32 -0
  69. package/src/furin.ts +383 -0
  70. package/src/internal.ts +51 -0
  71. package/src/link.tsx +1578 -0
  72. package/src/not-found.ts +40 -0
  73. package/src/plugin/index.ts +80 -0
  74. package/src/plugin/transform-client.ts +372 -0
  75. package/src/render/assemble.ts +66 -0
  76. package/src/render/boundaries.tsx +176 -0
  77. package/src/render/cache.ts +251 -0
  78. package/src/render/default-screens.tsx +299 -0
  79. package/src/render/digest.ts +71 -0
  80. package/src/render/element.tsx +119 -0
  81. package/src/render/index.ts +867 -0
  82. package/src/render/loaders.ts +127 -0
  83. package/src/render/shell.ts +187 -0
  84. package/src/render/template.ts +55 -0
  85. package/src/router.ts +779 -0
  86. package/src/runtime-env.ts +6 -0
  87. package/src/utils.ts +68 -0
@@ -0,0 +1,867 @@
1
+ import { createElement, type ReactNode } from "react";
2
+ import { renderToReadableStream } from "react-dom/server";
3
+ import { RouterContext, type RouterContextValue } from "../link.tsx";
4
+ import { FurinNotFoundError } from "../not-found.ts";
5
+ import type { RootLayout } from "../router.ts";
6
+ import { assembleHTML, resolvePath, splitTemplate, streamToString } from "./assemble.ts";
7
+ import {
8
+ getISRCache,
9
+ getSSGCache,
10
+ type ISRCacheEntry,
11
+ type SsgCacheEntry,
12
+ setISRCache,
13
+ setSSGCache,
14
+ } from "./cache.ts";
15
+ import { computeErrorDigest } from "./digest.ts";
16
+ import { buildElement, buildErrorElement, buildNotFoundElement } from "./element.tsx";
17
+ import { runLoaders } from "./loaders.ts";
18
+ import { buildHeadInjection, safeJson } from "./shell.ts";
19
+ import { getDevTemplate, getProductionTemplate } from "./template.ts";
20
+
21
+ // ── Re-exports (public API) ──────────────────────────────────────────────────
22
+ // biome-ignore lint/performance/noBarrelFile: acnowledged
23
+ export { type LoaderContext, streamToString } from "./assemble.ts";
24
+ export { buildElement } from "./element.tsx";
25
+ export { type LoaderResult, runLoaders } from "./loaders.ts";
26
+
27
+ // ── Types ────────────────────────────────────────────────────────────────────
28
+
29
+ import type { Context } from "elysia";
30
+ import { createLogger, runInSyntheticRenderScope, useLogger } from "../context-logger.ts";
31
+ import type { ResolvedRoute } from "../router.ts";
32
+ import { IS_DEV } from "../runtime-env.ts";
33
+ import type { LoaderContext } from "./assemble.ts";
34
+ import { generateIndexHtml } from "./shell.ts";
35
+
36
+ interface RenderResult {
37
+ headers: Record<string, string>;
38
+ html: string;
39
+ status: number;
40
+ }
41
+
42
+ // ── Shared render preparation ────────────────────────────────────────────────
43
+
44
+ interface PreparedRender {
45
+ componentProps: Record<string, unknown>;
46
+ element: ReactNode;
47
+ /** Set when the prepared element is an error UI. Surfaced to the client via
48
+ * `__FURIN_DATA__.__furinError.digest` and logged server-side. */
49
+ errorDigest?: string;
50
+ headData: string;
51
+ headers: Record<string, string>;
52
+ loader_ms: number;
53
+ /**
54
+ * Slice 8 — populated only when the loader threw `notFound()`. Mirrored into
55
+ * `__FURIN_DATA__.__furinNotFound` so the client-side `classifySpaResponse`
56
+ * can render the not-found UI inline on SPA navigation instead of falling
57
+ * back to a full-page reload.
58
+ */
59
+ notFoundError?: { data?: unknown; message?: string };
60
+ ssrContext: RouterContextValue;
61
+ status: number;
62
+ template: string;
63
+ }
64
+
65
+ function withSSRRouterContext(element: ReactNode, contextValue: RouterContextValue): ReactNode {
66
+ return createElement(RouterContext.Provider, { value: contextValue }, element);
67
+ }
68
+
69
+ /**
70
+ * Shared pipeline steps used by both `renderToHTML` (buffered) and `renderSSR`
71
+ * (streaming). Runs loaders, builds props, head injection, resolves template,
72
+ * and creates the React element.
73
+ *
74
+ * Returns the redirect Response directly when a loader redirects, so callers
75
+ * never need try/catch for redirect handling.
76
+ */
77
+ async function prepareRender(
78
+ route: ResolvedRoute,
79
+ ctx: Context,
80
+ root: RootLayout,
81
+ basePath: string | undefined,
82
+ throwOnFailure: boolean
83
+ ): Promise<PreparedRender | Response> {
84
+ const loaderStart = Date.now();
85
+ const loaderResult = await runLoaders(route, ctx, root.route);
86
+ const loader_ms = Date.now() - loaderStart;
87
+
88
+ if (loaderResult.type === "redirect") {
89
+ return loaderResult.response;
90
+ }
91
+
92
+ // Build-time paths (SSG) opt into re-throwing so CI fails loudly instead of
93
+ // silently generating a 404/500 page for buggy loaders.
94
+ if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
95
+ throw loaderResult.error;
96
+ }
97
+
98
+ const isNotFound = loaderResult.type === "not-found";
99
+ const isError = loaderResult.type === "error";
100
+ const isFallback = isNotFound || isError;
101
+ const data = isFallback ? {} : loaderResult.data;
102
+ const headers = loaderResult.headers;
103
+ const componentProps = {
104
+ ...data,
105
+ params: ctx.params,
106
+ query: ctx.query,
107
+ path: ctx.path,
108
+ };
109
+
110
+ const headData = isFallback ? "" : buildHeadInjection(route.page?.head?.(componentProps));
111
+
112
+ // An explicitly-set production template (static pre-render, compiled Bun server)
113
+ // always wins over the IS_DEV flag. This decouples template resolution from the
114
+ // IS_DEV singleton so callers never need to flip IS_DEV just to get the right shell.
115
+ const prodTemplate = getProductionTemplate();
116
+ const template =
117
+ prodTemplate ??
118
+ (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
119
+
120
+ let element: ReactNode;
121
+ let status = 200;
122
+ let errorDigest: string | undefined;
123
+ let notFoundError: { data?: unknown; message?: string } | undefined;
124
+ if (loaderResult.type === "not-found") {
125
+ element = buildNotFoundElement(route.notFound ?? root.notFound, loaderResult.error);
126
+ status = 404;
127
+ notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
128
+ } else if (loaderResult.type === "error") {
129
+ errorDigest = computeErrorDigest(loaderResult.error);
130
+ element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
131
+ status = 500;
132
+ } else {
133
+ element = buildElement(route, componentProps, root.route);
134
+ }
135
+
136
+ // Inject RouterContext so Link components have the correct currentHref for
137
+ // active-state detection and basePath-aware href generation. Previously this
138
+ // was only done for SSG (basePath !== undefined), which caused hydration
139
+ // mismatches in SSR/ISR because SSR_FALLBACK_ROUTER hardcodes currentHref "/"
140
+ // while the client hydrates with the real pathname.
141
+ const ssrContext: RouterContextValue = {
142
+ basePath: basePath ?? "",
143
+ currentHref: ctx.path,
144
+ navigate: () => Promise.resolve(),
145
+ prefetch: () => {
146
+ /* noop */
147
+ },
148
+ invalidatePrefetch: () => {
149
+ /* noop */
150
+ },
151
+ refresh: () => Promise.resolve(),
152
+ isNavigating: false,
153
+ defaultPreload: "intent",
154
+ defaultPreloadDelay: 50,
155
+ defaultPreloadStaleTime: 30_000,
156
+ };
157
+ element = withSSRRouterContext(element, ssrContext);
158
+
159
+ return {
160
+ componentProps,
161
+ element,
162
+ errorDigest,
163
+ headData,
164
+ headers,
165
+ loader_ms,
166
+ notFoundError,
167
+ ssrContext,
168
+ status,
169
+ template,
170
+ };
171
+ }
172
+
173
+ // ── Helpers ──────────────────────────────────────────────────────────────────
174
+
175
+ function renderForPath(
176
+ route: ResolvedRoute,
177
+ params: Record<string, string>,
178
+ root: RootLayout,
179
+ origin: string,
180
+ mode: "ssg" | "isr",
181
+ basePath: string | undefined
182
+ ): Promise<RenderResult | Response> {
183
+ return runInSyntheticRenderScope(
184
+ async () => {
185
+ const resolvedPath = resolvePath(route.pattern, params);
186
+ const ctx: Context = {
187
+ params,
188
+ query: {},
189
+ request: new Request(`${origin}${resolvedPath}`),
190
+ headers: {},
191
+ cookie: {},
192
+ redirect: (url: string, status: number | undefined) =>
193
+ new Response(null, { status: status ?? 302, headers: { Location: url } }),
194
+ set: { headers: {} },
195
+ path: resolvedPath,
196
+ } as Context;
197
+
198
+ const prepared = await prepareRender(route, ctx, root, basePath, true);
199
+ if (prepared instanceof Response) {
200
+ return prepared;
201
+ }
202
+
203
+ useLogger().set({
204
+ furin: {
205
+ render: mode,
206
+ route: route.pattern,
207
+ cache: mode === "isr" ? "revalidated" : "miss",
208
+ loader_ms: prepared.loader_ms,
209
+ ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
210
+ },
211
+ });
212
+
213
+ const { componentProps, element, headData, headers, status, template } = prepared;
214
+ const stream = await renderToReadableStream(element);
215
+ await stream.allReady;
216
+ const reactHtml = await streamToString(stream);
217
+ return {
218
+ html: assembleHTML(template, headData, reactHtml, componentProps),
219
+ headers,
220
+ status,
221
+ };
222
+ },
223
+ { route: route.pattern, render: mode }
224
+ );
225
+ }
226
+
227
+ // ── Core pipeline ────────────────────────────────────────────────────────────
228
+
229
+ export async function renderToHTML(
230
+ route: ResolvedRoute,
231
+ ctx: Context,
232
+ root: RootLayout
233
+ ): Promise<RenderResult> {
234
+ const prepared = await prepareRender(route, ctx, root, undefined, false);
235
+
236
+ // Redirect — re-throw so callers like prerenderSSG / handleISR can catch it
237
+ if (prepared instanceof Response) {
238
+ throw prepared;
239
+ }
240
+
241
+ const { componentProps, element, headData, headers, status, template } = prepared;
242
+
243
+ const stream = await renderToReadableStream(element);
244
+ await stream.allReady;
245
+ const reactHtml = await streamToString(stream);
246
+
247
+ return {
248
+ html: assembleHTML(template, headData, reactHtml, componentProps),
249
+ headers,
250
+ status,
251
+ };
252
+ }
253
+
254
+ // ── Public render functions ──────────────────────────────────────────────────
255
+
256
+ export async function renderToStream(
257
+ route: ResolvedRoute,
258
+ ctx: Context,
259
+ root: RootLayout
260
+ ): Promise<ReadableStream | Response> {
261
+ const response = await renderSSR(route, ctx, root);
262
+ if (!response.ok) {
263
+ return response;
264
+ }
265
+ return response.body ?? new ReadableStream();
266
+ }
267
+
268
+ export async function prerenderSSG(
269
+ route: ResolvedRoute,
270
+ params: Record<string, string>,
271
+ root: RootLayout,
272
+ origin: string,
273
+ basePath: string | undefined
274
+ ): Promise<SsgCacheEntry | Response> {
275
+ const resolvedPath = resolvePath(route.pattern, params);
276
+
277
+ const cached = getSSGCache(resolvedPath);
278
+ if (cached && !IS_DEV) {
279
+ return cached;
280
+ }
281
+
282
+ const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath);
283
+ if (renderResult instanceof Response) {
284
+ return renderResult;
285
+ }
286
+ const result = renderResult;
287
+
288
+ const entry: SsgCacheEntry = { html: result.html, cachedAt: Date.now(), status: result.status };
289
+
290
+ if (!IS_DEV) {
291
+ setSSGCache(resolvedPath, entry);
292
+ }
293
+
294
+ return entry;
295
+ }
296
+
297
+ export async function renderSSR(
298
+ route: ResolvedRoute,
299
+ ctx: Context,
300
+ root: RootLayout
301
+ ): Promise<Response> {
302
+ const prepared = await prepareRender(route, ctx, root, undefined, false);
303
+
304
+ // Redirect — return directly as a Response
305
+ if (prepared instanceof Response) {
306
+ return prepared;
307
+ }
308
+
309
+ useLogger().set({
310
+ furin: {
311
+ render: route.mode,
312
+ route: route.pattern,
313
+ loader_ms: prepared.loader_ms,
314
+ ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
315
+ },
316
+ });
317
+
318
+ const { componentProps, element, headData, headers, template } = prepared;
319
+
320
+ // Split template around placeholders
321
+ const { headPre, bodyPre, bodyPost } = splitTemplate(template);
322
+
323
+ // Shell-render gate: if the React shell (pre-Suspense render) throws, recover
324
+ // by rendering the nearest error.tsx. If THAT also throws, fall back to the
325
+ // built-in DefaultErrorComponent to break recursion.
326
+ let reactStream: ReadableStream<Uint8Array>;
327
+ let status = prepared.status;
328
+ let shellErrored = false;
329
+ let finalDigest = prepared.errorDigest;
330
+ try {
331
+ reactStream = await renderToReadableStream(element);
332
+ } catch (shellError) {
333
+ shellErrored = true;
334
+ status = 500;
335
+ finalDigest = computeErrorDigest(shellError);
336
+ // Log the shell-render error — prepared.errorDigest (if any) was for the
337
+ // loader-level error that never made it to the stream; this is a new one.
338
+ useLogger().set({
339
+ furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" },
340
+ });
341
+ try {
342
+ reactStream = await renderToReadableStream(
343
+ withSSRRouterContext(
344
+ buildErrorElement(route.error ?? root.error, shellError, finalDigest),
345
+ prepared.ssrContext
346
+ )
347
+ );
348
+ } catch {
349
+ // User's error.tsx also threw — render the built-in default which is
350
+ // pure markup and cannot crash.
351
+ reactStream = await renderToReadableStream(
352
+ withSSRRouterContext(
353
+ buildErrorElement(undefined, shellError, finalDigest),
354
+ prepared.ssrContext
355
+ )
356
+ );
357
+ }
358
+ }
359
+
360
+ // In error-recovery mode, don't inject loader data (it may contain the
361
+ // failing state that caused the crash). Use an empty payload so rehydration
362
+ // is a no-op rather than repeating the error. When we DO have a digest
363
+ // (either from loader error or shell recovery), expose it under __furinError
364
+ // so the client-side ErrorBoundary can surface the same id on rehydrate.
365
+ const dataPayload: Record<string, unknown> = shellErrored ? {} : { ...componentProps };
366
+ if (finalDigest) {
367
+ dataPayload.__furinError = { digest: finalDigest };
368
+ }
369
+ // Slice 8 — SPA 404 signal. When the loader threw `notFound()`, the response
370
+ // status is 404 and the body contains the rendered not-found UI. We ALSO
371
+ // embed a machine-readable signal in __FURIN_DATA__ so that a mid-SPA-nav
372
+ // client can detect the case without guessing from the HTML, and render the
373
+ // not-found component inline instead of performing a jarring full-page
374
+ // reload. Mirrors the existing `__furinError.digest` channel for 500s.
375
+ if (status === 404 && !shellErrored) {
376
+ dataPayload.__furinStatus = 404;
377
+ if (prepared.notFoundError) {
378
+ dataPayload.__furinNotFound = prepared.notFoundError;
379
+ }
380
+ }
381
+ const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(
382
+ dataPayload
383
+ )}</script>`;
384
+
385
+ // Pipe head + React stream + tail into a single ReadableStream
386
+ const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
387
+ const writer = writable.getWriter();
388
+ const enc = new TextEncoder();
389
+
390
+ (async () => {
391
+ await writer.write(enc.encode(headPre + headData + bodyPre));
392
+ const reader = reactStream.getReader();
393
+ for (;;) {
394
+ const { done, value } = await reader.read();
395
+ if (done) {
396
+ break;
397
+ }
398
+ await writer.write(value);
399
+ }
400
+ await writer.write(enc.encode(dataScript + bodyPost));
401
+ await writer.close();
402
+ })().catch((err) => writer.abort(err));
403
+
404
+ return new Response(readable, {
405
+ status,
406
+ headers: {
407
+ "Content-Type": "text/html; charset=utf-8",
408
+ "Cache-Control": "no-store, no-cache, must-revalidate",
409
+ ...headers,
410
+ },
411
+ });
412
+ }
413
+
414
+ // ── Catch-all 404 ────────────────────────────────────────────────────────────
415
+
416
+ /**
417
+ * Renders the root-level not-found component into a complete 404 HTML Response.
418
+ * Used by the Elysia `.onError` catch-all when no route matches the request URL.
419
+ *
420
+ * Template resolution mirrors the main render path:
421
+ * prod template (if pre-rendered / compiled server)
422
+ * → dev template from Bun's HTML bundler (in dev, for the rewritten script tag)
423
+ * → static `generateIndexHtml()` (last-resort fallback; test harness, SSR with no request).
424
+ *
425
+ * The dev-template branch is critical: Bun's HTML bundler rewrites
426
+ * `./_hydrate.tsx` to the hashed client chunk URL (e.g. `/_bun/client/index-*.js`).
427
+ * If we served the raw `generateIndexHtml()` output, the browser would try to
428
+ * load `./_hydrate.tsx` relative to the current URL (e.g. `/foo/_hydrate.tsx`),
429
+ * 404, and the page would be left static — so clicking any in-page link would
430
+ * trigger a full document load instead of SPA navigation.
431
+ *
432
+ * If the user's not-found.tsx itself throws, falls back to the built-in
433
+ * DefaultNotFoundComponent to break recursion.
434
+ *
435
+ * @param root - Resolved root layout (carries the user's `not-found.tsx` ref).
436
+ * @param request - The incoming request. Required in dev to resolve the HMR
437
+ * entry origin. Pass `undefined` in contexts where no request is available
438
+ * (tests, SSG warmup) — the function will fall through to the static shell.
439
+ */
440
+ export async function renderRootNotFound(
441
+ root: RootLayout,
442
+ request: Request | undefined
443
+ ): Promise<Response> {
444
+ const prodTemplate = getProductionTemplate();
445
+ let template: string;
446
+ if (prodTemplate !== null) {
447
+ template = prodTemplate;
448
+ } else if (IS_DEV && request !== undefined) {
449
+ try {
450
+ template = await getDevTemplate(new URL(request.url).origin);
451
+ } catch (devTemplateErr) {
452
+ // Loopback failed (server not listening yet, URL unreachable, etc.) —
453
+ // still return SOMETHING so the user doesn't see a raw error. The
454
+ // generated HTML will be non-interactive (see JSDoc), but that's
455
+ // strictly better than a 500.
456
+ useLogger().set({
457
+ furin: {
458
+ render: "not-found",
459
+ action: "dev_template_fallback",
460
+ error: devTemplateErr instanceof Error ? devTemplateErr.message : String(devTemplateErr),
461
+ },
462
+ });
463
+ template = generateIndexHtml();
464
+ }
465
+ } else {
466
+ template = generateIndexHtml();
467
+ }
468
+ const notFoundError = new FurinNotFoundError(undefined);
469
+
470
+ const notFoundContext: RouterContextValue = {
471
+ basePath: "",
472
+ currentHref: request ? new URL(request.url).pathname : "/",
473
+ navigate: () => Promise.resolve(),
474
+ prefetch: () => {
475
+ /* noop */
476
+ },
477
+ invalidatePrefetch: () => {
478
+ /* noop */
479
+ },
480
+ refresh: () => Promise.resolve(),
481
+ isNavigating: false,
482
+ defaultPreload: "intent",
483
+ defaultPreloadDelay: 50,
484
+ defaultPreloadStaleTime: 30_000,
485
+ };
486
+
487
+ useLogger().set({
488
+ furin: {
489
+ render: "not-found",
490
+ action: "catch_all",
491
+ path: request ? new URL(request.url).pathname : "/",
492
+ },
493
+ });
494
+
495
+ let reactStream: Awaited<ReturnType<typeof renderToReadableStream>>;
496
+ try {
497
+ reactStream = await renderToReadableStream(
498
+ withSSRRouterContext(buildNotFoundElement(root.notFound, notFoundError), notFoundContext)
499
+ );
500
+ } catch {
501
+ // User's not-found.tsx crashed — fall back to the built-in default.
502
+ reactStream = await renderToReadableStream(
503
+ withSSRRouterContext(buildNotFoundElement(undefined, notFoundError), notFoundContext)
504
+ );
505
+ }
506
+ await reactStream.allReady;
507
+ const reactHtml = await streamToString(reactStream);
508
+ // Embed the SPA 404 signal so client-side `fetchPageState` can detect the
509
+ // catch-all 404 via `classifySpaResponse` and render inline instead of doing
510
+ // a jarring full-page reload when navigating to an unmatched URL.
511
+ const html = assembleHTML(template, "", reactHtml, { __furinStatus: 404 });
512
+
513
+ return new Response(html, {
514
+ status: 404,
515
+ headers: { "Content-Type": "text/html; charset=utf-8" },
516
+ });
517
+ }
518
+
519
+ // ── ISR helpers ──────────────────────────────────────────────────────────────
520
+
521
+ /**
522
+ * Builds the Cache-Control header value for an ISR response.
523
+ * Browser: max-age=0 + must-revalidate forces a conditional request every time.
524
+ * CDN: s-maxage=N + stale-while-revalidate=N allow CDN-level serving + BG refresh.
525
+ */
526
+ function isrCacheControl(isFresh: boolean, revalidate: number): string {
527
+ const sMaxAge = isFresh ? revalidate : 0;
528
+ return `public, max-age=0, must-revalidate, s-maxage=${sMaxAge}, stale-while-revalidate=${revalidate}`;
529
+ }
530
+
531
+ /**
532
+ * Serves a response from an existing ISR cache entry.
533
+ * Handles stale-while-revalidate background refresh and ETag conditional requests.
534
+ * Returns `undefined` when a 304 Not Modified is sent (no body needed).
535
+ */
536
+ function serveISRCacheHit(
537
+ cached: ISRCacheEntry,
538
+ ctx: Context,
539
+ route: ResolvedRoute,
540
+ params: Record<string, string>,
541
+ cacheKey: string,
542
+ revalidate: number,
543
+ root: RootLayout,
544
+ buildId: string
545
+ ): string | undefined {
546
+ const isFresh = Date.now() - cached.generatedAt < revalidate * 1000;
547
+
548
+ // Kick off background refresh for stale entries *before* the ETag check
549
+ // so conditional requests (304) do not permanently suppress cache refreshes.
550
+ if (!isFresh) {
551
+ revalidateInBackground(route, params, cacheKey, revalidate, root, ctx);
552
+ }
553
+
554
+ // ETag = "buildId:generatedAt" — encodes both the deploy version and freshness.
555
+ // Only emit when buildId is non-empty (dev has no buildId).
556
+ const etag = buildId ? `"${buildId}:${cached.generatedAt}"` : null;
557
+ if (etag && ctx.request.headers.get("if-none-match") === etag) {
558
+ // RFC 7232 §4.1: a 304 MUST echo the ETag and SHOULD include Cache-Control
559
+ // so the browser continues sending If-None-Match on future requests.
560
+ ctx.set.status = 304;
561
+ ctx.set.headers.etag = etag;
562
+ ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
563
+ return;
564
+ }
565
+
566
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
567
+ ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
568
+ if (etag) {
569
+ ctx.set.headers.etag = etag;
570
+ }
571
+
572
+ useLogger().set({
573
+ furin: { render: "isr", route: route.pattern, cache: isFresh ? "hit" : "stale" },
574
+ });
575
+ return cached.html;
576
+ }
577
+
578
+ /**
579
+ * Handles the ISR non-200 render path: shell-recovery with fallback error
580
+ * component, structured logging, and cache-control headers. Extracted from
581
+ * handleISR to keep cyclomatic complexity under the lint threshold.
582
+ */
583
+ async function renderISRNon200(
584
+ prepared: PreparedRender,
585
+ route: ResolvedRoute,
586
+ ctx: Context,
587
+ root: RootLayout,
588
+ errorDigest: string | undefined,
589
+ renderStart: number,
590
+ buildId: string
591
+ ): Promise<string> {
592
+ const { componentProps, element, headData, template, status, notFoundError } = prepared;
593
+ const fallbackProps: Record<string, unknown> = { ...componentProps };
594
+ if (status === 404) {
595
+ fallbackProps.__furinStatus = 404;
596
+ if (notFoundError) {
597
+ fallbackProps.__furinNotFound = notFoundError;
598
+ }
599
+ }
600
+
601
+ // Shell-render gate: if the React render throws for the non-200 ISR branch,
602
+ // recover by rendering the fallback error component so that a broken
603
+ // user error/not-found UI cannot crash the ISR path entirely.
604
+ let reactStream: Awaited<ReturnType<typeof renderToReadableStream>>;
605
+ let finalStatus = status;
606
+ let finalDigest = errorDigest;
607
+ try {
608
+ reactStream = await renderToReadableStream(element);
609
+ } catch (shellError) {
610
+ finalStatus = 500;
611
+ finalDigest = computeErrorDigest(shellError);
612
+ useLogger().set({
613
+ furin: {
614
+ render: "isr",
615
+ route: route.pattern,
616
+ cache: "miss",
617
+ digest: finalDigest,
618
+ phase: "shell",
619
+ },
620
+ });
621
+ fallbackProps.__furinError = { digest: finalDigest };
622
+ fallbackProps.__furinStatus = 500;
623
+ try {
624
+ reactStream = await renderToReadableStream(
625
+ withSSRRouterContext(
626
+ buildErrorElement(route.error ?? root.error, shellError, finalDigest),
627
+ prepared.ssrContext
628
+ )
629
+ );
630
+ } catch {
631
+ // User's error.tsx also threw — render the built-in default (pure markup,
632
+ // cannot crash).
633
+ reactStream = await renderToReadableStream(
634
+ withSSRRouterContext(
635
+ buildErrorElement(undefined, shellError, finalDigest),
636
+ prepared.ssrContext
637
+ )
638
+ );
639
+ }
640
+ }
641
+ if (!fallbackProps.__furinError && errorDigest) {
642
+ fallbackProps.__furinError = { digest: errorDigest };
643
+ }
644
+
645
+ await reactStream.allReady;
646
+ const reactHtml = await streamToString(reactStream);
647
+ const html = assembleHTML(template, headData, reactHtml, fallbackProps);
648
+ const generatedAt = Date.now();
649
+
650
+ const renderMs = generatedAt - renderStart;
651
+ useLogger().set({
652
+ furin: {
653
+ render: "isr",
654
+ route: route.pattern,
655
+ cache: "miss",
656
+ render_ms: renderMs,
657
+ ...(finalDigest ? { digest: finalDigest } : {}),
658
+ status: finalStatus,
659
+ },
660
+ });
661
+
662
+ const etag = buildId ? `"${buildId}:${generatedAt}"` : null;
663
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
664
+ ctx.set.headers["cache-control"] = "no-store";
665
+ if (etag) {
666
+ ctx.set.headers.etag = etag;
667
+ }
668
+ ctx.set.status = finalStatus;
669
+ return html;
670
+ }
671
+
672
+ export async function handleISR(
673
+ route: ResolvedRoute,
674
+ ctx: Context,
675
+ root: RootLayout,
676
+ buildId = ""
677
+ ) {
678
+ const revalidate = route.page._route.revalidate ?? 60;
679
+ const params = ctx.params ?? {};
680
+ const cacheKey = resolvePath(route.pattern, params);
681
+
682
+ const cached = getISRCache(cacheKey);
683
+ if (cached && !IS_DEV) {
684
+ return serveISRCacheHit(cached, ctx, route, params, cacheKey, revalidate, root, buildId);
685
+ }
686
+
687
+ const renderStart = Date.now();
688
+ const prepared = await prepareRender(route, ctx, root, undefined, false);
689
+
690
+ // Redirect — return directly
691
+ if (prepared instanceof Response) {
692
+ return prepared;
693
+ }
694
+
695
+ const { componentProps, element, headData, template, status, errorDigest } = prepared;
696
+
697
+ if (status !== 200) {
698
+ return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
699
+ }
700
+
701
+ const stream = await renderToReadableStream(element);
702
+ await stream.allReady;
703
+ const reactHtml = await streamToString(stream);
704
+ const html = assembleHTML(template, headData, reactHtml, componentProps);
705
+ const generatedAt = Date.now();
706
+
707
+ useLogger().set({
708
+ furin: {
709
+ render: "isr",
710
+ route: route.pattern,
711
+ cache: "miss",
712
+ render_ms: generatedAt - renderStart,
713
+ },
714
+ });
715
+
716
+ if (!IS_DEV) {
717
+ setISRCache(cacheKey, { html, generatedAt, revalidate });
718
+ }
719
+
720
+ const etag = buildId ? `"${buildId}:${generatedAt}"` : null;
721
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
722
+ ctx.set.headers["cache-control"] = isrCacheControl(true, revalidate);
723
+ if (etag) {
724
+ ctx.set.headers.etag = etag;
725
+ }
726
+ return html;
727
+ }
728
+
729
+ // ── SSG warm-up ──────────────────────────────────────────────────────────────
730
+
731
+ /** Maximum number of concurrent `prerenderSSG` calls during SSG warm-up. */
732
+ const SSG_WARM_CONCURRENCY = 4;
733
+
734
+ /**
735
+ * Pre-renders all SSG routes that declare `staticParams` and populates the
736
+ * in-memory cache before the first real request arrives.
737
+ * Should be called from the Elysia `onStart` hook (production only).
738
+ *
739
+ * Uses a bounded worker pool (SSG_WARM_CONCURRENCY slots) so large sites
740
+ * with many routes × param sets cannot exhaust memory or CPU during startup.
741
+ * Failures are isolated per (route, params) pair and logged without aborting
742
+ * the rest of the warm-up.
743
+ */
744
+ export async function warmSSGCache(
745
+ routes: ResolvedRoute[],
746
+ root: RootLayout,
747
+ origin: string
748
+ ): Promise<void> {
749
+ const targets = routes.filter((r) => r.mode === "ssg" && r.page.staticParams);
750
+ const warmupLogger = createLogger({});
751
+ warmupLogger.set({
752
+ furin: {
753
+ render: "ssg",
754
+ action: "warmup",
755
+ routes: targets.length,
756
+ },
757
+ });
758
+ warmupLogger.emit();
759
+
760
+ // Collect all (route, params) render tasks, handling per-route errors early.
761
+ const tasks: Array<() => Promise<void>> = [];
762
+ for (const route of targets) {
763
+ let paramSets: Record<string, string>[];
764
+ try {
765
+ paramSets = (await route.page.staticParams?.()) ?? [];
766
+ } catch (err) {
767
+ const errorLogger = createLogger({});
768
+ errorLogger.set({
769
+ furin: {
770
+ render: "ssg",
771
+ action: "warmup_failed",
772
+ route: route.pattern,
773
+ },
774
+ });
775
+ errorLogger.error(err instanceof Error ? err : new Error(String(err)));
776
+ errorLogger.emit();
777
+ continue;
778
+ }
779
+ for (const params of paramSets) {
780
+ tasks.push(async () => {
781
+ try {
782
+ await prerenderSSG(route, params, root, origin, undefined);
783
+ } catch (err) {
784
+ const errorLogger = createLogger({});
785
+ errorLogger.set({
786
+ furin: {
787
+ render: "ssg",
788
+ action: "prerender_failed",
789
+ route: route.pattern,
790
+ },
791
+ });
792
+ errorLogger.error(err instanceof Error ? err : new Error(String(err)));
793
+ errorLogger.emit();
794
+ }
795
+ });
796
+ }
797
+ }
798
+
799
+ if (tasks.length === 0) {
800
+ return;
801
+ }
802
+
803
+ // Drain the task queue with a fixed-size worker pool.
804
+ const queue = [...tasks];
805
+ const workers = Array.from({ length: Math.min(SSG_WARM_CONCURRENCY, tasks.length) }, async () => {
806
+ while (queue.length > 0) {
807
+ await queue.shift()?.();
808
+ }
809
+ });
810
+ await Promise.all(workers);
811
+ }
812
+
813
+ /** Tracks in-flight ISR revalidations to prevent thundering herd. */
814
+ const pendingRevalidations = new Set<string>();
815
+
816
+ function revalidateInBackground(
817
+ route: ResolvedRoute,
818
+ params: Record<string, string>,
819
+ cacheKey: string,
820
+ revalidate: number,
821
+ root: RootLayout,
822
+ originalCtx: LoaderContext
823
+ ) {
824
+ if (pendingRevalidations.has(cacheKey)) {
825
+ const logger = createLogger({});
826
+ logger.set({
827
+ furin: {
828
+ render: "isr",
829
+ route: route.pattern,
830
+ cache: "revalidation_skipped",
831
+ reason: "already_in_flight",
832
+ },
833
+ });
834
+ logger.emit();
835
+ return;
836
+ }
837
+ pendingRevalidations.add(cacheKey);
838
+
839
+ renderForPath(route, params, root, new URL(originalCtx.request.url).origin, "isr", undefined)
840
+ .then((result) => {
841
+ if (result instanceof Response) {
842
+ // A loader called ctx.redirect() during ISR revalidation.
843
+ // Silently drop it — the next real request will hit the loader again.
844
+ return;
845
+ }
846
+ setISRCache(cacheKey, {
847
+ html: result.html,
848
+ generatedAt: Date.now(),
849
+ revalidate,
850
+ });
851
+ })
852
+ .catch((err: unknown) => {
853
+ const logger = createLogger({});
854
+ logger.set({
855
+ furin: {
856
+ render: "isr",
857
+ route: route.pattern,
858
+ cache: "revalidation_failed",
859
+ },
860
+ });
861
+ logger.error(err instanceof Error ? err : new Error(String(err)));
862
+ logger.emit();
863
+ })
864
+ .finally(() => {
865
+ pendingRevalidations.delete(cacheKey);
866
+ });
867
+ }