@sigil-dev/grimoire 0.9.20 → 0.9.22

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +16 -5
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +870 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -114
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -745
  28. package/src/rendering/preload.ts +101 -95
  29. package/src/rendering/ssrPlugin.ts +108 -108
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -194
  35. package/src/server/asset-cache.ts +57 -55
  36. package/src/server/build.ts +262 -249
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -0
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +1138 -1022
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -0
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -113
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -69
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +92 -92
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +798 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +378 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +805 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +131 -131
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -1,745 +1,755 @@
1
- import { randomBytes } from "node:crypto";
2
- import { preloadLinks } from "./preload.ts";
3
- import { createTimer } from "./timing.ts";
4
- import { optimizeImages } from "./images.ts";
5
- import { SafeHtml } from "@sigil-dev/runtime";
6
- import { startCollecting, stopCollecting } from "../client/deps";
7
- import { filterPublic } from "../env/index";
8
- import { findClosestError, type MatchedRoute } from "../routing/router";
9
- import type { RouteFile } from "../routing/scanner";
10
- import { isErrorResult } from "../sentinels/error.ts";
11
- import { isRedirectResult } from "../sentinels/redirect.ts";
12
- import { runWithContext } from "../server/context";
13
- import { clientAddressOf } from "../server/client-address";
14
- import { runHook } from "../server/plugins";
15
- import type { GrimoirePlugin, LoadContext, Route } from "../types";
16
- import { collectHead, initHead } from "./head";
17
-
18
- export type ModuleLoader = (path: string) => Promise<any>;
19
-
20
- type LayoutPair = { layout: RouteFile; mod: any; data: unknown };
21
-
22
- /** Placeholder for a top-level server-load promise still in flight. SSR text
23
- * interpolation renders it as an empty string via the normal String(v) path. */
24
- class DeferredMarker {
25
- constructor(
26
- public uid: string,
27
- public key: string,
28
- ) {}
29
- toString() {
30
- return "";
31
- }
32
- }
33
-
34
- type DeferredEntry = { promise: Promise<unknown>; key: string; uid: string };
35
-
36
- /**
37
- * Request header the client router sets to ask for the JSON navigate payload
38
- * instead of an HTML document. Both representations live at the same URL, so
39
- * every response that depends on it MUST also send it in `Vary`.
40
- */
41
- export const NAVIGATE_HEADER = "x-grimoire-navigate";
42
-
43
- /**
44
- * Serialize the hydration state payload for embedding inside a
45
- * `<script type="application/json">` tag. Escapes every `<` so a data value
46
- * like `"</script><script>alert(1)</script>"` cannot close the state script
47
- * early and inject markup. JSON.parse reads `\u003c` back as `<`.
48
- * DeferredMarkers serialize to `{ __deferred: uid }`.
49
- */
50
- const safeStateJson = (value: unknown): string =>
51
- JSON.stringify(value, (_k, v) =>
52
- v instanceof DeferredMarker ? { __deferred: v.uid } : v,
53
- ).replace(/</g, "\\u003c");
54
-
55
- /** Replace every own top-level promise property with a marker and record the
56
- * promise for late flush. Nested promises are awaited by the load itself. */
57
- function extractDeferred(
58
- data: unknown,
59
- deferred: DeferredEntry[],
60
- counter: { n: number },
61
- ): void {
62
- if (!data || typeof data !== "object" || Array.isArray(data)) return;
63
- const record = data as Record<string, unknown>;
64
- for (const key of Object.keys(record)) {
65
- const value = record[key];
66
- if (value instanceof Promise) {
67
- const uid = `gd-${counter.n++}`;
68
- record[key] = new DeferredMarker(uid, key);
69
- deferred.push({ promise: value, key, uid });
70
- }
71
- }
72
- }
73
-
74
- /**
75
- * The data a component renders with on the server: a value still in flight
76
- * reads as `undefined`, so `{data.reviews ?? "Loading…"}` shows its
77
- * fallback. The state script keeps the markers, and the settled values
78
- * reach the browser before it hydrates.
79
- */
80
- function renderable(data: unknown): unknown {
81
- if (!data || typeof data !== "object" || Array.isArray(data)) return data;
82
- const values = Object.values(data as Record<string, unknown>);
83
- if (!values.some((v) => v instanceof DeferredMarker)) return data;
84
- const out: Record<string, unknown> = {};
85
- for (const [k, v] of Object.entries(data as Record<string, unknown>)) {
86
- out[k] = v instanceof DeferredMarker ? undefined : v;
87
- }
88
- return out;
89
- }
90
-
91
- /** Template + patch script for one settled deferred value. */
92
- function deferredChunk(key: string, value: unknown, error: boolean): string {
93
- const keyJson = JSON.stringify(key);
94
- // The value rides inline (safeStateJson escapes `<`, so the script cannot
95
- // be broken out of). No DOM lookups: trailing chunks arrive after </html>,
96
- // where element timing is unreliable across parsers.
97
- return `<script>(function(){var value=${safeStateJson(value)};var tag=document.getElementById("__grimoire_state__");if(tag){try{var s=JSON.parse(tag.textContent);s.data[${keyJson}]=value;tag.textContent=JSON.stringify(s)}catch(e){}}var w=window.__grimoire_state__;if(!w||w.nodeType)w=window.__grimoire_state__={data:{}};if(!w.data)w.data={};w.data[${keyJson}]=value;window.dispatchEvent(new CustomEvent("grimoire:deferred",{detail:{key:${keyJson},error:${error ? "true" : "false"}}}))})()</script>`;
98
- }
99
-
100
- /**
101
- * PUBLIC_ environment variables for `$env/dynamic/public` in the browser,
102
- * as the server sees them now.
103
- */
104
- function publicEnvScript(nonceAttr: string): string {
105
- const env = filterPublic(process.env);
106
- if (Object.keys(env).length === 0) return "";
107
- return `\n <script${nonceAttr}>window.__grimoire_env__=${safeStateJson(env)}</script>`;
108
- }
109
-
110
- function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
111
- return `<!DOCTYPE html>
112
- <html>
113
- <head>
114
- <meta charset="UTF-8" />
115
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />${publicEnvScript(nonceAttr)}
116
- <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
117
- ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
118
- }
119
-
120
- /**
121
- * Copy `<link rel="stylesheet">` tags found in rendered body HTML so they can
122
- * be emitted in <head>, where they are render-blocking. Components declare
123
- * stylesheets inline in JSX (usually in a layout), which lands them in the
124
- * body — the browser paints the unstyled document before body CSS applies,
125
- * causing a white flash on every full-document load. The body originals are
126
- * left in place so hydration can still claim them; the head copy shares the
127
- * same URL, so the browser only fetches once.
128
- */
129
- function hoistStylesheets(bodyHtml: string): string {
130
- const links = new Set<string>();
131
- for (const m of bodyHtml.matchAll(
132
- /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi,
133
- )) {
134
- links.add(m[0]);
135
- }
136
- return [...links].join("\n ");
137
- }
138
-
139
- /**
140
- * <style> tags for the scoped CSS of every component file whose scope class
141
- * appears in `html`. Server builds register each file's CSS by hash (see
142
- * serverStyleSnippet in the compiler), so a server-rendered page is styled
143
- * before any script runs; the browser build's own injection sees the id and
144
- * skips it.
145
- */
146
- function scopedStyles(html: string, nonceAttr: string): string {
147
- const registry = (globalThis as { __sigil_css__?: Map<string, string> })
148
- .__sigil_css__;
149
- if (!registry) return "";
150
- let out = "";
151
- for (const [hash, css] of registry) {
152
- if (!html.includes(hash)) continue;
153
- out += `<style id="sigil-${hash}"${nonceAttr}>${css.replace(/<\/style/gi, "<\\/style")}</style>`;
154
- }
155
- return out;
156
- }
157
-
158
- /**
159
- * The CSRF token for this response: the visitor's existing `_csrf` cookie
160
- * when it holds a well-formed token, so pages open in other tabs keep
161
- * working, otherwise a fresh one.
162
- */
163
- function csrfTokenFor(req: Request): string {
164
- const m = /(?:^|;\s*)_csrf=([0-9a-f]{64})(?:;|$)/.exec(
165
- req.headers.get("cookie") ?? "",
166
- );
167
- return m?.[1] ?? randomBytes(32).toString("hex");
168
- }
169
-
170
- /**
171
- * Put the token into every POST form, with or without an action attribute
172
- * (one without posts back to the page). GET forms never get it: the token
173
- * would end up in the URL, and a GET is never CSRF-checked anyway.
174
- */
175
- function injectCsrf(html: string, token: string): string {
176
- const input = `<input type="hidden" name="_csrf" value="${token}" data-grimoire-csrf>`;
177
- return html.replace(
178
- /<form\b([^>]*\bmethod=["']?post["']?[^>]*)>/gi,
179
- `<form$1>${input}`,
180
- );
181
- }
182
-
183
- const csrfCookie = (token: string) => `_csrf=${token}; SameSite=Strict; Path=/`;
184
-
185
- /**
186
- * The collected <Head> tags between marker comments, so the client router
187
- * can find and replace them on navigation.
188
- */
189
- const headBlock = (headHtml: string) =>
190
- `<!--grimoire-head-->${headHtml}<!--/grimoire-head-->`;
191
-
192
- /** Wrap page/error HTML in whatever parent layouts loaded successfully. */
193
- function applyLayoutTree(
194
- innerHtml: string,
195
- layoutPairs: LayoutPair[],
196
- params: Record<string, string>,
197
- pattern?: string,
198
- innerId = "grimoire-page",
199
- ): string {
200
- let bodyHtml = `<div id="${innerId}">${innerHtml}</div>`;
201
- for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
202
- bodyHtml = String(
203
- layoutMod.default({
204
- data: renderable(data),
205
- children: new SafeHtml(bodyHtml),
206
- params,
207
- path: pattern,
208
- }),
209
- );
210
- }
211
- return `<div id="grimoire-root">${bodyHtml}</div>`;
212
- }
213
-
214
- /**
215
- * Render a +error.tsx page as a full HTML document (doctype, hydration
216
- * script, and any parent layouts that had already loaded successfully),
217
- * instead of a bare fragment. No __grimoire_state__ script is emitted —
218
- * error pages aren't part of the client route table, so hydrate.js
219
- * simply skips client hydration for them (SSR-only, which is correct
220
- * since there's no client-side error route to hydrate against).
221
- */
222
- export async function renderErrorPage(
223
- errorRoutes: RouteFile[],
224
- pathname: string,
225
- status: number,
226
- message: string,
227
- error: unknown,
228
- loadModule: ModuleLoader,
229
- opts: {
230
- layoutPairs?: LayoutPair[];
231
- params?: Record<string, string>;
232
- nonceAttr?: string;
233
- dev?: boolean;
234
- } = {},
235
- ): Promise<Response | null> {
236
- const errorPage = findClosestError(errorRoutes, pathname);
237
- if (!errorPage) return null;
238
- const mod = await loadModule(errorPage.filePath);
239
-
240
- const { layoutPairs = [], params = {}, nonceAttr = "", dev } = opts;
241
-
242
- // own context so <Head> used by the error page (or wrapping layouts)
243
- // is collected fresh, independent of whatever the failed page pushed
244
- return runWithContext(async () => {
245
- const nonce = nonceAttr.match(/nonce="([^"]+)"/)?.[1];
246
- initHead(nonce);
247
-
248
- const errorHtml = String(
249
- mod.default({ status, message, error, route: pathname }),
250
- );
251
- const bodyHtml = applyLayoutTree(errorHtml, layoutPairs, params);
252
- const headHtml = collectHead();
253
- const hoistedCss = hoistStylesheets(bodyHtml);
254
- const styles = scopedStyles(bodyHtml, nonceAttr);
255
-
256
- const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${styles ? `\n ${styles}` : ""}\n${headBlock(headHtml)}
257
- </head>
258
- <body>
259
- <div id="app">${bodyHtml}</div>
260
- </body>
261
- </html>`;
262
-
263
- return new Response(html, {
264
- status,
265
- headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
266
- });
267
- });
268
- }
269
-
270
- export async function renderRoute(
271
- matched: MatchedRoute,
272
- req: Request,
273
- errorRoutes: RouteFile[] = [],
274
- loadModule: ModuleLoader = (path) => import(path),
275
- locals: Record<string, any> = {},
276
- plugins: GrimoirePlugin[] = [],
277
- cspNonce?: string,
278
- dev?: boolean,
279
- patchedFetch?: typeof fetch,
280
- /** A form action's fail() on a plain (non-enhanced) POST: the page renders
281
- * again with the failure as its `form` prop, and with its status. */
282
- actionFailure?: { status: number; data: unknown },
283
- ): Promise<Response> {
284
- return runWithContext(async () => {
285
- const context: LoadContext = {
286
- request: req,
287
- params: matched.params,
288
- url: new URL(req.url),
289
- locals,
290
- fetch: patchedFetch ?? globalThis.fetch,
291
- getClientAddress: () => clientAddressOf(req),
292
- // no layouts have loaded yet — parent() is empty until the loop runs
293
- parent: async () => ({}),
294
- };
295
-
296
- const timer = createTimer();
297
- initHead(cspNonce);
298
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
299
-
300
- // ── layout loading ──────────────────────────────────────────────────────
301
- const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
302
- const parentData: Record<string, unknown> = {};
303
- // depends() keys gathered across every server-executed load
304
- const collectedDeps = new Set<string>();
305
- // top-level load promises flushed late (deferred streaming)
306
- const deferred: DeferredEntry[] = [];
307
- const deferredCounter = { n: 0 };
308
- const collectDeps = async (run: () => unknown): Promise<unknown> => {
309
- startCollecting();
310
- try {
311
- return await run();
312
- } finally {
313
- for (const key of stopCollecting()) collectedDeps.add(key);
314
- }
315
- };
316
-
317
- const route: Route = {
318
- path: matched.route.path,
319
- params: matched.params,
320
- filePath: matched.route.filePath,
321
- loadPath: matched.pageServer?.filePath,
322
- layoutPath: matched.layouts.at(-1)?.filePath,
323
- };
324
- await runHook(plugins, "onRouteLoad", route, context);
325
-
326
- // One level per folder with a +layout.tsx, a +layout.server.ts, or
327
- // both. A server load without a layout component still runs: it's
328
- // where a folder's guard lives, and skipping it left the folder open.
329
- const levels = [
330
- ...new Set(
331
- [...matched.layouts, ...matched.layoutServers].map((l) => l.path),
332
- ),
333
- ].sort((a, b) => a.length - b.length);
334
-
335
- for (const levelPath of levels) {
336
- const layout = matched.layouts.find((l) => l.path === levelPath);
337
- // loads in this layout see everything accumulated so far
338
- context.parent = async () => ({ ...parentData });
339
-
340
- const layoutMod = layout ? await loadModule(layout.filePath) : {};
341
-
342
- if (layoutMod.canMatch) {
343
- try {
344
- const result = await layoutMod.canMatch(context);
345
- if (result === false)
346
- return new Response("Not Found", { status: 404 });
347
- if (isRedirectResult(result))
348
- return new Response(null, {
349
- status: result.status,
350
- headers: { Location: result.location },
351
- });
352
- } catch (e) {
353
- if (isRedirectResult(e))
354
- return new Response(null, {
355
- status: e.status,
356
- headers: { Location: e.location },
357
- });
358
- if (isErrorResult(e))
359
- return (
360
- (await renderErrorPage(
361
- errorRoutes,
362
- context.url.pathname,
363
- e.status,
364
- e.message,
365
- e,
366
- loadModule,
367
- { layoutPairs, params: matched.params, nonceAttr, dev },
368
- )) ?? new Response(e.message, { status: e.status })
369
- );
370
- throw e;
371
- }
372
- }
373
-
374
- const layoutServer = matched.layoutServers.find(
375
- (ls) => ls.path === levelPath,
376
- );
377
- let data: unknown;
378
- if (layoutServer) {
379
- try {
380
- const mod = await loadModule(layoutServer.filePath);
381
- data = await collectDeps(() => mod.load?.(context));
382
- } catch (e) {
383
- if (isRedirectResult(e))
384
- return new Response(null, {
385
- status: e.status,
386
- headers: { Location: e.location },
387
- });
388
- if (isErrorResult(e))
389
- return (
390
- (await renderErrorPage(
391
- errorRoutes,
392
- context.url.pathname,
393
- e.status,
394
- e.message,
395
- e,
396
- loadModule,
397
- { layoutPairs, params: matched.params, nonceAttr, dev },
398
- )) ?? new Response(e.message, { status: e.status })
399
- );
400
- throw e;
401
- }
402
- }
403
-
404
- const universalLayoutData = layoutMod.load
405
- ? await collectDeps(() => layoutMod.load(context))
406
- : undefined;
407
-
408
- const mergedLayoutData =
409
- universalLayoutData !== undefined
410
- ? //@ts-expect-error user-provided data is always unknown
411
- { ...universalLayoutData, ...data }
412
- : data;
413
-
414
- // only components wrap the page; the client indexes layoutData by them
415
- if (layout)
416
- layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
417
- extractDeferred(mergedLayoutData, deferred, deferredCounter);
418
- if (mergedLayoutData && typeof mergedLayoutData === "object") {
419
- Object.assign(parentData, mergedLayoutData);
420
- }
421
- }
422
-
423
- // no page at this address: its layouts are loaded, the 404 goes in them
424
- if (matched.notFound)
425
- return (
426
- (await renderErrorPage(
427
- errorRoutes,
428
- context.url.pathname,
429
- 404,
430
- "Not Found",
431
- null,
432
- loadModule,
433
- { layoutPairs, params: matched.params, nonceAttr, dev },
434
- )) ?? new Response("Not Found", { status: 404 })
435
- );
436
-
437
- // page loads see every layout's data merged
438
- context.parent = async () => ({ ...parentData });
439
-
440
- // ── page server load ────────────────────────────────────────────────────
441
- let pageData: unknown;
442
- if (matched.pageServer) {
443
- try {
444
- const mod = await loadModule(matched.pageServer.filePath);
445
- pageData = await collectDeps(() => mod.load?.(context));
446
- } catch (e) {
447
- if (isRedirectResult(e))
448
- return new Response(null, {
449
- status: e.status,
450
- headers: { Location: e.location },
451
- });
452
- if (isErrorResult(e))
453
- return (
454
- (await renderErrorPage(
455
- errorRoutes,
456
- context.url.pathname,
457
- e.status,
458
- e.message,
459
- e,
460
- loadModule,
461
- { layoutPairs, params: matched.params, nonceAttr, dev },
462
- )) ?? new Response(e.message, { status: e.status })
463
- );
464
- throw e;
465
- }
466
- }
467
-
468
- // ── page module ─────────────────────────────────────────────────────────
469
- const pageMod = await loadModule(matched.route.filePath);
470
-
471
- if (pageMod.canMatch) {
472
- try {
473
- const result = await pageMod.canMatch(context);
474
- if (result === false) return new Response("Not Found", { status: 404 });
475
- if (isRedirectResult(result))
476
- return new Response(null, {
477
- status: result.status,
478
- headers: { Location: result.location },
479
- });
480
- } catch (e) {
481
- if (isRedirectResult(e))
482
- return new Response(null, {
483
- status: e.status,
484
- headers: { Location: e.location },
485
- });
486
- if (isErrorResult(e))
487
- return (
488
- (await renderErrorPage(
489
- errorRoutes,
490
- context.url.pathname,
491
- e.status,
492
- e.message,
493
- e,
494
- loadModule,
495
- { layoutPairs, params: matched.params, nonceAttr, dev },
496
- )) ?? new Response(e.message, { status: e.status })
497
- );
498
- throw e;
499
- }
500
- }
501
-
502
- const isNavigate = req.headers.get(NAVIGATE_HEADER) === "1";
503
- const hasLoading = typeof pageMod.loading === "function";
504
-
505
- // helper: wrap page html in layout tree
506
- function applyLayouts(pageHtml: string): string {
507
- return applyLayoutTree(
508
- pageHtml,
509
- layoutPairs,
510
- matched.params,
511
- matched.route.path,
512
- );
513
- }
514
-
515
- // ── two-pass streaming (loading export present) ─────────────────────────
516
- if (hasLoading && !isNavigate) {
517
- const uid = Math.random().toString(36).slice(2);
518
- const csrfToken = csrfTokenFor(req);
519
- const loadingHtml = String(pageMod.loading());
520
- const loadingBody = injectCsrf(
521
- applyLayouts(`<div id="ab-${uid}">${loadingHtml}</div>`),
522
- csrfToken,
523
- );
524
- // layout stylesheets are in the loading shell — hoist before first flush
525
- const hoistedCss = hoistStylesheets(loadingBody);
526
- const shellStyles = scopedStyles(loadingBody, nonceAttr);
527
-
528
- const stream = new ReadableStream({
529
- async start(controller) {
530
- // 1. skeleton + loading shell — browser paints immediately
531
- controller.enqueue(
532
- `${buildHtmlSkeleton(nonceAttr, dev)}${preloadLinks(matched.route.path, nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
533
- </head>
534
- <body>
535
- <div id="app">${loadingBody}`,
536
- );
537
-
538
- // 2. run universal load while browser renders shell
539
- const universalData = pageMod.load
540
- ? await collectDeps(() => pageMod.load(context)).catch(
541
- (e: unknown) => {
542
- if (isRedirectResult(e)) throw e;
543
- if (isErrorResult(e)) throw e;
544
- throw e;
545
- },
546
- )
547
- : undefined;
548
-
549
- const mergedData =
550
- universalData !== undefined
551
- ? //@ts-expect-error user-provided data is always unknown
552
- { ...universalData, ...pageData }
553
- : pageData;
554
- extractDeferred(mergedData, deferred, deferredCounter);
555
-
556
- // 3. render real page + collect head
557
- const pageHtml = injectCsrf(
558
- String(
559
- await Promise.resolve(
560
- pageMod.default({
561
- data: renderable(mergedData),
562
- params: matched.params,
563
- form: actionFailure?.data,
564
- }),
565
- ),
566
- ),
567
- csrfToken,
568
- );
569
- const headHtml = collectHead();
570
- const stateJson = safeStateJson({
571
- params: matched.params,
572
- data: mergedData,
573
- layoutData: layoutPairs.map((l) => l.data),
574
- pattern: matched.route.path,
575
- deps: [...collectedDeps],
576
- form: actionFailure?.data,
577
- });
578
-
579
- // 4. inject late head tags
580
- if (headHtml) {
581
- controller.enqueue(
582
- `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString(${JSON.stringify(`<head>${headHtml}</head>`).replace(/</g, "\\u003c")},"text/html");for(var e of Array.from(p.head.children)){var c=e.cloneNode(true);c.setAttribute("data-grimoire-head","1");document.head.appendChild(c)}})();</script>`,
583
- );
584
- }
585
-
586
- // 5. swap shell with real content
587
- controller.enqueue(
588
- `<template id="ab-${uid}-r">${scopedStyles(String(pageHtml), nonceAttr)}${String(pageHtml)}</template>
589
- <script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
590
- <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
591
- </div>
592
- </body>
593
- </html>`,
594
- );
595
-
596
- // 6. flush deferred values in order as they settle
597
- for (const d of deferred) {
598
- try {
599
- const value = await d.promise;
600
- controller.enqueue(deferredChunk(d.key, value, false));
601
- } catch {
602
- controller.enqueue(deferredChunk(d.key, null, true));
603
- }
604
- }
605
-
606
- controller.close();
607
- },
608
- });
609
-
610
- return new Response(stream, {
611
- status: actionFailure?.status ?? 200,
612
- headers: {
613
- "Content-Type": "text/html",
614
- "Set-Cookie": csrfCookie(csrfToken),
615
- Vary: NAVIGATE_HEADER,
616
- },
617
- });
618
- }
619
-
620
- // ── single-pass (no loading export) ────────────────────────────────────
621
- const universalData = pageMod.load
622
- ? await collectDeps(() => pageMod.load(context)).catch((e) => {
623
- if (isRedirectResult(e)) throw e;
624
- if (isErrorResult(e)) throw e;
625
- throw e;
626
- })
627
- : undefined;
628
-
629
- const mergedData =
630
- universalData !== undefined
631
- ? //@ts-expect-error user-provided data is always unknown
632
- { ...universalData, ...pageData }
633
- : pageData;
634
- extractDeferred(mergedData, deferred, deferredCounter);
635
-
636
- timer.mark("load");
637
- const pageHtml = await Promise.resolve(
638
- pageMod.default({
639
- data: renderable(mergedData),
640
- params: matched.params,
641
- form: actionFailure?.data,
642
- }),
643
- );
644
-
645
- // layouts must render before collectHead(): a <Head> call inside a
646
- // layout component (a common place for site-wide <title>/meta
647
- // defaults) only registers once the layout itself has run, so
648
- // collecting too early silently drops it
649
- let bodyHtml = applyLayouts(String(pageHtml));
650
- timer.mark("render");
651
-
652
- const headHtml = collectHead();
653
-
654
- if (isNavigate) {
655
- // no stream to flush into — resolve everything before responding
656
- for (const d of deferred) {
657
- try {
658
- (mergedData as Record<string, unknown>)[d.key] = await d.promise;
659
- } catch {
660
- (mergedData as Record<string, unknown>)[d.key] = null;
661
- }
662
- }
663
- // Vary is mandatory here: this JSON and the HTML document share one
664
- // URL and are chosen by a request header, so without it any cache may
665
- // hand the JSON to a plain document request. That is what surfaced as
666
- // raw state payloads rendering as the page after a back navigation.
667
- // Deliberately still cacheable: hover-prefetch exists to warm this
668
- // entry, and Vary already keeps document requests from matching it.
669
- timer.mark("deferred");
670
- return Response.json(
671
- {
672
- data: mergedData ?? {},
673
- layoutData: layoutPairs.map((l) => l.data),
674
- params: matched.params,
675
- pattern: matched.route.path,
676
- head: headHtml,
677
- deps: [...collectedDeps],
678
- },
679
- { headers: { Vary: NAVIGATE_HEADER, ...timer.headers() } },
680
- );
681
- }
682
-
683
- // ── single-pass SSR stream ──────────────────────────────────────────────
684
- const csrfToken = csrfTokenFor(req);
685
- const stateJson = safeStateJson({
686
- params: matched.params,
687
- data: mergedData,
688
- layoutData: layoutPairs.map((l) => l.data),
689
- pattern: matched.route.path,
690
- deps: [...collectedDeps],
691
- form: actionFailure?.data,
692
- });
693
-
694
- bodyHtml = optimizeImages(injectCsrf(bodyHtml, csrfToken));
695
-
696
- const hoistedCss = hoistStylesheets(bodyHtml);
697
- const styles = scopedStyles(bodyHtml, nonceAttr);
698
-
699
- const stream = new ReadableStream({
700
- async start(controller) {
701
- controller.enqueue(
702
- buildHtmlSkeleton(nonceAttr, dev) +
703
- preloadLinks(matched.route.path, nonceAttr, dev),
704
- );
705
-
706
- if (hoistedCss) {
707
- controller.enqueue(`\n ${hoistedCss}`);
708
- }
709
- if (styles) {
710
- controller.enqueue(`\n ${styles}`);
711
- }
712
- controller.enqueue(`\n${headBlock(headHtml)}`);
713
-
714
- controller.enqueue(`\n</head>
715
- <body>
716
- <div id="app">${bodyHtml}</div>
717
- <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
718
- </body>
719
- </html>`);
720
-
721
- // flush deferred values in order as they settle
722
- for (const d of deferred) {
723
- try {
724
- const value = await d.promise;
725
- controller.enqueue(deferredChunk(d.key, value, false));
726
- } catch {
727
- controller.enqueue(deferredChunk(d.key, null, true));
728
- }
729
- }
730
-
731
- controller.close();
732
- },
733
- });
734
-
735
- return new Response(stream, {
736
- status: actionFailure?.status ?? 200,
737
- headers: {
738
- "Content-Type": "text/html",
739
- "Set-Cookie": csrfCookie(csrfToken),
740
- Vary: NAVIGATE_HEADER,
741
- ...timer.headers(),
742
- },
743
- });
744
- });
745
- }
1
+ import { randomBytes } from "node:crypto";
2
+ import { SafeHtml } from "@sigil-dev/runtime";
3
+ import { startCollecting, stopCollecting } from "../client/deps";
4
+ import { filterPublic } from "../env/index";
5
+ import { findClosestError, type MatchedRoute } from "../routing/router";
6
+ import type { RouteFile } from "../routing/scanner";
7
+ import { isErrorResult } from "../sentinels/error.ts";
8
+ import { isRedirectResult } from "../sentinels/redirect.ts";
9
+ import { clientAddressOf } from "../server/client-address";
10
+ import { hydrateEntry } from "../server/client-entry";
11
+ import { runWithContext } from "../server/context";
12
+ import { base, withBase } from "../base";
13
+ import { runHook } from "../server/plugins";
14
+ import type { GrimoirePlugin, LoadContext, Route } from "../types";
15
+ import { collectHead, initHead } from "./head";
16
+ import { optimizeImages } from "./images.ts";
17
+ import { preloadLinks } from "./preload.ts";
18
+ import { createTimer } from "./timing.ts";
19
+
20
+ /** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
21
+ const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
22
+
23
+ export type ModuleLoader = (path: string) => Promise<any>;
24
+
25
+ type LayoutPair = { layout: RouteFile; mod: any; data: unknown };
26
+
27
+ /** Placeholder for a top-level server-load promise still in flight. SSR text
28
+ * interpolation renders it as an empty string via the normal String(v) path. */
29
+ class DeferredMarker {
30
+ constructor(
31
+ public uid: string,
32
+ public key: string,
33
+ ) {}
34
+ toString() {
35
+ return "";
36
+ }
37
+ }
38
+
39
+ type DeferredEntry = { promise: Promise<unknown>; key: string; uid: string };
40
+
41
+ /**
42
+ * Request header the client router sets to ask for the JSON navigate payload
43
+ * instead of an HTML document. Both representations live at the same URL, so
44
+ * every response that depends on it MUST also send it in `Vary`.
45
+ */
46
+ export const NAVIGATE_HEADER = "x-grimoire-navigate";
47
+
48
+ /**
49
+ * Serialize the hydration state payload for embedding inside a
50
+ * `<script type="application/json">` tag. Escapes every `<` so a data value
51
+ * like `"</script><script>alert(1)</script>"` cannot close the state script
52
+ * early and inject markup. JSON.parse reads `\u003c` back as `<`.
53
+ * DeferredMarkers serialize to `{ __deferred: uid }`.
54
+ */
55
+ const safeStateJson = (value: unknown): string =>
56
+ JSON.stringify(value, (_k, v) =>
57
+ v instanceof DeferredMarker ? { __deferred: v.uid } : v,
58
+ ).replace(/</g, "\\u003c");
59
+
60
+ /** Replace every own top-level promise property with a marker and record the
61
+ * promise for late flush. Nested promises are awaited by the load itself. */
62
+ function extractDeferred(
63
+ data: unknown,
64
+ deferred: DeferredEntry[],
65
+ counter: { n: number },
66
+ ): void {
67
+ if (!data || typeof data !== "object" || Array.isArray(data)) return;
68
+ const record = data as Record<string, unknown>;
69
+ for (const key of Object.keys(record)) {
70
+ const value = record[key];
71
+ if (value instanceof Promise) {
72
+ const uid = `gd-${counter.n++}`;
73
+ record[key] = new DeferredMarker(uid, key);
74
+ deferred.push({ promise: value, key, uid });
75
+ }
76
+ }
77
+ }
78
+
79
+ /**
80
+ * The data a component renders with on the server: a value still in flight
81
+ * reads as `undefined`, so `{data.reviews ?? "Loading…"}` shows its
82
+ * fallback. The state script keeps the markers, and the settled values
83
+ * reach the browser before it hydrates.
84
+ */
85
+ function renderable(data: unknown): unknown {
86
+ if (!data || typeof data !== "object" || Array.isArray(data)) return data;
87
+ const values = Object.values(data as Record<string, unknown>);
88
+ if (!values.some((v) => v instanceof DeferredMarker)) return data;
89
+ const out: Record<string, unknown> = {};
90
+ for (const [k, v] of Object.entries(data as Record<string, unknown>)) {
91
+ out[k] = v instanceof DeferredMarker ? undefined : v;
92
+ }
93
+ return out;
94
+ }
95
+
96
+ /** Template + patch script for one settled deferred value. */
97
+ function deferredChunk(key: string, value: unknown, error: boolean): string {
98
+ const keyJson = JSON.stringify(key);
99
+ // The value rides inline (safeStateJson escapes `<`, so the script cannot
100
+ // be broken out of). No DOM lookups: trailing chunks arrive after </html>,
101
+ // where element timing is unreliable across parsers.
102
+ return `<script>(function(){var value=${safeStateJson(value)};var tag=document.getElementById("__grimoire_state__");if(tag){try{var s=JSON.parse(tag.textContent);s.data[${keyJson}]=value;tag.textContent=JSON.stringify(s)}catch(e){}}var w=window.__grimoire_state__;if(!w||w.nodeType)w=window.__grimoire_state__={data:{}};if(!w.data)w.data={};w.data[${keyJson}]=value;window.dispatchEvent(new CustomEvent("grimoire:deferred",{detail:{key:${keyJson},error:${error ? "true" : "false"}}}))})()</script>`;
103
+ }
104
+
105
+ /**
106
+ * PUBLIC_ environment variables for `$env/dynamic/public` in the browser,
107
+ * as the server sees them now.
108
+ */
109
+ function publicEnvScript(nonceAttr: string): string {
110
+ const env = filterPublic(process.env);
111
+ if (Object.keys(env).length === 0) return "";
112
+ return `\n <script${nonceAttr}>window.__grimoire_env__=${safeStateJson(env)}</script>`;
113
+ }
114
+
115
+ function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
116
+ // a meta tag, not a script: the base has to reach the router under a CSP
117
+ // nonce too, and the bundle reads it so one build works under any base
118
+ const baseMeta = base
119
+ ? `\n <meta name="grimoire-base" content="${base}" />`
120
+ : "";
121
+ return `<!DOCTYPE html>
122
+ <html>
123
+ <head>
124
+ <meta charset="UTF-8" />
125
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />${publicEnvScript(nonceAttr)}
126
+ <script type="module" src="/__grimoire__/${hydrateEntry()}"${nonceAttr}></script>
127
+ ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
128
+ }
129
+
130
+ /**
131
+ * Copy `<link rel="stylesheet">` tags found in rendered body HTML so they can
132
+ * be emitted in <head>, where they are render-blocking. Components declare
133
+ * stylesheets inline in JSX (usually in a layout), which lands them in the
134
+ * body — the browser paints the unstyled document before body CSS applies,
135
+ * causing a white flash on every full-document load. The body originals are
136
+ * left in place so hydration can still claim them; the head copy shares the
137
+ * same URL, so the browser only fetches once.
138
+ */
139
+ function hoistStylesheets(bodyHtml: string): string {
140
+ const links = new Set<string>();
141
+ for (const m of bodyHtml.matchAll(
142
+ /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi,
143
+ )) {
144
+ links.add(m[0]);
145
+ }
146
+ return [...links].join("\n ");
147
+ }
148
+
149
+ /**
150
+ * <style> tags for the scoped CSS of every component file whose scope class
151
+ * appears in `html`. Server builds register each file's CSS by hash (see
152
+ * serverStyleSnippet in the compiler), so a server-rendered page is styled
153
+ * before any script runs; the browser build's own injection sees the id and
154
+ * skips it.
155
+ */
156
+ function scopedStyles(html: string, nonceAttr: string): string {
157
+ const registry = (globalThis as { __sigil_css__?: Map<string, string> })
158
+ .__sigil_css__;
159
+ if (!registry) return "";
160
+ let out = "";
161
+ for (const [hash, css] of registry) {
162
+ if (!html.includes(hash)) continue;
163
+ out += `<style id="sigil-${hash}"${nonceAttr}>${css.replace(/<\/style/gi, "<\\/style")}</style>`;
164
+ }
165
+ return out;
166
+ }
167
+
168
+ /**
169
+ * The CSRF token for this response: the visitor's existing `_csrf` cookie
170
+ * when it holds a well-formed token, so pages open in other tabs keep
171
+ * working, otherwise a fresh one.
172
+ */
173
+ function csrfTokenFor(req: Request): string {
174
+ const m = /(?:^|;\s*)_csrf=([0-9a-f]{64})(?:;|$)/.exec(
175
+ req.headers.get("cookie") ?? "",
176
+ );
177
+ return m?.[1] ?? randomBytes(32).toString("hex");
178
+ }
179
+
180
+ /**
181
+ * Put the token into every POST form, with or without an action attribute
182
+ * (one without posts back to the page). GET forms never get it: the token
183
+ * would end up in the URL, and a GET is never CSRF-checked anyway.
184
+ */
185
+ function injectCsrf(html: string, token: string): string {
186
+ const input = `<input type="hidden" name="_csrf" value="${token}" data-grimoire-csrf>`;
187
+ return html.replace(
188
+ /<form\b([^>]*\bmethod=["']?post["']?[^>]*)>/gi,
189
+ `<form$1>${input}`,
190
+ );
191
+ }
192
+
193
+ const csrfCookie = (token: string) => `_csrf=${token}; SameSite=Strict; Path=/`;
194
+
195
+ /**
196
+ * The collected <Head> tags between marker comments, so the client router
197
+ * can find and replace them on navigation.
198
+ */
199
+ const headBlock = (headHtml: string) =>
200
+ `<!--grimoire-head-->${headHtml}<!--/grimoire-head-->`;
201
+
202
+ /** Wrap page/error HTML in whatever parent layouts loaded successfully. */
203
+ function applyLayoutTree(
204
+ innerHtml: string,
205
+ layoutPairs: LayoutPair[],
206
+ params: Record<string, string>,
207
+ pattern?: string,
208
+ innerId = "grimoire-page",
209
+ ): string {
210
+ let bodyHtml = `<div id="${innerId}">${innerHtml}</div>`;
211
+ for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
212
+ bodyHtml = String(
213
+ layoutMod.default({
214
+ data: renderable(data),
215
+ children: new SafeHtml(bodyHtml),
216
+ params,
217
+ path: pattern,
218
+ }),
219
+ );
220
+ }
221
+ return `<div id="grimoire-root">${bodyHtml}</div>`;
222
+ }
223
+
224
+ /**
225
+ * Render a +error.tsx page as a full HTML document (doctype, hydration
226
+ * script, and any parent layouts that had already loaded successfully),
227
+ * instead of a bare fragment. No __grimoire_state__ script is emitted —
228
+ * error pages aren't part of the client route table, so hydrate.js
229
+ * simply skips client hydration for them (SSR-only, which is correct
230
+ * since there's no client-side error route to hydrate against).
231
+ */
232
+ export async function renderErrorPage(
233
+ errorRoutes: RouteFile[],
234
+ pathname: string,
235
+ status: number,
236
+ message: string,
237
+ error: unknown,
238
+ loadModule: ModuleLoader,
239
+ opts: {
240
+ layoutPairs?: LayoutPair[];
241
+ params?: Record<string, string>;
242
+ nonceAttr?: string;
243
+ dev?: boolean;
244
+ } = {},
245
+ ): Promise<Response | null> {
246
+ const errorPage = findClosestError(errorRoutes, pathname);
247
+ if (!errorPage) return null;
248
+ const mod = await loadModule(errorPage.filePath);
249
+
250
+ const { layoutPairs = [], params = {}, nonceAttr = "", dev } = opts;
251
+
252
+ // own context so <Head> used by the error page (or wrapping layouts)
253
+ // is collected fresh, independent of whatever the failed page pushed
254
+ return runWithContext(async () => {
255
+ const nonce = nonceAttr.match(/nonce="([^"]+)"/)?.[1];
256
+ initHead(nonce);
257
+
258
+ const errorHtml = String(
259
+ mod.default({ status, message, error, route: pathname }),
260
+ );
261
+ const bodyHtml = applyLayoutTree(errorHtml, layoutPairs, params);
262
+ const headHtml = collectHead();
263
+ const hoistedCss = hoistStylesheets(bodyHtml);
264
+ const styles = scopedStyles(bodyHtml, nonceAttr);
265
+
266
+ const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${styles ? `\n ${styles}` : ""}\n${headBlock(headHtml)}
267
+ </head>
268
+ <body>
269
+ <div id="app">${bodyHtml}</div>
270
+ </body>
271
+ </html>`;
272
+
273
+ return new Response(html, {
274
+ status,
275
+ headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
276
+ });
277
+ });
278
+ }
279
+
280
+ export async function renderRoute(
281
+ matched: MatchedRoute,
282
+ req: Request,
283
+ errorRoutes: RouteFile[] = [],
284
+ loadModule: ModuleLoader = (path) => import(path),
285
+ locals: Record<string, any> = {},
286
+ plugins: GrimoirePlugin[] = [],
287
+ cspNonce?: string,
288
+ dev?: boolean,
289
+ patchedFetch?: typeof fetch,
290
+ /** A form action's fail() on a plain (non-enhanced) POST: the page renders
291
+ * again with the failure as its `form` prop, and with its status. */
292
+ actionFailure?: { status: number; data: unknown },
293
+ ): Promise<Response> {
294
+ return runWithContext(async () => {
295
+ const context: LoadContext = {
296
+ request: req,
297
+ params: matched.params,
298
+ url: new URL(req.url),
299
+ locals,
300
+ fetch: patchedFetch ?? globalThis.fetch,
301
+ getClientAddress: () => clientAddressOf(req),
302
+ // no layouts have loaded yet — parent() is empty until the loop runs
303
+ parent: async () => ({}),
304
+ };
305
+
306
+ const timer = createTimer();
307
+ initHead(cspNonce);
308
+ const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
309
+
310
+ // ── layout loading ──────────────────────────────────────────────────────
311
+ const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
312
+ const parentData: Record<string, unknown> = {};
313
+ // depends() keys gathered across every server-executed load
314
+ const collectedDeps = new Set<string>();
315
+ // top-level load promises flushed late (deferred streaming)
316
+ const deferred: DeferredEntry[] = [];
317
+ const deferredCounter = { n: 0 };
318
+ const collectDeps = async (run: () => unknown): Promise<unknown> => {
319
+ startCollecting();
320
+ try {
321
+ return await run();
322
+ } finally {
323
+ for (const key of stopCollecting()) collectedDeps.add(key);
324
+ }
325
+ };
326
+
327
+ const route: Route = {
328
+ path: matched.route.path,
329
+ params: matched.params,
330
+ filePath: matched.route.filePath,
331
+ loadPath: matched.pageServer?.filePath,
332
+ layoutPath: matched.layouts.at(-1)?.filePath,
333
+ };
334
+ await runHook(plugins, "onRouteLoad", route, context);
335
+
336
+ // One level per folder with a +layout.tsx, a +layout.server.ts, or
337
+ // both. A server load without a layout component still runs: it's
338
+ // where a folder's guard lives, and skipping it left the folder open.
339
+ const levels = [
340
+ ...new Set(
341
+ [...matched.layouts, ...matched.layoutServers].map((l) => l.path),
342
+ ),
343
+ ].sort((a, b) => a.length - b.length);
344
+
345
+ for (const levelPath of levels) {
346
+ const layout = matched.layouts.find((l) => l.path === levelPath);
347
+ // loads in this layout see everything accumulated so far
348
+ context.parent = async () => ({ ...parentData });
349
+
350
+ const layoutMod = layout ? await loadModule(layout.filePath) : {};
351
+
352
+ if (layoutMod.canMatch) {
353
+ try {
354
+ const result = await layoutMod.canMatch(context);
355
+ if (result === false)
356
+ return new Response("Not Found", { status: 404 });
357
+ if (isRedirectResult(result))
358
+ return new Response(null, {
359
+ status: result.status,
360
+ headers: { Location: result.location },
361
+ });
362
+ } catch (e) {
363
+ if (isRedirectResult(e))
364
+ return new Response(null, {
365
+ status: e.status,
366
+ headers: { Location: e.location },
367
+ });
368
+ if (isErrorResult(e))
369
+ return (
370
+ (await renderErrorPage(
371
+ errorRoutes,
372
+ context.url.pathname,
373
+ e.status,
374
+ e.message,
375
+ e,
376
+ loadModule,
377
+ { layoutPairs, params: matched.params, nonceAttr, dev },
378
+ )) ?? new Response(e.message, { status: e.status, headers: TEXT })
379
+ );
380
+ throw e;
381
+ }
382
+ }
383
+
384
+ const layoutServer = matched.layoutServers.find(
385
+ (ls) => ls.path === levelPath,
386
+ );
387
+ let data: unknown;
388
+ if (layoutServer) {
389
+ try {
390
+ const mod = await loadModule(layoutServer.filePath);
391
+ data = await collectDeps(() => mod.load?.(context));
392
+ } catch (e) {
393
+ if (isRedirectResult(e))
394
+ return new Response(null, {
395
+ status: e.status,
396
+ headers: { Location: e.location },
397
+ });
398
+ if (isErrorResult(e))
399
+ return (
400
+ (await renderErrorPage(
401
+ errorRoutes,
402
+ context.url.pathname,
403
+ e.status,
404
+ e.message,
405
+ e,
406
+ loadModule,
407
+ { layoutPairs, params: matched.params, nonceAttr, dev },
408
+ )) ?? new Response(e.message, { status: e.status, headers: TEXT })
409
+ );
410
+ throw e;
411
+ }
412
+ }
413
+
414
+ const universalLayoutData = layoutMod.load
415
+ ? await collectDeps(() => layoutMod.load(context))
416
+ : undefined;
417
+
418
+ const mergedLayoutData =
419
+ universalLayoutData !== undefined
420
+ ? //@ts-expect-error user-provided data is always unknown
421
+ { ...universalLayoutData, ...data }
422
+ : data;
423
+
424
+ // only components wrap the page; the client indexes layoutData by them
425
+ if (layout)
426
+ layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
427
+ extractDeferred(mergedLayoutData, deferred, deferredCounter);
428
+ if (mergedLayoutData && typeof mergedLayoutData === "object") {
429
+ Object.assign(parentData, mergedLayoutData);
430
+ }
431
+ }
432
+
433
+ // no page at this address: its layouts are loaded, the 404 goes in them
434
+ if (matched.notFound)
435
+ return (
436
+ (await renderErrorPage(
437
+ errorRoutes,
438
+ context.url.pathname,
439
+ 404,
440
+ "Not Found",
441
+ null,
442
+ loadModule,
443
+ { layoutPairs, params: matched.params, nonceAttr, dev },
444
+ )) ?? new Response("Not Found", { status: 404 })
445
+ );
446
+
447
+ // page loads see every layout's data merged
448
+ context.parent = async () => ({ ...parentData });
449
+
450
+ // ── page server load ────────────────────────────────────────────────────
451
+ let pageData: unknown;
452
+ if (matched.pageServer) {
453
+ try {
454
+ const mod = await loadModule(matched.pageServer.filePath);
455
+ pageData = await collectDeps(() => mod.load?.(context));
456
+ } catch (e) {
457
+ if (isRedirectResult(e))
458
+ return new Response(null, {
459
+ status: e.status,
460
+ headers: { Location: e.location },
461
+ });
462
+ if (isErrorResult(e))
463
+ return (
464
+ (await renderErrorPage(
465
+ errorRoutes,
466
+ context.url.pathname,
467
+ e.status,
468
+ e.message,
469
+ e,
470
+ loadModule,
471
+ { layoutPairs, params: matched.params, nonceAttr, dev },
472
+ )) ?? new Response(e.message, { status: e.status, headers: TEXT })
473
+ );
474
+ throw e;
475
+ }
476
+ }
477
+
478
+ // ── page module ─────────────────────────────────────────────────────────
479
+ const pageMod = await loadModule(matched.route.filePath);
480
+
481
+ if (pageMod.canMatch) {
482
+ try {
483
+ const result = await pageMod.canMatch(context);
484
+ if (result === false) return new Response("Not Found", { status: 404 });
485
+ if (isRedirectResult(result))
486
+ return new Response(null, {
487
+ status: result.status,
488
+ headers: { Location: result.location },
489
+ });
490
+ } catch (e) {
491
+ if (isRedirectResult(e))
492
+ return new Response(null, {
493
+ status: e.status,
494
+ headers: { Location: e.location },
495
+ });
496
+ if (isErrorResult(e))
497
+ return (
498
+ (await renderErrorPage(
499
+ errorRoutes,
500
+ context.url.pathname,
501
+ e.status,
502
+ e.message,
503
+ e,
504
+ loadModule,
505
+ { layoutPairs, params: matched.params, nonceAttr, dev },
506
+ )) ?? new Response(e.message, { status: e.status, headers: TEXT })
507
+ );
508
+ throw e;
509
+ }
510
+ }
511
+
512
+ const isNavigate = req.headers.get(NAVIGATE_HEADER) === "1";
513
+ const hasLoading = typeof pageMod.loading === "function";
514
+
515
+ // helper: wrap page html in layout tree
516
+ function applyLayouts(pageHtml: string): string {
517
+ return applyLayoutTree(
518
+ pageHtml,
519
+ layoutPairs,
520
+ matched.params,
521
+ matched.route.path,
522
+ );
523
+ }
524
+
525
+ // ── two-pass streaming (loading export present) ─────────────────────────
526
+ if (hasLoading && !isNavigate) {
527
+ const uid = Math.random().toString(36).slice(2);
528
+ const csrfToken = csrfTokenFor(req);
529
+ const loadingHtml = String(pageMod.loading());
530
+ const loadingBody = injectCsrf(
531
+ applyLayouts(`<div id="ab-${uid}">${loadingHtml}</div>`),
532
+ csrfToken,
533
+ );
534
+ // layout stylesheets are in the loading shell — hoist before first flush
535
+ const hoistedCss = hoistStylesheets(loadingBody);
536
+ const shellStyles = scopedStyles(loadingBody, nonceAttr);
537
+
538
+ const stream = new ReadableStream({
539
+ async start(controller) {
540
+ // 1. skeleton + loading shell — browser paints immediately
541
+ controller.enqueue(
542
+ `${buildHtmlSkeleton(nonceAttr, dev)}${preloadLinks(matched.route.path, nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
543
+ </head>
544
+ <body>
545
+ <div id="app">${loadingBody}`,
546
+ );
547
+
548
+ // 2. run universal load while browser renders shell
549
+ const universalData = pageMod.load
550
+ ? await collectDeps(() => pageMod.load(context)).catch(
551
+ (e: unknown) => {
552
+ if (isRedirectResult(e)) throw e;
553
+ if (isErrorResult(e)) throw e;
554
+ throw e;
555
+ },
556
+ )
557
+ : undefined;
558
+
559
+ const mergedData =
560
+ universalData !== undefined
561
+ ? //@ts-expect-error user-provided data is always unknown
562
+ { ...universalData, ...pageData }
563
+ : pageData;
564
+ extractDeferred(mergedData, deferred, deferredCounter);
565
+
566
+ // 3. render real page + collect head
567
+ const pageHtml = injectCsrf(
568
+ String(
569
+ await Promise.resolve(
570
+ pageMod.default({
571
+ data: renderable(mergedData),
572
+ params: matched.params,
573
+ form: actionFailure?.data,
574
+ }),
575
+ ),
576
+ ),
577
+ csrfToken,
578
+ );
579
+ const headHtml = collectHead();
580
+ const stateJson = safeStateJson({
581
+ params: matched.params,
582
+ data: mergedData,
583
+ layoutData: layoutPairs.map((l) => l.data),
584
+ pattern: matched.route.path,
585
+ deps: [...collectedDeps],
586
+ form: actionFailure?.data,
587
+ });
588
+
589
+ // 4. inject late head tags
590
+ if (headHtml) {
591
+ controller.enqueue(
592
+ `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString(${JSON.stringify(`<head>${headHtml}</head>`).replace(/</g, "\\u003c")},"text/html");for(var e of Array.from(p.head.children)){var c=e.cloneNode(true);c.setAttribute("data-grimoire-head","1");document.head.appendChild(c)}})();</script>`,
593
+ );
594
+ }
595
+
596
+ // 5. swap shell with real content
597
+ controller.enqueue(
598
+ `<template id="ab-${uid}-r">${scopedStyles(String(pageHtml), nonceAttr)}${String(pageHtml)}</template>
599
+ <script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
600
+ <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
601
+ </div>
602
+ </body>
603
+ </html>`,
604
+ );
605
+
606
+ // 6. flush deferred values in order as they settle
607
+ for (const d of deferred) {
608
+ try {
609
+ const value = await d.promise;
610
+ controller.enqueue(deferredChunk(d.key, value, false));
611
+ } catch {
612
+ controller.enqueue(deferredChunk(d.key, null, true));
613
+ }
614
+ }
615
+
616
+ controller.close();
617
+ },
618
+ });
619
+
620
+ return new Response(stream, {
621
+ status: actionFailure?.status ?? 200,
622
+ headers: {
623
+ "Content-Type": "text/html",
624
+ "Set-Cookie": csrfCookie(csrfToken),
625
+ Vary: NAVIGATE_HEADER,
626
+ },
627
+ });
628
+ }
629
+
630
+ // ── single-pass (no loading export) ────────────────────────────────────
631
+ const universalData = pageMod.load
632
+ ? await collectDeps(() => pageMod.load(context)).catch((e) => {
633
+ if (isRedirectResult(e)) throw e;
634
+ if (isErrorResult(e)) throw e;
635
+ throw e;
636
+ })
637
+ : undefined;
638
+
639
+ const mergedData =
640
+ universalData !== undefined
641
+ ? //@ts-expect-error user-provided data is always unknown
642
+ { ...universalData, ...pageData }
643
+ : pageData;
644
+ extractDeferred(mergedData, deferred, deferredCounter);
645
+
646
+ timer.mark("load");
647
+ const pageHtml = await Promise.resolve(
648
+ pageMod.default({
649
+ data: renderable(mergedData),
650
+ params: matched.params,
651
+ form: actionFailure?.data,
652
+ }),
653
+ );
654
+
655
+ // layouts must render before collectHead(): a <Head> call inside a
656
+ // layout component (a common place for site-wide <title>/meta
657
+ // defaults) only registers once the layout itself has run, so
658
+ // collecting too early silently drops it
659
+ let bodyHtml = applyLayouts(String(pageHtml));
660
+ timer.mark("render");
661
+
662
+ const headHtml = collectHead();
663
+
664
+ if (isNavigate) {
665
+ // no stream to flush into — resolve everything before responding
666
+ for (const d of deferred) {
667
+ try {
668
+ (mergedData as Record<string, unknown>)[d.key] = await d.promise;
669
+ } catch {
670
+ (mergedData as Record<string, unknown>)[d.key] = null;
671
+ }
672
+ }
673
+ // Vary is mandatory here: this JSON and the HTML document share one
674
+ // URL and are chosen by a request header, so without it any cache may
675
+ // hand the JSON to a plain document request. That is what surfaced as
676
+ // raw state payloads rendering as the page after a back navigation.
677
+ // Deliberately still cacheable: hover-prefetch exists to warm this
678
+ // entry, and Vary already keeps document requests from matching it.
679
+ timer.mark("deferred");
680
+ return Response.json(
681
+ {
682
+ data: mergedData ?? {},
683
+ layoutData: layoutPairs.map((l) => l.data),
684
+ params: matched.params,
685
+ pattern: matched.route.path,
686
+ head: headHtml,
687
+ deps: [...collectedDeps],
688
+ },
689
+ { headers: { Vary: NAVIGATE_HEADER, ...timer.headers() } },
690
+ );
691
+ }
692
+
693
+ // ── single-pass SSR stream ──────────────────────────────────────────────
694
+ const csrfToken = csrfTokenFor(req);
695
+ const stateJson = safeStateJson({
696
+ params: matched.params,
697
+ data: mergedData,
698
+ layoutData: layoutPairs.map((l) => l.data),
699
+ pattern: matched.route.path,
700
+ deps: [...collectedDeps],
701
+ form: actionFailure?.data,
702
+ });
703
+
704
+ bodyHtml = optimizeImages(injectCsrf(bodyHtml, csrfToken));
705
+
706
+ const hoistedCss = hoistStylesheets(bodyHtml);
707
+ const styles = scopedStyles(bodyHtml, nonceAttr);
708
+
709
+ const stream = new ReadableStream({
710
+ async start(controller) {
711
+ controller.enqueue(
712
+ buildHtmlSkeleton(nonceAttr, dev) +
713
+ preloadLinks(matched.route.path, nonceAttr, dev),
714
+ );
715
+
716
+ if (hoistedCss) {
717
+ controller.enqueue(`\n ${hoistedCss}`);
718
+ }
719
+ if (styles) {
720
+ controller.enqueue(`\n ${styles}`);
721
+ }
722
+ controller.enqueue(`\n${headBlock(headHtml)}`);
723
+
724
+ controller.enqueue(`\n</head>
725
+ <body>
726
+ <div id="app">${bodyHtml}</div>
727
+ <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
728
+ </body>
729
+ </html>`);
730
+
731
+ // flush deferred values in order as they settle
732
+ for (const d of deferred) {
733
+ try {
734
+ const value = await d.promise;
735
+ controller.enqueue(deferredChunk(d.key, value, false));
736
+ } catch {
737
+ controller.enqueue(deferredChunk(d.key, null, true));
738
+ }
739
+ }
740
+
741
+ controller.close();
742
+ },
743
+ });
744
+
745
+ return new Response(stream, {
746
+ status: actionFailure?.status ?? 200,
747
+ headers: {
748
+ "Content-Type": "text/html",
749
+ "Set-Cookie": csrfCookie(csrfToken),
750
+ Vary: NAVIGATE_HEADER,
751
+ ...timer.headers(),
752
+ },
753
+ });
754
+ });
755
+ }