@sigil-dev/grimoire 0.9.26 → 0.9.28

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