@sigil-dev/grimoire 0.9.2 → 0.9.3
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.
- package/index.ts +35 -35
- package/package.json +8 -8
- package/preload.js +3 -3
- package/server.ts +19 -19
- package/src/client/deps.ts +13 -7
- package/src/client/enhance.ts +98 -98
- package/src/client/head.ts +30 -30
- package/src/client/index.ts +2 -2
- package/src/client/router.ts +445 -371
- package/src/client/scope.ts +22 -22
- package/src/dev/compile-module.ts +163 -163
- package/src/dev/effect-registry.ts +23 -23
- package/src/dev/graph.ts +114 -114
- package/src/dev/hmr-client.ts +185 -185
- package/src/dev/loader.ts +47 -47
- package/src/dev/paths.ts +14 -14
- package/src/dev/runtime-bundle.ts +52 -52
- package/src/dev/watcher.ts +47 -46
- package/src/env/dynamic-private.ts +19 -19
- package/src/env/dynamic-public.ts +22 -22
- package/src/env/index.ts +25 -25
- package/src/env/plugin.ts +19 -19
- package/src/env/private.ts +5 -5
- package/src/env/public.ts +7 -7
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +114 -114
- package/src/integrations/vite.ts +73 -73
- package/src/logger/index.ts +4 -4
- package/src/logger/instance.ts +6 -6
- package/src/logger/logger.ts +113 -113
- package/src/logger/request-middleware.ts +24 -24
- package/src/logger/transports.ts +117 -117
- package/src/logger/types.ts +39 -39
- package/src/rendering/head.ts +47 -47
- package/src/rendering/hydrate.ts +98 -79
- package/src/rendering/index.ts +455 -372
- package/src/rendering/ssrPlugin.ts +69 -69
- package/src/routing/manifest-gen.ts +12 -11
- package/src/routing/router.ts +109 -109
- package/src/routing/scanner.ts +141 -141
- package/src/routing/transform-routes.ts +102 -102
- package/src/sentinels/error.ts +52 -52
- package/src/sentinels/fail.ts +41 -41
- package/src/sentinels/redirect.ts +35 -35
- package/src/server/build.ts +243 -219
- package/src/server/context.ts +10 -10
- package/src/server/cookie-utils.ts +66 -66
- package/src/server/coordinator.ts +364 -356
- package/src/server/hooks.ts +114 -114
- package/src/server/index.ts +655 -658
- package/src/server/interactive.ts +56 -56
- package/src/server/plugins.ts +121 -120
- package/src/server/worker.ts +58 -58
- package/src/typegen/index.ts +356 -356
- package/src/types.ts +4 -4
- package/test/client-router.test.ts +37 -31
- package/test/context.test.ts +52 -52
- package/test/env.test.ts +70 -70
- package/test/exports.test.ts +37 -37
- package/test/fail.test.ts +46 -46
- package/test/headers.test.ts +100 -100
- package/test/hydration.test.ts +119 -119
- package/test/middleware.test.ts +223 -223
- package/test/preload.ts +5 -5
- package/test/redirect-error.test.ts +112 -112
- package/test/rendering.test.ts +615 -579
- package/test/routing.test.ts +81 -81
- package/test/scanning.test.ts +200 -200
- package/test/scope.test.ts +195 -195
- package/test/server.test.ts +249 -249
- package/test/streaming.test.ts +125 -125
- package/test/transform-routes.test.ts +84 -84
- package/test/typegen.test.ts +682 -682
- package/tsconfig.json +10 -10
- package/.grimoire/_routes.dom.js +0 -8
- package/.grimoire/_routes.hydrate.js +0 -8
- package/.grimoire/tsconfig.generated.json +0 -11
- package/.grimoire/types/ambient.d.ts +0 -59
- package/.grimoire/types/api/hello/$types.d.ts +0 -50
- package/.grimoire/types/api/items/$types.d.ts +0 -50
- package/.grimoire/types/echo/$types.d.ts +0 -50
- package/.grimoire/types/env-private.d.ts +0 -5
- package/.grimoire/types/env-public.d.ts +0 -5
- package/.grimoire/types/mixed/$types.d.ts +0 -50
- package/.grimoire/types/params/[docId]/$types.d.ts +0 -52
- package/.grimoire/types/reject/$types.d.ts +0 -50
- package/public/__grimoire__/hydrate.js +0 -585
- package/public/__grimoire__/index.js +0 -490
package/src/rendering/index.ts
CHANGED
|
@@ -1,372 +1,455 @@
|
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
):
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
e,
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
//
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
</
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
}
|
|
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
|
+
type LayoutPair = { layout: RouteFile; mod: any; data: unknown };
|
|
15
|
+
|
|
16
|
+
function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
|
|
17
|
+
return `<!DOCTYPE html>
|
|
18
|
+
<html>
|
|
19
|
+
<head>
|
|
20
|
+
<meta charset="UTF-8" />
|
|
21
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
22
|
+
<script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
|
|
23
|
+
${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Copy `<link rel="stylesheet">` tags found in rendered body HTML so they can
|
|
28
|
+
* be emitted in <head>, where they are render-blocking. Components declare
|
|
29
|
+
* stylesheets inline in JSX (usually in a layout), which lands them in the
|
|
30
|
+
* body — the browser paints the unstyled document before body CSS applies,
|
|
31
|
+
* causing a white flash on every full-document load. The body originals are
|
|
32
|
+
* left in place so hydration can still claim them; the head copy shares the
|
|
33
|
+
* same URL, so the browser only fetches once.
|
|
34
|
+
*/
|
|
35
|
+
function hoistStylesheets(bodyHtml: string): string {
|
|
36
|
+
const links = new Set<string>();
|
|
37
|
+
for (const m of bodyHtml.matchAll(
|
|
38
|
+
/<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi,
|
|
39
|
+
)) {
|
|
40
|
+
links.add(m[0]);
|
|
41
|
+
}
|
|
42
|
+
return [...links].join("\n ");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Wrap page/error HTML in whatever parent layouts loaded successfully. */
|
|
46
|
+
function applyLayoutTree(
|
|
47
|
+
innerHtml: string,
|
|
48
|
+
layoutPairs: LayoutPair[],
|
|
49
|
+
params: Record<string, string>,
|
|
50
|
+
innerId = "grimoire-page",
|
|
51
|
+
): string {
|
|
52
|
+
let bodyHtml = `<div id="${innerId}">${innerHtml}</div>`;
|
|
53
|
+
for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
|
|
54
|
+
bodyHtml = String(
|
|
55
|
+
layoutMod.default({
|
|
56
|
+
data,
|
|
57
|
+
children: new SafeHtml(bodyHtml),
|
|
58
|
+
params,
|
|
59
|
+
}),
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return `<div id="grimoire-root">${bodyHtml}</div>`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Render a +error.tsx page as a full HTML document (doctype, hydration
|
|
67
|
+
* script, and any parent layouts that had already loaded successfully),
|
|
68
|
+
* instead of a bare fragment. No __grimoire_state__ script is emitted —
|
|
69
|
+
* error pages aren't part of the client route table, so hydrate.js
|
|
70
|
+
* simply skips client hydration for them (SSR-only, which is correct
|
|
71
|
+
* since there's no client-side error route to hydrate against).
|
|
72
|
+
*/
|
|
73
|
+
export async function renderErrorPage(
|
|
74
|
+
errorRoutes: RouteFile[],
|
|
75
|
+
pathname: string,
|
|
76
|
+
status: number,
|
|
77
|
+
message: string,
|
|
78
|
+
error: unknown,
|
|
79
|
+
loadModule: ModuleLoader,
|
|
80
|
+
opts: {
|
|
81
|
+
layoutPairs?: LayoutPair[];
|
|
82
|
+
params?: Record<string, string>;
|
|
83
|
+
nonceAttr?: string;
|
|
84
|
+
dev?: boolean;
|
|
85
|
+
} = {},
|
|
86
|
+
): Promise<Response | null> {
|
|
87
|
+
const errorPage = findClosestError(errorRoutes, pathname);
|
|
88
|
+
if (!errorPage) return null;
|
|
89
|
+
const mod = await loadModule(errorPage.filePath);
|
|
90
|
+
|
|
91
|
+
const { layoutPairs = [], params = {}, nonceAttr = "", dev } = opts;
|
|
92
|
+
|
|
93
|
+
// own context so <Head> used by the error page (or wrapping layouts)
|
|
94
|
+
// is collected fresh, independent of whatever the failed page pushed
|
|
95
|
+
return runWithContext(async () => {
|
|
96
|
+
const nonce = nonceAttr.match(/nonce="([^"]+)"/)?.[1];
|
|
97
|
+
initHead(nonce);
|
|
98
|
+
|
|
99
|
+
const errorHtml = String(
|
|
100
|
+
mod.default({ status, message, error, route: pathname }),
|
|
101
|
+
);
|
|
102
|
+
const bodyHtml = applyLayoutTree(errorHtml, layoutPairs, params);
|
|
103
|
+
const headHtml = collectHead();
|
|
104
|
+
const hoistedCss = hoistStylesheets(bodyHtml);
|
|
105
|
+
|
|
106
|
+
const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${headHtml ? `\n${headHtml}` : ""}
|
|
107
|
+
</head>
|
|
108
|
+
<body>
|
|
109
|
+
<div id="app">${bodyHtml}</div>
|
|
110
|
+
</body>
|
|
111
|
+
</html>`;
|
|
112
|
+
|
|
113
|
+
return new Response(html, {
|
|
114
|
+
status,
|
|
115
|
+
headers: { "Content-Type": "text/html" },
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export async function renderRoute(
|
|
121
|
+
matched: MatchedRoute,
|
|
122
|
+
req: Request,
|
|
123
|
+
errorRoutes: RouteFile[] = [],
|
|
124
|
+
loadModule: ModuleLoader = (path) => import(path),
|
|
125
|
+
locals: Record<string, any> = {},
|
|
126
|
+
plugins: GrimoirePlugin[] = [],
|
|
127
|
+
cspNonce?: string,
|
|
128
|
+
dev?: boolean,
|
|
129
|
+
patchedFetch?: typeof fetch,
|
|
130
|
+
): Promise<Response> {
|
|
131
|
+
return runWithContext(async () => {
|
|
132
|
+
const context: LoadContext = {
|
|
133
|
+
request: req,
|
|
134
|
+
params: matched.params,
|
|
135
|
+
url: new URL(req.url),
|
|
136
|
+
locals,
|
|
137
|
+
fetch: patchedFetch ?? globalThis.fetch,
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
initHead(cspNonce);
|
|
141
|
+
const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
|
|
142
|
+
|
|
143
|
+
const route: Route = {
|
|
144
|
+
path: matched.route.path,
|
|
145
|
+
params: matched.params,
|
|
146
|
+
filePath: matched.route.filePath,
|
|
147
|
+
loadPath: matched.pageServer?.filePath,
|
|
148
|
+
layoutPath: matched.layouts.at(-1)?.filePath,
|
|
149
|
+
};
|
|
150
|
+
await runHook(plugins, "onRouteLoad", route, context);
|
|
151
|
+
|
|
152
|
+
// ── layout loading ──────────────────────────────────────────────────────
|
|
153
|
+
const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
|
|
154
|
+
for (const layout of matched.layouts) {
|
|
155
|
+
const layoutMod = await loadModule(layout.filePath);
|
|
156
|
+
|
|
157
|
+
if (layoutMod.canMatch) {
|
|
158
|
+
try {
|
|
159
|
+
const result = await layoutMod.canMatch(context);
|
|
160
|
+
if (result === false)
|
|
161
|
+
return new Response("Not Found", { status: 404 });
|
|
162
|
+
if (isRedirectResult(result))
|
|
163
|
+
return new Response(null, {
|
|
164
|
+
status: result.status,
|
|
165
|
+
headers: { Location: result.location },
|
|
166
|
+
});
|
|
167
|
+
} catch (e) {
|
|
168
|
+
if (isRedirectResult(e))
|
|
169
|
+
return new Response(null, {
|
|
170
|
+
status: e.status,
|
|
171
|
+
headers: { Location: e.location },
|
|
172
|
+
});
|
|
173
|
+
if (isErrorResult(e))
|
|
174
|
+
return (
|
|
175
|
+
(await renderErrorPage(
|
|
176
|
+
errorRoutes,
|
|
177
|
+
context.url.pathname,
|
|
178
|
+
e.status,
|
|
179
|
+
e.message,
|
|
180
|
+
e,
|
|
181
|
+
loadModule,
|
|
182
|
+
{ layoutPairs, params: matched.params, nonceAttr, dev },
|
|
183
|
+
)) ?? new Response(e.message, { status: e.status })
|
|
184
|
+
);
|
|
185
|
+
throw e;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const layoutServer = matched.layoutServers.find(
|
|
190
|
+
(ls) => ls.path === layout.path,
|
|
191
|
+
);
|
|
192
|
+
let data: unknown;
|
|
193
|
+
if (layoutServer) {
|
|
194
|
+
try {
|
|
195
|
+
const mod = await loadModule(layoutServer.filePath);
|
|
196
|
+
data = await mod.load?.(context);
|
|
197
|
+
} catch (e) {
|
|
198
|
+
if (isRedirectResult(e))
|
|
199
|
+
return new Response(null, {
|
|
200
|
+
status: e.status,
|
|
201
|
+
headers: { Location: e.location },
|
|
202
|
+
});
|
|
203
|
+
if (isErrorResult(e))
|
|
204
|
+
return (
|
|
205
|
+
(await renderErrorPage(
|
|
206
|
+
errorRoutes,
|
|
207
|
+
context.url.pathname,
|
|
208
|
+
e.status,
|
|
209
|
+
e.message,
|
|
210
|
+
e,
|
|
211
|
+
loadModule,
|
|
212
|
+
{ layoutPairs, params: matched.params, nonceAttr, dev },
|
|
213
|
+
)) ?? new Response(e.message, { status: e.status })
|
|
214
|
+
);
|
|
215
|
+
throw e;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const universalLayoutData = layoutMod.load
|
|
220
|
+
? await layoutMod.load(context)
|
|
221
|
+
: undefined;
|
|
222
|
+
|
|
223
|
+
const mergedLayoutData =
|
|
224
|
+
universalLayoutData !== undefined
|
|
225
|
+
? //@ts-expect-error user-provided data is always unknown
|
|
226
|
+
{ ...universalLayoutData, ...data }
|
|
227
|
+
: data;
|
|
228
|
+
|
|
229
|
+
layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ── page server load ────────────────────────────────────────────────────
|
|
233
|
+
let pageData: unknown;
|
|
234
|
+
if (matched.pageServer) {
|
|
235
|
+
try {
|
|
236
|
+
const mod = await loadModule(matched.pageServer.filePath);
|
|
237
|
+
pageData = await mod.load?.(context);
|
|
238
|
+
} catch (e) {
|
|
239
|
+
if (isRedirectResult(e))
|
|
240
|
+
return new Response(null, {
|
|
241
|
+
status: e.status,
|
|
242
|
+
headers: { Location: e.location },
|
|
243
|
+
});
|
|
244
|
+
if (isErrorResult(e))
|
|
245
|
+
return (
|
|
246
|
+
(await renderErrorPage(
|
|
247
|
+
errorRoutes,
|
|
248
|
+
context.url.pathname,
|
|
249
|
+
e.status,
|
|
250
|
+
e.message,
|
|
251
|
+
e,
|
|
252
|
+
loadModule,
|
|
253
|
+
{ layoutPairs, params: matched.params, nonceAttr, dev },
|
|
254
|
+
)) ?? new Response(e.message, { status: e.status })
|
|
255
|
+
);
|
|
256
|
+
throw e;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ── page module ─────────────────────────────────────────────────────────
|
|
261
|
+
const pageMod = await loadModule(matched.route.filePath);
|
|
262
|
+
|
|
263
|
+
if (pageMod.canMatch) {
|
|
264
|
+
try {
|
|
265
|
+
const result = await pageMod.canMatch(context);
|
|
266
|
+
if (result === false) return new Response("Not Found", { status: 404 });
|
|
267
|
+
if (isRedirectResult(result))
|
|
268
|
+
return new Response(null, {
|
|
269
|
+
status: result.status,
|
|
270
|
+
headers: { Location: result.location },
|
|
271
|
+
});
|
|
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 isNavigate = req.headers.get("x-grimoire-navigate") === "1";
|
|
295
|
+
const hasLoading = typeof pageMod.loading === "function";
|
|
296
|
+
|
|
297
|
+
// helper: wrap page html in layout tree
|
|
298
|
+
function applyLayouts(pageHtml: string): string {
|
|
299
|
+
return applyLayoutTree(pageHtml, layoutPairs, matched.params);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ── two-pass streaming (loading export present) ─────────────────────────
|
|
303
|
+
if (hasLoading && !isNavigate) {
|
|
304
|
+
const uid = Math.random().toString(36).slice(2);
|
|
305
|
+
const loadingHtml = String(pageMod.loading());
|
|
306
|
+
const loadingBody = applyLayouts(
|
|
307
|
+
`<div id="ab-${uid}">${loadingHtml}</div>`,
|
|
308
|
+
);
|
|
309
|
+
// layout stylesheets are in the loading shell — hoist before first flush
|
|
310
|
+
const hoistedCss = hoistStylesheets(loadingBody);
|
|
311
|
+
|
|
312
|
+
const stream = new ReadableStream({
|
|
313
|
+
async start(controller) {
|
|
314
|
+
// 1. skeleton + loading shell — browser paints immediately
|
|
315
|
+
controller.enqueue(
|
|
316
|
+
`${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}
|
|
317
|
+
</head>
|
|
318
|
+
<body>
|
|
319
|
+
<div id="app">${loadingBody}`,
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
// 2. run universal load while browser renders shell
|
|
323
|
+
const universalData = pageMod.load
|
|
324
|
+
? await pageMod.load(context).catch((e: unknown) => {
|
|
325
|
+
if (isRedirectResult(e)) throw e;
|
|
326
|
+
if (isErrorResult(e)) throw e;
|
|
327
|
+
throw e;
|
|
328
|
+
})
|
|
329
|
+
: undefined;
|
|
330
|
+
|
|
331
|
+
const mergedData =
|
|
332
|
+
universalData !== undefined
|
|
333
|
+
? //@ts-expect-error user-provided data is always unknown
|
|
334
|
+
{ ...universalData, ...pageData }
|
|
335
|
+
: pageData;
|
|
336
|
+
|
|
337
|
+
// 3. render real page + collect head
|
|
338
|
+
const pageHtml = await Promise.resolve(
|
|
339
|
+
pageMod.default({ data: mergedData, params: matched.params }),
|
|
340
|
+
);
|
|
341
|
+
const headHtml = collectHead();
|
|
342
|
+
const stateJson = JSON.stringify({
|
|
343
|
+
params: matched.params,
|
|
344
|
+
data: mergedData,
|
|
345
|
+
layoutData: layoutPairs.map((l) => l.data),
|
|
346
|
+
pattern: matched.route.path,
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
// 4. inject late head tags
|
|
350
|
+
if (headHtml) {
|
|
351
|
+
controller.enqueue(
|
|
352
|
+
`<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>`,
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// 5. swap shell with real content
|
|
357
|
+
controller.enqueue(
|
|
358
|
+
`<template id="ab-${uid}-r">${String(pageHtml)}</template>
|
|
359
|
+
<script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
|
|
360
|
+
<script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
|
|
361
|
+
</div>
|
|
362
|
+
</body>
|
|
363
|
+
</html>`,
|
|
364
|
+
);
|
|
365
|
+
|
|
366
|
+
controller.close();
|
|
367
|
+
},
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
return new Response(stream, {
|
|
371
|
+
headers: { "Content-Type": "text/html" },
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ── single-pass (no loading export) ────────────────────────────────────
|
|
376
|
+
const universalData = pageMod.load
|
|
377
|
+
? await pageMod.load(context).catch((e) => {
|
|
378
|
+
if (isRedirectResult(e)) throw e;
|
|
379
|
+
if (isErrorResult(e)) throw e;
|
|
380
|
+
throw e;
|
|
381
|
+
})
|
|
382
|
+
: undefined;
|
|
383
|
+
|
|
384
|
+
const mergedData =
|
|
385
|
+
universalData !== undefined
|
|
386
|
+
? //@ts-expect-error user-provided data is always unknown
|
|
387
|
+
{ ...universalData, ...pageData }
|
|
388
|
+
: pageData;
|
|
389
|
+
|
|
390
|
+
const pageHtml = await Promise.resolve(
|
|
391
|
+
pageMod.default({ data: mergedData, params: matched.params }),
|
|
392
|
+
);
|
|
393
|
+
|
|
394
|
+
const headHtml = collectHead();
|
|
395
|
+
|
|
396
|
+
// ── navigation request — client handles rendering ───────────────────────
|
|
397
|
+
if (isNavigate) {
|
|
398
|
+
return Response.json({
|
|
399
|
+
data: mergedData ?? {},
|
|
400
|
+
layoutData: layoutPairs.map((l) => l.data),
|
|
401
|
+
params: matched.params,
|
|
402
|
+
pattern: matched.route.path,
|
|
403
|
+
head: headHtml,
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// ── single-pass SSR stream ──────────────────────────────────────────────
|
|
408
|
+
const csrfToken = randomBytes(32).toString("hex");
|
|
409
|
+
const stateJson = JSON.stringify({
|
|
410
|
+
params: matched.params,
|
|
411
|
+
data: mergedData,
|
|
412
|
+
layoutData: layoutPairs.map((l) => l.data),
|
|
413
|
+
pattern: matched.route.path,
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
let bodyHtml = applyLayouts(String(pageHtml));
|
|
417
|
+
|
|
418
|
+
const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}">`;
|
|
419
|
+
bodyHtml = bodyHtml.replace(
|
|
420
|
+
/<form([^>]*action=[^>]*)>/gi,
|
|
421
|
+
`<form$1>${csrfInput}`,
|
|
422
|
+
);
|
|
423
|
+
|
|
424
|
+
const hoistedCss = hoistStylesheets(bodyHtml);
|
|
425
|
+
|
|
426
|
+
const stream = new ReadableStream({
|
|
427
|
+
start(controller) {
|
|
428
|
+
controller.enqueue(buildHtmlSkeleton(nonceAttr, dev));
|
|
429
|
+
|
|
430
|
+
if (hoistedCss) {
|
|
431
|
+
controller.enqueue(`\n ${hoistedCss}`);
|
|
432
|
+
}
|
|
433
|
+
if (headHtml) {
|
|
434
|
+
controller.enqueue(`\n${headHtml}`);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
controller.enqueue(`\n</head>
|
|
438
|
+
<body>
|
|
439
|
+
<div id="app">${bodyHtml}</div>
|
|
440
|
+
<script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
|
|
441
|
+
</body>
|
|
442
|
+
</html>`);
|
|
443
|
+
|
|
444
|
+
controller.close();
|
|
445
|
+
},
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
return new Response(stream, {
|
|
449
|
+
headers: {
|
|
450
|
+
"Content-Type": "text/html",
|
|
451
|
+
"Set-Cookie": `_csrf=${csrfToken}; SameSite=Strict; Path=/`,
|
|
452
|
+
},
|
|
453
|
+
});
|
|
454
|
+
});
|
|
455
|
+
}
|