@sigil-dev/grimoire 0.9.2 → 0.9.4

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