@sigil-dev/grimoire 0.9.6 → 0.9.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,599 +1,599 @@
1
- import { randomBytes } from "node:crypto";
2
- import { SafeHtml } from "@sigil-dev/runtime";
3
- import { startCollecting, stopCollecting } from "../client/deps";
4
- import { findClosestError, type MatchedRoute } from "../routing/router";
5
- import type { RouteFile } from "../routing/scanner";
6
- import { isErrorResult } from "../sentinels/error.ts";
7
- import { isRedirectResult } from "../sentinels/redirect.ts";
8
- import { runWithContext } from "../server/context";
9
- import { runHook } from "../server/plugins";
10
- import type { GrimoirePlugin, LoadContext, Route } from "../types";
11
- import { collectHead, initHead } from "./head";
12
-
13
- export type ModuleLoader = (path: string) => Promise<any>;
14
-
15
- type LayoutPair = { layout: RouteFile; mod: any; data: unknown };
16
-
17
- /** Placeholder for a top-level server-load promise still in flight. SSR text
18
- * interpolation renders it as an empty string via the normal String(v) path. */
19
- class DeferredMarker {
20
- constructor(
21
- public uid: string,
22
- public key: string,
23
- ) {}
24
- toString() {
25
- return "";
26
- }
27
- }
28
-
29
- type DeferredEntry = { promise: Promise<unknown>; key: string; uid: string };
30
-
31
- /**
32
- * Request header the client router sets to ask for the JSON navigate payload
33
- * instead of an HTML document. Both representations live at the same URL, so
34
- * every response that depends on it MUST also send it in `Vary`.
35
- */
36
- export const NAVIGATE_HEADER = "x-grimoire-navigate";
37
-
38
- /**
39
- * Serialize the hydration state payload for embedding inside a
40
- * `<script type="application/json">` tag. Escapes every `<` so a data value
41
- * like `"</script><script>alert(1)</script>"` cannot close the state script
42
- * early and inject markup. JSON.parse reads `\u003c` back as `<`.
43
- * DeferredMarkers serialize to `{ __deferred: uid }`.
44
- */
45
- const safeStateJson = (value: unknown): string =>
46
- JSON.stringify(value, (_k, v) =>
47
- v instanceof DeferredMarker ? { __deferred: v.uid } : v,
48
- ).replace(/</g, "\\u003c");
49
-
50
- /** Replace every own top-level promise property with a marker and record the
51
- * promise for late flush. Nested promises are awaited by the load itself. */
52
- function extractDeferred(
53
- data: unknown,
54
- deferred: DeferredEntry[],
55
- counter: { n: number },
56
- ): void {
57
- if (!data || typeof data !== "object" || Array.isArray(data)) return;
58
- const record = data as Record<string, unknown>;
59
- for (const key of Object.keys(record)) {
60
- const value = record[key];
61
- if (value instanceof Promise) {
62
- const uid = `gd-${counter.n++}`;
63
- record[key] = new DeferredMarker(uid, key);
64
- deferred.push({ promise: value, key, uid });
65
- }
66
- }
67
- }
68
-
69
- /** Template + patch script for one settled deferred value. */
70
- function deferredChunk(key: string, value: unknown, error: boolean): string {
71
- const keyJson = JSON.stringify(key);
72
- // The value rides inline (safeStateJson escapes `<`, so the script cannot
73
- // be broken out of). No DOM lookups: trailing chunks arrive after </html>,
74
- // where element timing is unreliable across parsers.
75
- 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>`;
76
- }
77
-
78
- function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
79
- return `<!DOCTYPE html>
80
- <html>
81
- <head>
82
- <meta charset="UTF-8" />
83
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
84
- <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
85
- ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
86
- }
87
-
88
- /**
89
- * Copy `<link rel="stylesheet">` tags found in rendered body HTML so they can
90
- * be emitted in <head>, where they are render-blocking. Components declare
91
- * stylesheets inline in JSX (usually in a layout), which lands them in the
92
- * body — the browser paints the unstyled document before body CSS applies,
93
- * causing a white flash on every full-document load. The body originals are
94
- * left in place so hydration can still claim them; the head copy shares the
95
- * same URL, so the browser only fetches once.
96
- */
97
- function hoistStylesheets(bodyHtml: string): string {
98
- const links = new Set<string>();
99
- for (const m of bodyHtml.matchAll(
100
- /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi,
101
- )) {
102
- links.add(m[0]);
103
- }
104
- return [...links].join("\n ");
105
- }
106
-
107
- /** Wrap page/error HTML in whatever parent layouts loaded successfully. */
108
- function applyLayoutTree(
109
- innerHtml: string,
110
- layoutPairs: LayoutPair[],
111
- params: Record<string, string>,
112
- pattern?: string,
113
- innerId = "grimoire-page",
114
- ): string {
115
- let bodyHtml = `<div id="${innerId}">${innerHtml}</div>`;
116
- for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
117
- bodyHtml = String(
118
- layoutMod.default({
119
- data,
120
- children: new SafeHtml(bodyHtml),
121
- params,
122
- path: pattern,
123
- }),
124
- );
125
- }
126
- return `<div id="grimoire-root">${bodyHtml}</div>`;
127
- }
128
-
129
- /**
130
- * Render a +error.tsx page as a full HTML document (doctype, hydration
131
- * script, and any parent layouts that had already loaded successfully),
132
- * instead of a bare fragment. No __grimoire_state__ script is emitted —
133
- * error pages aren't part of the client route table, so hydrate.js
134
- * simply skips client hydration for them (SSR-only, which is correct
135
- * since there's no client-side error route to hydrate against).
136
- */
137
- export async function renderErrorPage(
138
- errorRoutes: RouteFile[],
139
- pathname: string,
140
- status: number,
141
- message: string,
142
- error: unknown,
143
- loadModule: ModuleLoader,
144
- opts: {
145
- layoutPairs?: LayoutPair[];
146
- params?: Record<string, string>;
147
- nonceAttr?: string;
148
- dev?: boolean;
149
- } = {},
150
- ): Promise<Response | null> {
151
- const errorPage = findClosestError(errorRoutes, pathname);
152
- if (!errorPage) return null;
153
- const mod = await loadModule(errorPage.filePath);
154
-
155
- const { layoutPairs = [], params = {}, nonceAttr = "", dev } = opts;
156
-
157
- // own context so <Head> used by the error page (or wrapping layouts)
158
- // is collected fresh, independent of whatever the failed page pushed
159
- return runWithContext(async () => {
160
- const nonce = nonceAttr.match(/nonce="([^"]+)"/)?.[1];
161
- initHead(nonce);
162
-
163
- const errorHtml = String(
164
- mod.default({ status, message, error, route: pathname }),
165
- );
166
- const bodyHtml = applyLayoutTree(errorHtml, layoutPairs, params);
167
- const headHtml = collectHead();
168
- const hoistedCss = hoistStylesheets(bodyHtml);
169
-
170
- const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${headHtml ? `\n${headHtml}` : ""}
171
- </head>
172
- <body>
173
- <div id="app">${bodyHtml}</div>
174
- </body>
175
- </html>`;
176
-
177
- return new Response(html, {
178
- status,
179
- headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
180
- });
181
- });
182
- }
183
-
184
- export async function renderRoute(
185
- matched: MatchedRoute,
186
- req: Request,
187
- errorRoutes: RouteFile[] = [],
188
- loadModule: ModuleLoader = (path) => import(path),
189
- locals: Record<string, any> = {},
190
- plugins: GrimoirePlugin[] = [],
191
- cspNonce?: string,
192
- dev?: boolean,
193
- patchedFetch?: typeof fetch,
194
- ): Promise<Response> {
195
- return runWithContext(async () => {
196
- const context: LoadContext = {
197
- request: req,
198
- params: matched.params,
199
- url: new URL(req.url),
200
- locals,
201
- fetch: patchedFetch ?? globalThis.fetch,
202
- // no layouts have loaded yet — parent() is empty until the loop runs
203
- parent: async () => ({}),
204
- };
205
-
206
- initHead(cspNonce);
207
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
208
-
209
- // ── layout loading ──────────────────────────────────────────────────────
210
- const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
211
- const parentData: Record<string, unknown> = {};
212
- // depends() keys gathered across every server-executed load
213
- const collectedDeps = new Set<string>();
214
- // top-level load promises flushed late (deferred streaming)
215
- const deferred: DeferredEntry[] = [];
216
- const deferredCounter = { n: 0 };
217
- const collectDeps = async (run: () => unknown): Promise<unknown> => {
218
- startCollecting();
219
- try {
220
- return await run();
221
- } finally {
222
- for (const key of stopCollecting()) collectedDeps.add(key);
223
- }
224
- };
225
-
226
- const route: Route = {
227
- path: matched.route.path,
228
- params: matched.params,
229
- filePath: matched.route.filePath,
230
- loadPath: matched.pageServer?.filePath,
231
- layoutPath: matched.layouts.at(-1)?.filePath,
232
- };
233
- await runHook(plugins, "onRouteLoad", route, context);
234
-
235
- for (const layout of matched.layouts) {
236
- // loads in this layout see everything accumulated so far
237
- context.parent = async () => ({ ...parentData });
238
-
239
- const layoutMod = await loadModule(layout.filePath);
240
-
241
- if (layoutMod.canMatch) {
242
- try {
243
- const result = await layoutMod.canMatch(context);
244
- if (result === false)
245
- return new Response("Not Found", { status: 404 });
246
- if (isRedirectResult(result))
247
- return new Response(null, {
248
- status: result.status,
249
- headers: { Location: result.location },
250
- });
251
- } catch (e) {
252
- if (isRedirectResult(e))
253
- return new Response(null, {
254
- status: e.status,
255
- headers: { Location: e.location },
256
- });
257
- if (isErrorResult(e))
258
- return (
259
- (await renderErrorPage(
260
- errorRoutes,
261
- context.url.pathname,
262
- e.status,
263
- e.message,
264
- e,
265
- loadModule,
266
- { layoutPairs, params: matched.params, nonceAttr, dev },
267
- )) ?? new Response(e.message, { status: e.status })
268
- );
269
- throw e;
270
- }
271
- }
272
-
273
- const layoutServer = matched.layoutServers.find(
274
- (ls) => ls.path === layout.path,
275
- );
276
- let data: unknown;
277
- if (layoutServer) {
278
- try {
279
- const mod = await loadModule(layoutServer.filePath);
280
- data = await collectDeps(() => mod.load?.(context));
281
- } catch (e) {
282
- if (isRedirectResult(e))
283
- return new Response(null, {
284
- status: e.status,
285
- headers: { Location: e.location },
286
- });
287
- if (isErrorResult(e))
288
- return (
289
- (await renderErrorPage(
290
- errorRoutes,
291
- context.url.pathname,
292
- e.status,
293
- e.message,
294
- e,
295
- loadModule,
296
- { layoutPairs, params: matched.params, nonceAttr, dev },
297
- )) ?? new Response(e.message, { status: e.status })
298
- );
299
- throw e;
300
- }
301
- }
302
-
303
- const universalLayoutData = layoutMod.load
304
- ? await collectDeps(() => layoutMod.load(context))
305
- : undefined;
306
-
307
- const mergedLayoutData =
308
- universalLayoutData !== undefined
309
- ? //@ts-expect-error user-provided data is always unknown
310
- { ...universalLayoutData, ...data }
311
- : data;
312
-
313
- layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
314
- extractDeferred(mergedLayoutData, deferred, deferredCounter);
315
- if (mergedLayoutData && typeof mergedLayoutData === "object") {
316
- Object.assign(parentData, mergedLayoutData);
317
- }
318
- }
319
-
320
- // page loads see every layout's data merged
321
- context.parent = async () => ({ ...parentData });
322
-
323
- // ── page server load ────────────────────────────────────────────────────
324
- let pageData: unknown;
325
- if (matched.pageServer) {
326
- try {
327
- const mod = await loadModule(matched.pageServer.filePath);
328
- pageData = await collectDeps(() => mod.load?.(context));
329
- } catch (e) {
330
- if (isRedirectResult(e))
331
- return new Response(null, {
332
- status: e.status,
333
- headers: { Location: e.location },
334
- });
335
- if (isErrorResult(e))
336
- return (
337
- (await renderErrorPage(
338
- errorRoutes,
339
- context.url.pathname,
340
- e.status,
341
- e.message,
342
- e,
343
- loadModule,
344
- { layoutPairs, params: matched.params, nonceAttr, dev },
345
- )) ?? new Response(e.message, { status: e.status })
346
- );
347
- throw e;
348
- }
349
- }
350
-
351
- // ── page module ─────────────────────────────────────────────────────────
352
- const pageMod = await loadModule(matched.route.filePath);
353
-
354
- if (pageMod.canMatch) {
355
- try {
356
- const result = await pageMod.canMatch(context);
357
- if (result === false) return new Response("Not Found", { status: 404 });
358
- if (isRedirectResult(result))
359
- return new Response(null, {
360
- status: result.status,
361
- headers: { Location: result.location },
362
- });
363
- } catch (e) {
364
- if (isRedirectResult(e))
365
- return new Response(null, {
366
- status: e.status,
367
- headers: { Location: e.location },
368
- });
369
- if (isErrorResult(e))
370
- return (
371
- (await renderErrorPage(
372
- errorRoutes,
373
- context.url.pathname,
374
- e.status,
375
- e.message,
376
- e,
377
- loadModule,
378
- { layoutPairs, params: matched.params, nonceAttr, dev },
379
- )) ?? new Response(e.message, { status: e.status })
380
- );
381
- throw e;
382
- }
383
- }
384
-
385
- const isNavigate = req.headers.get(NAVIGATE_HEADER) === "1";
386
- const hasLoading = typeof pageMod.loading === "function";
387
-
388
- // helper: wrap page html in layout tree
389
- function applyLayouts(pageHtml: string): string {
390
- return applyLayoutTree(
391
- pageHtml,
392
- layoutPairs,
393
- matched.params,
394
- matched.route.path,
395
- );
396
- }
397
-
398
- // ── two-pass streaming (loading export present) ─────────────────────────
399
- if (hasLoading && !isNavigate) {
400
- const uid = Math.random().toString(36).slice(2);
401
- const loadingHtml = String(pageMod.loading());
402
- const loadingBody = applyLayouts(
403
- `<div id="ab-${uid}">${loadingHtml}</div>`,
404
- );
405
- // layout stylesheets are in the loading shell — hoist before first flush
406
- const hoistedCss = hoistStylesheets(loadingBody);
407
-
408
- const stream = new ReadableStream({
409
- async start(controller) {
410
- // 1. skeleton + loading shell — browser paints immediately
411
- controller.enqueue(
412
- `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}
413
- </head>
414
- <body>
415
- <div id="app">${loadingBody}`,
416
- );
417
-
418
- // 2. run universal load while browser renders shell
419
- const universalData = pageMod.load
420
- ? await collectDeps(() => pageMod.load(context)).catch(
421
- (e: unknown) => {
422
- if (isRedirectResult(e)) throw e;
423
- if (isErrorResult(e)) throw e;
424
- throw e;
425
- },
426
- )
427
- : undefined;
428
-
429
- const mergedData =
430
- universalData !== undefined
431
- ? //@ts-expect-error user-provided data is always unknown
432
- { ...universalData, ...pageData }
433
- : pageData;
434
- extractDeferred(mergedData, deferred, deferredCounter);
435
-
436
- // 3. render real page + collect head
437
- const pageHtml = await Promise.resolve(
438
- pageMod.default({ data: mergedData, params: matched.params }),
439
- );
440
- const headHtml = collectHead();
441
- const stateJson = safeStateJson({
442
- params: matched.params,
443
- data: mergedData,
444
- layoutData: layoutPairs.map((l) => l.data),
445
- pattern: matched.route.path,
446
- deps: [...collectedDeps],
447
- });
448
-
449
- // 4. inject late head tags
450
- if (headHtml) {
451
- controller.enqueue(
452
- `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString('<head>${headHtml.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}</head>','text/html');for(var e of Array.from(p.head.children))document.head.appendChild(e.cloneNode(true))})();</script>`,
453
- );
454
- }
455
-
456
- // 5. swap shell with real content
457
- controller.enqueue(
458
- `<template id="ab-${uid}-r">${String(pageHtml)}</template>
459
- <script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
460
- <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
461
- </div>
462
- </body>
463
- </html>`,
464
- );
465
-
466
- // 6. flush deferred values in order as they settle
467
- for (const d of deferred) {
468
- try {
469
- const value = await d.promise;
470
- controller.enqueue(deferredChunk(d.key, value, false));
471
- } catch {
472
- controller.enqueue(deferredChunk(d.key, null, true));
473
- }
474
- }
475
-
476
- controller.close();
477
- },
478
- });
479
-
480
- return new Response(stream, {
481
- headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
482
- });
483
- }
484
-
485
- // ── single-pass (no loading export) ────────────────────────────────────
486
- const universalData = pageMod.load
487
- ? await collectDeps(() => pageMod.load(context)).catch((e) => {
488
- if (isRedirectResult(e)) throw e;
489
- if (isErrorResult(e)) throw e;
490
- throw e;
491
- })
492
- : undefined;
493
-
494
- const mergedData =
495
- universalData !== undefined
496
- ? //@ts-expect-error user-provided data is always unknown
497
- { ...universalData, ...pageData }
498
- : pageData;
499
- extractDeferred(mergedData, deferred, deferredCounter);
500
-
501
- const pageHtml = await Promise.resolve(
502
- pageMod.default({ data: mergedData, params: matched.params }),
503
- );
504
-
505
- // layouts must render before collectHead(): a <Head> call inside a
506
- // layout component (a common place for site-wide <title>/meta
507
- // defaults) only registers once the layout itself has run, so
508
- // collecting too early silently drops it
509
- let bodyHtml = applyLayouts(String(pageHtml));
510
-
511
- const headHtml = collectHead();
512
-
513
- if (isNavigate) {
514
- // no stream to flush into — resolve everything before responding
515
- for (const d of deferred) {
516
- try {
517
- (mergedData as Record<string, unknown>)[d.key] = await d.promise;
518
- } catch {
519
- (mergedData as Record<string, unknown>)[d.key] = null;
520
- }
521
- }
522
- // Vary is mandatory here: this JSON and the HTML document share one
523
- // URL and are chosen by a request header, so without it any cache may
524
- // hand the JSON to a plain document request. That is what surfaced as
525
- // raw state payloads rendering as the page after a back navigation.
526
- // Deliberately still cacheable: hover-prefetch exists to warm this
527
- // entry, and Vary already keeps document requests from matching it.
528
- return Response.json(
529
- {
530
- data: mergedData ?? {},
531
- layoutData: layoutPairs.map((l) => l.data),
532
- params: matched.params,
533
- pattern: matched.route.path,
534
- head: headHtml,
535
- deps: [...collectedDeps],
536
- },
537
- { headers: { Vary: NAVIGATE_HEADER } },
538
- );
539
- }
540
-
541
- // ── single-pass SSR stream ──────────────────────────────────────────────
542
- const csrfToken = randomBytes(32).toString("hex");
543
- const stateJson = safeStateJson({
544
- params: matched.params,
545
- data: mergedData,
546
- layoutData: layoutPairs.map((l) => l.data),
547
- pattern: matched.route.path,
548
- deps: [...collectedDeps],
549
- });
550
-
551
- const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}">`;
552
- bodyHtml = bodyHtml.replace(
553
- /<form([^>]*action=[^>]*)>/gi,
554
- `<form$1>${csrfInput}`,
555
- );
556
-
557
- const hoistedCss = hoistStylesheets(bodyHtml);
558
-
559
- const stream = new ReadableStream({
560
- async start(controller) {
561
- controller.enqueue(buildHtmlSkeleton(nonceAttr, dev));
562
-
563
- if (hoistedCss) {
564
- controller.enqueue(`\n ${hoistedCss}`);
565
- }
566
- if (headHtml) {
567
- controller.enqueue(`\n${headHtml}`);
568
- }
569
-
570
- controller.enqueue(`\n</head>
571
- <body>
572
- <div id="app">${bodyHtml}</div>
573
- <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
574
- </body>
575
- </html>`);
576
-
577
- // flush deferred values in order as they settle
578
- for (const d of deferred) {
579
- try {
580
- const value = await d.promise;
581
- controller.enqueue(deferredChunk(d.key, value, false));
582
- } catch {
583
- controller.enqueue(deferredChunk(d.key, null, true));
584
- }
585
- }
586
-
587
- controller.close();
588
- },
589
- });
590
-
591
- return new Response(stream, {
592
- headers: {
593
- "Content-Type": "text/html",
594
- "Set-Cookie": `_csrf=${csrfToken}; SameSite=Strict; Path=/`,
595
- Vary: NAVIGATE_HEADER,
596
- },
597
- });
598
- });
599
- }
1
+ import { randomBytes } from "node:crypto";
2
+ import { SafeHtml } from "@sigil-dev/runtime";
3
+ import { startCollecting, stopCollecting } from "../client/deps";
4
+ import { findClosestError, type MatchedRoute } from "../routing/router";
5
+ import type { RouteFile } from "../routing/scanner";
6
+ import { isErrorResult } from "../sentinels/error.ts";
7
+ import { isRedirectResult } from "../sentinels/redirect.ts";
8
+ import { runWithContext } from "../server/context";
9
+ import { runHook } from "../server/plugins";
10
+ import type { GrimoirePlugin, LoadContext, Route } from "../types";
11
+ import { collectHead, initHead } from "./head";
12
+
13
+ export type ModuleLoader = (path: string) => Promise<any>;
14
+
15
+ type LayoutPair = { layout: RouteFile; mod: any; data: unknown };
16
+
17
+ /** Placeholder for a top-level server-load promise still in flight. SSR text
18
+ * interpolation renders it as an empty string via the normal String(v) path. */
19
+ class DeferredMarker {
20
+ constructor(
21
+ public uid: string,
22
+ public key: string,
23
+ ) {}
24
+ toString() {
25
+ return "";
26
+ }
27
+ }
28
+
29
+ type DeferredEntry = { promise: Promise<unknown>; key: string; uid: string };
30
+
31
+ /**
32
+ * Request header the client router sets to ask for the JSON navigate payload
33
+ * instead of an HTML document. Both representations live at the same URL, so
34
+ * every response that depends on it MUST also send it in `Vary`.
35
+ */
36
+ export const NAVIGATE_HEADER = "x-grimoire-navigate";
37
+
38
+ /**
39
+ * Serialize the hydration state payload for embedding inside a
40
+ * `<script type="application/json">` tag. Escapes every `<` so a data value
41
+ * like `"</script><script>alert(1)</script>"` cannot close the state script
42
+ * early and inject markup. JSON.parse reads `\u003c` back as `<`.
43
+ * DeferredMarkers serialize to `{ __deferred: uid }`.
44
+ */
45
+ const safeStateJson = (value: unknown): string =>
46
+ JSON.stringify(value, (_k, v) =>
47
+ v instanceof DeferredMarker ? { __deferred: v.uid } : v,
48
+ ).replace(/</g, "\\u003c");
49
+
50
+ /** Replace every own top-level promise property with a marker and record the
51
+ * promise for late flush. Nested promises are awaited by the load itself. */
52
+ function extractDeferred(
53
+ data: unknown,
54
+ deferred: DeferredEntry[],
55
+ counter: { n: number },
56
+ ): void {
57
+ if (!data || typeof data !== "object" || Array.isArray(data)) return;
58
+ const record = data as Record<string, unknown>;
59
+ for (const key of Object.keys(record)) {
60
+ const value = record[key];
61
+ if (value instanceof Promise) {
62
+ const uid = `gd-${counter.n++}`;
63
+ record[key] = new DeferredMarker(uid, key);
64
+ deferred.push({ promise: value, key, uid });
65
+ }
66
+ }
67
+ }
68
+
69
+ /** Template + patch script for one settled deferred value. */
70
+ function deferredChunk(key: string, value: unknown, error: boolean): string {
71
+ const keyJson = JSON.stringify(key);
72
+ // The value rides inline (safeStateJson escapes `<`, so the script cannot
73
+ // be broken out of). No DOM lookups: trailing chunks arrive after </html>,
74
+ // where element timing is unreliable across parsers.
75
+ 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>`;
76
+ }
77
+
78
+ function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
79
+ return `<!DOCTYPE html>
80
+ <html>
81
+ <head>
82
+ <meta charset="UTF-8" />
83
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
84
+ <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
85
+ ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
86
+ }
87
+
88
+ /**
89
+ * Copy `<link rel="stylesheet">` tags found in rendered body HTML so they can
90
+ * be emitted in <head>, where they are render-blocking. Components declare
91
+ * stylesheets inline in JSX (usually in a layout), which lands them in the
92
+ * body — the browser paints the unstyled document before body CSS applies,
93
+ * causing a white flash on every full-document load. The body originals are
94
+ * left in place so hydration can still claim them; the head copy shares the
95
+ * same URL, so the browser only fetches once.
96
+ */
97
+ function hoistStylesheets(bodyHtml: string): string {
98
+ const links = new Set<string>();
99
+ for (const m of bodyHtml.matchAll(
100
+ /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi,
101
+ )) {
102
+ links.add(m[0]);
103
+ }
104
+ return [...links].join("\n ");
105
+ }
106
+
107
+ /** Wrap page/error HTML in whatever parent layouts loaded successfully. */
108
+ function applyLayoutTree(
109
+ innerHtml: string,
110
+ layoutPairs: LayoutPair[],
111
+ params: Record<string, string>,
112
+ pattern?: string,
113
+ innerId = "grimoire-page",
114
+ ): string {
115
+ let bodyHtml = `<div id="${innerId}">${innerHtml}</div>`;
116
+ for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
117
+ bodyHtml = String(
118
+ layoutMod.default({
119
+ data,
120
+ children: new SafeHtml(bodyHtml),
121
+ params,
122
+ path: pattern,
123
+ }),
124
+ );
125
+ }
126
+ return `<div id="grimoire-root">${bodyHtml}</div>`;
127
+ }
128
+
129
+ /**
130
+ * Render a +error.tsx page as a full HTML document (doctype, hydration
131
+ * script, and any parent layouts that had already loaded successfully),
132
+ * instead of a bare fragment. No __grimoire_state__ script is emitted —
133
+ * error pages aren't part of the client route table, so hydrate.js
134
+ * simply skips client hydration for them (SSR-only, which is correct
135
+ * since there's no client-side error route to hydrate against).
136
+ */
137
+ export async function renderErrorPage(
138
+ errorRoutes: RouteFile[],
139
+ pathname: string,
140
+ status: number,
141
+ message: string,
142
+ error: unknown,
143
+ loadModule: ModuleLoader,
144
+ opts: {
145
+ layoutPairs?: LayoutPair[];
146
+ params?: Record<string, string>;
147
+ nonceAttr?: string;
148
+ dev?: boolean;
149
+ } = {},
150
+ ): Promise<Response | null> {
151
+ const errorPage = findClosestError(errorRoutes, pathname);
152
+ if (!errorPage) return null;
153
+ const mod = await loadModule(errorPage.filePath);
154
+
155
+ const { layoutPairs = [], params = {}, nonceAttr = "", dev } = opts;
156
+
157
+ // own context so <Head> used by the error page (or wrapping layouts)
158
+ // is collected fresh, independent of whatever the failed page pushed
159
+ return runWithContext(async () => {
160
+ const nonce = nonceAttr.match(/nonce="([^"]+)"/)?.[1];
161
+ initHead(nonce);
162
+
163
+ const errorHtml = String(
164
+ mod.default({ status, message, error, route: pathname }),
165
+ );
166
+ const bodyHtml = applyLayoutTree(errorHtml, layoutPairs, params);
167
+ const headHtml = collectHead();
168
+ const hoistedCss = hoistStylesheets(bodyHtml);
169
+
170
+ const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${headHtml ? `\n${headHtml}` : ""}
171
+ </head>
172
+ <body>
173
+ <div id="app">${bodyHtml}</div>
174
+ </body>
175
+ </html>`;
176
+
177
+ return new Response(html, {
178
+ status,
179
+ headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
180
+ });
181
+ });
182
+ }
183
+
184
+ export async function renderRoute(
185
+ matched: MatchedRoute,
186
+ req: Request,
187
+ errorRoutes: RouteFile[] = [],
188
+ loadModule: ModuleLoader = (path) => import(path),
189
+ locals: Record<string, any> = {},
190
+ plugins: GrimoirePlugin[] = [],
191
+ cspNonce?: string,
192
+ dev?: boolean,
193
+ patchedFetch?: typeof fetch,
194
+ ): Promise<Response> {
195
+ return runWithContext(async () => {
196
+ const context: LoadContext = {
197
+ request: req,
198
+ params: matched.params,
199
+ url: new URL(req.url),
200
+ locals,
201
+ fetch: patchedFetch ?? globalThis.fetch,
202
+ // no layouts have loaded yet — parent() is empty until the loop runs
203
+ parent: async () => ({}),
204
+ };
205
+
206
+ initHead(cspNonce);
207
+ const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
208
+
209
+ // ── layout loading ──────────────────────────────────────────────────────
210
+ const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
211
+ const parentData: Record<string, unknown> = {};
212
+ // depends() keys gathered across every server-executed load
213
+ const collectedDeps = new Set<string>();
214
+ // top-level load promises flushed late (deferred streaming)
215
+ const deferred: DeferredEntry[] = [];
216
+ const deferredCounter = { n: 0 };
217
+ const collectDeps = async (run: () => unknown): Promise<unknown> => {
218
+ startCollecting();
219
+ try {
220
+ return await run();
221
+ } finally {
222
+ for (const key of stopCollecting()) collectedDeps.add(key);
223
+ }
224
+ };
225
+
226
+ const route: Route = {
227
+ path: matched.route.path,
228
+ params: matched.params,
229
+ filePath: matched.route.filePath,
230
+ loadPath: matched.pageServer?.filePath,
231
+ layoutPath: matched.layouts.at(-1)?.filePath,
232
+ };
233
+ await runHook(plugins, "onRouteLoad", route, context);
234
+
235
+ for (const layout of matched.layouts) {
236
+ // loads in this layout see everything accumulated so far
237
+ context.parent = async () => ({ ...parentData });
238
+
239
+ const layoutMod = await loadModule(layout.filePath);
240
+
241
+ if (layoutMod.canMatch) {
242
+ try {
243
+ const result = await layoutMod.canMatch(context);
244
+ if (result === false)
245
+ return new Response("Not Found", { status: 404 });
246
+ if (isRedirectResult(result))
247
+ return new Response(null, {
248
+ status: result.status,
249
+ headers: { Location: result.location },
250
+ });
251
+ } catch (e) {
252
+ if (isRedirectResult(e))
253
+ return new Response(null, {
254
+ status: e.status,
255
+ headers: { Location: e.location },
256
+ });
257
+ if (isErrorResult(e))
258
+ return (
259
+ (await renderErrorPage(
260
+ errorRoutes,
261
+ context.url.pathname,
262
+ e.status,
263
+ e.message,
264
+ e,
265
+ loadModule,
266
+ { layoutPairs, params: matched.params, nonceAttr, dev },
267
+ )) ?? new Response(e.message, { status: e.status })
268
+ );
269
+ throw e;
270
+ }
271
+ }
272
+
273
+ const layoutServer = matched.layoutServers.find(
274
+ (ls) => ls.path === layout.path,
275
+ );
276
+ let data: unknown;
277
+ if (layoutServer) {
278
+ try {
279
+ const mod = await loadModule(layoutServer.filePath);
280
+ data = await collectDeps(() => mod.load?.(context));
281
+ } catch (e) {
282
+ if (isRedirectResult(e))
283
+ return new Response(null, {
284
+ status: e.status,
285
+ headers: { Location: e.location },
286
+ });
287
+ if (isErrorResult(e))
288
+ return (
289
+ (await renderErrorPage(
290
+ errorRoutes,
291
+ context.url.pathname,
292
+ e.status,
293
+ e.message,
294
+ e,
295
+ loadModule,
296
+ { layoutPairs, params: matched.params, nonceAttr, dev },
297
+ )) ?? new Response(e.message, { status: e.status })
298
+ );
299
+ throw e;
300
+ }
301
+ }
302
+
303
+ const universalLayoutData = layoutMod.load
304
+ ? await collectDeps(() => layoutMod.load(context))
305
+ : undefined;
306
+
307
+ const mergedLayoutData =
308
+ universalLayoutData !== undefined
309
+ ? //@ts-expect-error user-provided data is always unknown
310
+ { ...universalLayoutData, ...data }
311
+ : data;
312
+
313
+ layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
314
+ extractDeferred(mergedLayoutData, deferred, deferredCounter);
315
+ if (mergedLayoutData && typeof mergedLayoutData === "object") {
316
+ Object.assign(parentData, mergedLayoutData);
317
+ }
318
+ }
319
+
320
+ // page loads see every layout's data merged
321
+ context.parent = async () => ({ ...parentData });
322
+
323
+ // ── page server load ────────────────────────────────────────────────────
324
+ let pageData: unknown;
325
+ if (matched.pageServer) {
326
+ try {
327
+ const mod = await loadModule(matched.pageServer.filePath);
328
+ pageData = await collectDeps(() => mod.load?.(context));
329
+ } catch (e) {
330
+ if (isRedirectResult(e))
331
+ return new Response(null, {
332
+ status: e.status,
333
+ headers: { Location: e.location },
334
+ });
335
+ if (isErrorResult(e))
336
+ return (
337
+ (await renderErrorPage(
338
+ errorRoutes,
339
+ context.url.pathname,
340
+ e.status,
341
+ e.message,
342
+ e,
343
+ loadModule,
344
+ { layoutPairs, params: matched.params, nonceAttr, dev },
345
+ )) ?? new Response(e.message, { status: e.status })
346
+ );
347
+ throw e;
348
+ }
349
+ }
350
+
351
+ // ── page module ─────────────────────────────────────────────────────────
352
+ const pageMod = await loadModule(matched.route.filePath);
353
+
354
+ if (pageMod.canMatch) {
355
+ try {
356
+ const result = await pageMod.canMatch(context);
357
+ if (result === false) return new Response("Not Found", { status: 404 });
358
+ if (isRedirectResult(result))
359
+ return new Response(null, {
360
+ status: result.status,
361
+ headers: { Location: result.location },
362
+ });
363
+ } catch (e) {
364
+ if (isRedirectResult(e))
365
+ return new Response(null, {
366
+ status: e.status,
367
+ headers: { Location: e.location },
368
+ });
369
+ if (isErrorResult(e))
370
+ return (
371
+ (await renderErrorPage(
372
+ errorRoutes,
373
+ context.url.pathname,
374
+ e.status,
375
+ e.message,
376
+ e,
377
+ loadModule,
378
+ { layoutPairs, params: matched.params, nonceAttr, dev },
379
+ )) ?? new Response(e.message, { status: e.status })
380
+ );
381
+ throw e;
382
+ }
383
+ }
384
+
385
+ const isNavigate = req.headers.get(NAVIGATE_HEADER) === "1";
386
+ const hasLoading = typeof pageMod.loading === "function";
387
+
388
+ // helper: wrap page html in layout tree
389
+ function applyLayouts(pageHtml: string): string {
390
+ return applyLayoutTree(
391
+ pageHtml,
392
+ layoutPairs,
393
+ matched.params,
394
+ matched.route.path,
395
+ );
396
+ }
397
+
398
+ // ── two-pass streaming (loading export present) ─────────────────────────
399
+ if (hasLoading && !isNavigate) {
400
+ const uid = Math.random().toString(36).slice(2);
401
+ const loadingHtml = String(pageMod.loading());
402
+ const loadingBody = applyLayouts(
403
+ `<div id="ab-${uid}">${loadingHtml}</div>`,
404
+ );
405
+ // layout stylesheets are in the loading shell — hoist before first flush
406
+ const hoistedCss = hoistStylesheets(loadingBody);
407
+
408
+ const stream = new ReadableStream({
409
+ async start(controller) {
410
+ // 1. skeleton + loading shell — browser paints immediately
411
+ controller.enqueue(
412
+ `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}
413
+ </head>
414
+ <body>
415
+ <div id="app">${loadingBody}`,
416
+ );
417
+
418
+ // 2. run universal load while browser renders shell
419
+ const universalData = pageMod.load
420
+ ? await collectDeps(() => pageMod.load(context)).catch(
421
+ (e: unknown) => {
422
+ if (isRedirectResult(e)) throw e;
423
+ if (isErrorResult(e)) throw e;
424
+ throw e;
425
+ },
426
+ )
427
+ : undefined;
428
+
429
+ const mergedData =
430
+ universalData !== undefined
431
+ ? //@ts-expect-error user-provided data is always unknown
432
+ { ...universalData, ...pageData }
433
+ : pageData;
434
+ extractDeferred(mergedData, deferred, deferredCounter);
435
+
436
+ // 3. render real page + collect head
437
+ const pageHtml = await Promise.resolve(
438
+ pageMod.default({ data: mergedData, params: matched.params }),
439
+ );
440
+ const headHtml = collectHead();
441
+ const stateJson = safeStateJson({
442
+ params: matched.params,
443
+ data: mergedData,
444
+ layoutData: layoutPairs.map((l) => l.data),
445
+ pattern: matched.route.path,
446
+ deps: [...collectedDeps],
447
+ });
448
+
449
+ // 4. inject late head tags
450
+ if (headHtml) {
451
+ controller.enqueue(
452
+ `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString('<head>${headHtml.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}</head>','text/html');for(var e of Array.from(p.head.children))document.head.appendChild(e.cloneNode(true))})();</script>`,
453
+ );
454
+ }
455
+
456
+ // 5. swap shell with real content
457
+ controller.enqueue(
458
+ `<template id="ab-${uid}-r">${String(pageHtml)}</template>
459
+ <script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
460
+ <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
461
+ </div>
462
+ </body>
463
+ </html>`,
464
+ );
465
+
466
+ // 6. flush deferred values in order as they settle
467
+ for (const d of deferred) {
468
+ try {
469
+ const value = await d.promise;
470
+ controller.enqueue(deferredChunk(d.key, value, false));
471
+ } catch {
472
+ controller.enqueue(deferredChunk(d.key, null, true));
473
+ }
474
+ }
475
+
476
+ controller.close();
477
+ },
478
+ });
479
+
480
+ return new Response(stream, {
481
+ headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
482
+ });
483
+ }
484
+
485
+ // ── single-pass (no loading export) ────────────────────────────────────
486
+ const universalData = pageMod.load
487
+ ? await collectDeps(() => pageMod.load(context)).catch((e) => {
488
+ if (isRedirectResult(e)) throw e;
489
+ if (isErrorResult(e)) throw e;
490
+ throw e;
491
+ })
492
+ : undefined;
493
+
494
+ const mergedData =
495
+ universalData !== undefined
496
+ ? //@ts-expect-error user-provided data is always unknown
497
+ { ...universalData, ...pageData }
498
+ : pageData;
499
+ extractDeferred(mergedData, deferred, deferredCounter);
500
+
501
+ const pageHtml = await Promise.resolve(
502
+ pageMod.default({ data: mergedData, params: matched.params }),
503
+ );
504
+
505
+ // layouts must render before collectHead(): a <Head> call inside a
506
+ // layout component (a common place for site-wide <title>/meta
507
+ // defaults) only registers once the layout itself has run, so
508
+ // collecting too early silently drops it
509
+ let bodyHtml = applyLayouts(String(pageHtml));
510
+
511
+ const headHtml = collectHead();
512
+
513
+ if (isNavigate) {
514
+ // no stream to flush into — resolve everything before responding
515
+ for (const d of deferred) {
516
+ try {
517
+ (mergedData as Record<string, unknown>)[d.key] = await d.promise;
518
+ } catch {
519
+ (mergedData as Record<string, unknown>)[d.key] = null;
520
+ }
521
+ }
522
+ // Vary is mandatory here: this JSON and the HTML document share one
523
+ // URL and are chosen by a request header, so without it any cache may
524
+ // hand the JSON to a plain document request. That is what surfaced as
525
+ // raw state payloads rendering as the page after a back navigation.
526
+ // Deliberately still cacheable: hover-prefetch exists to warm this
527
+ // entry, and Vary already keeps document requests from matching it.
528
+ return Response.json(
529
+ {
530
+ data: mergedData ?? {},
531
+ layoutData: layoutPairs.map((l) => l.data),
532
+ params: matched.params,
533
+ pattern: matched.route.path,
534
+ head: headHtml,
535
+ deps: [...collectedDeps],
536
+ },
537
+ { headers: { Vary: NAVIGATE_HEADER } },
538
+ );
539
+ }
540
+
541
+ // ── single-pass SSR stream ──────────────────────────────────────────────
542
+ const csrfToken = randomBytes(32).toString("hex");
543
+ const stateJson = safeStateJson({
544
+ params: matched.params,
545
+ data: mergedData,
546
+ layoutData: layoutPairs.map((l) => l.data),
547
+ pattern: matched.route.path,
548
+ deps: [...collectedDeps],
549
+ });
550
+
551
+ const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}" data-grimoire-csrf>`;
552
+ bodyHtml = bodyHtml.replace(
553
+ /<form([^>]*action=[^>]*)>/gi,
554
+ `<form$1>${csrfInput}`,
555
+ );
556
+
557
+ const hoistedCss = hoistStylesheets(bodyHtml);
558
+
559
+ const stream = new ReadableStream({
560
+ async start(controller) {
561
+ controller.enqueue(buildHtmlSkeleton(nonceAttr, dev));
562
+
563
+ if (hoistedCss) {
564
+ controller.enqueue(`\n ${hoistedCss}`);
565
+ }
566
+ if (headHtml) {
567
+ controller.enqueue(`\n${headHtml}`);
568
+ }
569
+
570
+ controller.enqueue(`\n</head>
571
+ <body>
572
+ <div id="app">${bodyHtml}</div>
573
+ <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
574
+ </body>
575
+ </html>`);
576
+
577
+ // flush deferred values in order as they settle
578
+ for (const d of deferred) {
579
+ try {
580
+ const value = await d.promise;
581
+ controller.enqueue(deferredChunk(d.key, value, false));
582
+ } catch {
583
+ controller.enqueue(deferredChunk(d.key, null, true));
584
+ }
585
+ }
586
+
587
+ controller.close();
588
+ },
589
+ });
590
+
591
+ return new Response(stream, {
592
+ headers: {
593
+ "Content-Type": "text/html",
594
+ "Set-Cookie": `_csrf=${csrfToken}; SameSite=Strict; Path=/`,
595
+ Vary: NAVIGATE_HEADER,
596
+ },
597
+ });
598
+ });
599
+ }