@sigil-dev/grimoire 0.9.3 → 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.
@@ -1,138 +1,146 @@
1
- import {
2
- claim,
3
- getHydrationNodes,
4
- insert,
5
- popHydrationNodes,
6
- pushHydrationNodes,
7
- } from "@sigil-dev/runtime";
8
- //@ts-expect-error compiler generated
9
- import { layouts, routes } from "#grimoire-routes";
10
- import {
11
- afterNavigate,
12
- beforeNavigate,
13
- navigate,
14
- onNavigate,
15
- } from "../client/router";
16
- import { initRouter } from "../client/router.ts";
17
- import { withEffectScope } from "../client/scope.ts";
18
- import { Head } from "./head";
19
-
20
- // expose for HMR module shim
21
- (globalThis as any).__grimoire_Head__ = Head;
22
- (globalThis as any).__grimoire_navigate__ = navigate;
23
- (globalThis as any).__grimoire_beforeNavigate__ = beforeNavigate;
24
- (globalThis as any).__grimoire_onNavigate__ = onNavigate;
25
- (globalThis as any).__grimoire_afterNavigate__ = afterNavigate;
26
-
27
- async function resolveInitialPage(pattern: string): Promise<any> {
28
- const entry = routes[pattern];
29
- if (!entry) return null;
30
- if (typeof entry === "function") return entry;
31
- return (await entry.__lazy()).default;
32
- }
33
-
34
- async function hydrate(): Promise<(() => void) | undefined> {
35
- const stateEl = document.getElementById("__grimoire_state__");
36
- if (!stateEl) return undefined;
37
-
38
- const state = JSON.parse(stateEl.textContent!);
39
- const Page = await resolveInitialPage(state.pattern);
40
- if (!Page) return undefined;
41
- const slot = document.getElementById("grimoire-root");
42
- if (!slot) return undefined;
43
-
44
- const matchedLayouts = layouts
45
- .filter(
46
- (l: any) =>
47
- l.path === "/" ||
48
- state.pattern === l.path ||
49
- state.pattern.startsWith(`${l.path}/`),
50
- )
51
- .sort((a: any, b: any) => a.path.length - b.path.length);
52
-
53
- // The page's SSR container is findable by id, so the page can hydrate
54
- // in place inside it while a single root layout claims from the
55
- // top-level pool. With nested layouts (>1) the inner layout's DOM
56
- // position can't be located in the flat pool — fall back to clearing
57
- // the SSR content and re-rendering in DOM mode (empty pool).
58
- const pageHost = document.getElementById("grimoire-page");
59
- const hasLayouts = matchedLayouts.length > 0;
60
- const inPlace = !hasLayouts || (matchedLayouts.length === 1 && !!pageHost);
61
- if (!inPlace) {
62
- slot.replaceChildren();
63
- }
64
-
65
- const ssrClones = inPlace
66
- ? Array.from(slot.childNodes).map((n) => n.cloneNode(true))
67
- : [];
68
- pushHydrationNodes(inPlace ? (Array.from(slot.childNodes) as ChildNode[]) : []);
69
- let initialDispose: (() => void) | undefined;
70
- try {
71
- initialDispose = withEffectScope(() => {
72
- try {
73
- let renderFn = () => {
74
- const pageDiv =
75
- hasLayouts && inPlace && pageHost
76
- ? pageHost
77
- : claim(getHydrationNodes(), "div");
78
- pageDiv.id = "grimoire-page";
79
-
80
- if (pageDiv.childNodes.length > 0) {
81
- pushHydrationNodes(Array.from(pageDiv.childNodes) as ChildNode[]);
82
- let pageNode: unknown;
83
- try {
84
- pageNode = Page({
85
- data: state.data,
86
- params: state.params,
87
- });
88
- } finally {
89
- // always rebalance the global hydration stack — a throwing
90
- // page component must not corrupt claims for the whole session
91
- popHydrationNodes();
92
- }
93
- insert(pageDiv, pageNode);
94
- } else {
95
- const pageNode = Page({
96
- data: state.data,
97
- params: state.params,
98
- });
99
- insert(pageDiv, pageNode);
100
- }
101
-
102
- return pageDiv;
103
- };
104
-
105
- for (let i = matchedLayouts.length - 1; i >= 0; i--) {
106
- const LayoutComponent = matchedLayouts[i].component;
107
- const innerRender = renderFn;
108
- const layoutData = state.layoutData?.[i];
109
- renderFn = () => {
110
- // Pre-render inner content so children is a Node (insert() doesn't call functions)
111
- const childNode = innerRender();
112
- return LayoutComponent({
113
- data: layoutData,
114
- params: state.params,
115
- children: childNode,
116
- });
117
- };
118
- }
119
-
120
- const rootNode = renderFn();
121
- insert(slot, rootNode);
122
- } finally {
123
- popHydrationNodes();
124
- }
125
- });
126
- } catch (e) {
127
- console.warn("[grimoire] hydration error:", e);
128
- }
129
-
130
- if (!slot.hasChildNodes() && ssrClones.length > 0) {
131
- slot.replaceChildren(...ssrClones);
132
- }
133
- return initialDispose;
134
- }
135
-
136
- hydrate().then((initialDispose) => {
137
- initRouter(routes, layouts, initialDispose);
138
- });
1
+ import {
2
+ claim,
3
+ getHydrationNodes,
4
+ insert,
5
+ popHydrationNodes,
6
+ pushHydrationNodes,
7
+ } from "@sigil-dev/runtime";
8
+ //@ts-expect-error compiler generated
9
+ import { layouts, matchers, routes } from "#grimoire-routes";
10
+ import {
11
+ afterNavigate,
12
+ beforeNavigate,
13
+ navigate,
14
+ onNavigate,
15
+ } from "../client/router";
16
+ import { initRouter } from "../client/router.ts";
17
+ import { withEffectScope } from "../client/scope.ts";
18
+ import { Head } from "./head";
19
+
20
+ // expose for HMR module shim
21
+ (globalThis as any).__grimoire_Head__ = Head;
22
+ (globalThis as any).__grimoire_navigate__ = navigate;
23
+ (globalThis as any).__grimoire_beforeNavigate__ = beforeNavigate;
24
+ (globalThis as any).__grimoire_onNavigate__ = onNavigate;
25
+ (globalThis as any).__grimoire_afterNavigate__ = afterNavigate;
26
+
27
+ async function resolveInitialPage(pattern: string): Promise<any> {
28
+ const entry = routes[pattern];
29
+ if (!entry) return null;
30
+ if (typeof entry === "function") return entry;
31
+ return (await entry.__lazy()).default;
32
+ }
33
+
34
+ async function hydrate(): Promise<(() => void) | undefined> {
35
+ const stateEl = document.getElementById("__grimoire_state__");
36
+ if (!stateEl) return undefined;
37
+
38
+ const state = JSON.parse(stateEl.textContent!);
39
+ const Page = await resolveInitialPage(state.pattern);
40
+ if (!Page) return undefined;
41
+ const slot = document.getElementById("grimoire-root");
42
+ if (!slot) return undefined;
43
+
44
+ const matchedLayouts = layouts
45
+ .filter(
46
+ (l: any) =>
47
+ l.path === "/" ||
48
+ state.pattern === l.path ||
49
+ state.pattern.startsWith(`${l.path}/`),
50
+ )
51
+ .sort((a: any, b: any) => a.path.length - b.path.length);
52
+
53
+ // The page's SSR container is findable by id, so the page can hydrate
54
+ // in place inside it while a single root layout claims from the
55
+ // top-level pool. With nested layouts (>1) the inner layout's DOM
56
+ // position can't be located in the flat pool — fall back to clearing
57
+ // the SSR content and re-rendering in DOM mode (empty pool).
58
+ const pageHost = document.getElementById("grimoire-page");
59
+ const hasLayouts = matchedLayouts.length > 0;
60
+ const inPlace = !hasLayouts || (matchedLayouts.length === 1 && !!pageHost);
61
+ if (!inPlace) {
62
+ slot.replaceChildren();
63
+ }
64
+
65
+ const ssrClones = inPlace
66
+ ? Array.from(slot.childNodes).map((n) => n.cloneNode(true))
67
+ : [];
68
+ pushHydrationNodes(inPlace ? (Array.from(slot.childNodes) as ChildNode[]) : []);
69
+ let initialDispose: (() => void) | undefined;
70
+ try {
71
+ initialDispose = withEffectScope(() => {
72
+ try {
73
+ let renderFn = () => {
74
+ const pageDiv =
75
+ hasLayouts && inPlace && pageHost
76
+ ? pageHost
77
+ : claim(getHydrationNodes(), "div");
78
+ pageDiv.id = "grimoire-page";
79
+
80
+ if (pageDiv.childNodes.length > 0) {
81
+ pushHydrationNodes(Array.from(pageDiv.childNodes) as ChildNode[]);
82
+ let pageNode: unknown;
83
+ try {
84
+ pageNode = Page({
85
+ data: state.data,
86
+ params: state.params,
87
+ });
88
+ } finally {
89
+ // always rebalance the global hydration stack — a throwing
90
+ // page component must not corrupt claims for the whole session
91
+ popHydrationNodes();
92
+ }
93
+ insert(pageDiv, pageNode);
94
+ } else {
95
+ const pageNode = Page({
96
+ data: state.data,
97
+ params: state.params,
98
+ });
99
+ insert(pageDiv, pageNode);
100
+ }
101
+
102
+ return pageDiv;
103
+ };
104
+
105
+ for (let i = matchedLayouts.length - 1; i >= 0; i--) {
106
+ const LayoutComponent = matchedLayouts[i].component;
107
+ const innerRender = renderFn;
108
+ const layoutData = state.layoutData?.[i];
109
+ renderFn = () => {
110
+ // Pre-render inner content so children is a Node (insert() doesn't call functions)
111
+ const childNode = innerRender();
112
+ return LayoutComponent({
113
+ data: layoutData,
114
+ params: state.params,
115
+ children: childNode,
116
+ });
117
+ };
118
+ }
119
+
120
+ const rootNode = renderFn();
121
+ insert(slot, rootNode);
122
+ } finally {
123
+ popHydrationNodes();
124
+ }
125
+ });
126
+ } catch (e) {
127
+ console.warn("[grimoire] hydration error:", e);
128
+ }
129
+
130
+ if (!slot.hasChildNodes() && ssrClones.length > 0) {
131
+ slot.replaceChildren(...ssrClones);
132
+ }
133
+ return initialDispose;
134
+ }
135
+
136
+ hydrate().then((initialDispose) => {
137
+ const stateEl = document.getElementById("__grimoire_state__");
138
+ const state = stateEl ? JSON.parse(stateEl.textContent!) : null;
139
+ initRouter(routes, layouts, initialDispose, {
140
+ matchers,
141
+ deps:
142
+ state && Array.isArray(state.deps)
143
+ ? { [state.pattern]: state.deps }
144
+ : undefined,
145
+ });
146
+ });
@@ -1,5 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { SafeHtml } from "@sigil-dev/runtime";
3
+ import { startCollecting, stopCollecting } from "../client/deps";
3
4
  import { findClosestError, type MatchedRoute } from "../routing/router";
4
5
  import type { RouteFile } from "../routing/scanner";
5
6
  import { isErrorResult } from "../sentinels/error.ts";
@@ -13,6 +14,60 @@ export type ModuleLoader = (path: string) => Promise<any>;
13
14
 
14
15
  type LayoutPair = { layout: RouteFile; mod: any; data: unknown };
15
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
+
16
71
  function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
17
72
  return `<!DOCTYPE html>
18
73
  <html>
@@ -135,11 +190,30 @@ export async function renderRoute(
135
190
  url: new URL(req.url),
136
191
  locals,
137
192
  fetch: patchedFetch ?? globalThis.fetch,
193
+ // no layouts have loaded yet — parent() is empty until the loop runs
194
+ parent: async () => ({}),
138
195
  };
139
196
 
140
197
  initHead(cspNonce);
141
198
  const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
142
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
+
143
217
  const route: Route = {
144
218
  path: matched.route.path,
145
219
  params: matched.params,
@@ -149,9 +223,10 @@ export async function renderRoute(
149
223
  };
150
224
  await runHook(plugins, "onRouteLoad", route, context);
151
225
 
152
- // ── layout loading ──────────────────────────────────────────────────────
153
- const layoutPairs: { layout: RouteFile; mod: any; data: unknown }[] = [];
154
226
  for (const layout of matched.layouts) {
227
+ // loads in this layout see everything accumulated so far
228
+ context.parent = async () => ({ ...parentData });
229
+
155
230
  const layoutMod = await loadModule(layout.filePath);
156
231
 
157
232
  if (layoutMod.canMatch) {
@@ -193,7 +268,7 @@ export async function renderRoute(
193
268
  if (layoutServer) {
194
269
  try {
195
270
  const mod = await loadModule(layoutServer.filePath);
196
- data = await mod.load?.(context);
271
+ data = await collectDeps(() => mod.load?.(context));
197
272
  } catch (e) {
198
273
  if (isRedirectResult(e))
199
274
  return new Response(null, {
@@ -217,7 +292,7 @@ export async function renderRoute(
217
292
  }
218
293
 
219
294
  const universalLayoutData = layoutMod.load
220
- ? await layoutMod.load(context)
295
+ ? await collectDeps(() => layoutMod.load(context))
221
296
  : undefined;
222
297
 
223
298
  const mergedLayoutData =
@@ -227,14 +302,21 @@ export async function renderRoute(
227
302
  : data;
228
303
 
229
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
+ }
230
309
  }
231
310
 
311
+ // page loads see every layout's data merged
312
+ context.parent = async () => ({ ...parentData });
313
+
232
314
  // ── page server load ────────────────────────────────────────────────────
233
315
  let pageData: unknown;
234
316
  if (matched.pageServer) {
235
317
  try {
236
318
  const mod = await loadModule(matched.pageServer.filePath);
237
- pageData = await mod.load?.(context);
319
+ pageData = await collectDeps(() => mod.load?.(context));
238
320
  } catch (e) {
239
321
  if (isRedirectResult(e))
240
322
  return new Response(null, {
@@ -321,11 +403,13 @@ export async function renderRoute(
321
403
 
322
404
  // 2. run universal load while browser renders shell
323
405
  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
- })
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
+ )
329
413
  : undefined;
330
414
 
331
415
  const mergedData =
@@ -333,17 +417,19 @@ export async function renderRoute(
333
417
  ? //@ts-expect-error user-provided data is always unknown
334
418
  { ...universalData, ...pageData }
335
419
  : pageData;
420
+ extractDeferred(mergedData, deferred, deferredCounter);
336
421
 
337
422
  // 3. render real page + collect head
338
423
  const pageHtml = await Promise.resolve(
339
424
  pageMod.default({ data: mergedData, params: matched.params }),
340
425
  );
341
426
  const headHtml = collectHead();
342
- const stateJson = JSON.stringify({
427
+ const stateJson = safeStateJson({
343
428
  params: matched.params,
344
429
  data: mergedData,
345
430
  layoutData: layoutPairs.map((l) => l.data),
346
431
  pattern: matched.route.path,
432
+ deps: [...collectedDeps],
347
433
  });
348
434
 
349
435
  // 4. inject late head tags
@@ -363,6 +449,18 @@ export async function renderRoute(
363
449
  </html>`,
364
450
  );
365
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
+
366
464
  controller.close();
367
465
  },
368
466
  });
@@ -374,7 +472,7 @@ export async function renderRoute(
374
472
 
375
473
  // ── single-pass (no loading export) ────────────────────────────────────
376
474
  const universalData = pageMod.load
377
- ? await pageMod.load(context).catch((e) => {
475
+ ? await collectDeps(() => pageMod.load(context)).catch((e) => {
378
476
  if (isRedirectResult(e)) throw e;
379
477
  if (isErrorResult(e)) throw e;
380
478
  throw e;
@@ -386,6 +484,7 @@ export async function renderRoute(
386
484
  ? //@ts-expect-error user-provided data is always unknown
387
485
  { ...universalData, ...pageData }
388
486
  : pageData;
487
+ extractDeferred(mergedData, deferred, deferredCounter);
389
488
 
390
489
  const pageHtml = await Promise.resolve(
391
490
  pageMod.default({ data: mergedData, params: matched.params }),
@@ -393,24 +492,33 @@ export async function renderRoute(
393
492
 
394
493
  const headHtml = collectHead();
395
494
 
396
- // ── navigation request — client handles rendering ───────────────────────
397
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
+ }
398
504
  return Response.json({
399
505
  data: mergedData ?? {},
400
506
  layoutData: layoutPairs.map((l) => l.data),
401
507
  params: matched.params,
402
508
  pattern: matched.route.path,
403
509
  head: headHtml,
510
+ deps: [...collectedDeps],
404
511
  });
405
512
  }
406
513
 
407
514
  // ── single-pass SSR stream ──────────────────────────────────────────────
408
515
  const csrfToken = randomBytes(32).toString("hex");
409
- const stateJson = JSON.stringify({
516
+ const stateJson = safeStateJson({
410
517
  params: matched.params,
411
518
  data: mergedData,
412
519
  layoutData: layoutPairs.map((l) => l.data),
413
520
  pattern: matched.route.path,
521
+ deps: [...collectedDeps],
414
522
  });
415
523
 
416
524
  let bodyHtml = applyLayouts(String(pageHtml));
@@ -424,7 +532,7 @@ export async function renderRoute(
424
532
  const hoistedCss = hoistStylesheets(bodyHtml);
425
533
 
426
534
  const stream = new ReadableStream({
427
- start(controller) {
535
+ async start(controller) {
428
536
  controller.enqueue(buildHtmlSkeleton(nonceAttr, dev));
429
537
 
430
538
  if (hoistedCss) {
@@ -441,6 +549,16 @@ export async function renderRoute(
441
549
  </body>
442
550
  </html>`);
443
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
+
444
562
  controller.close();
445
563
  },
446
564
  });
@@ -1,43 +1,55 @@
1
- import type { RouteFile } from "./scanner";
2
-
3
- /**
4
- * Generates a manifest module that exposes page routes keyed by route path.
5
- * Emits plain JS so the same output is valid as both `.ts` and `.js`.
6
- *
7
- * Pages are emitted as lazy entries (`{ __lazy: () => import(...) }`) so a
8
- * route module — including its module-level $state/$effect code — only
9
- * executes when that route is actually visited. Layouts stay eager: they are
10
- * needed for every render.
11
- *
12
- * If `fileMap` is provided, original `filePath`s are remapped to compiled
13
- * `.js` paths (used after pre-transforming routes to plain JS).
14
- */
15
- export function generateManifest(
16
- routes: RouteFile[],
17
- fileMap?: Map<string, string>,
18
- ): string {
19
- const pages = routes.filter((r) => r.type === "page" || r.type === "simple");
20
- const layouts = routes.filter((r) => r.type === "layout");
21
-
22
- const layoutImports = layouts
23
- .map((r, i) => {
24
- const path = fileMap?.get(r.filePath) ?? r.filePath;
25
- return `import __Layout${i} from ${JSON.stringify(path)};`;
26
- })
27
- .join("\n");
28
-
29
- const map = pages
30
- .map((r) => {
31
- const path = fileMap?.get(r.filePath) ?? r.filePath;
32
- return ` ${JSON.stringify(r.path)}: { __lazy: () => import(${JSON.stringify(path)}) },`;
33
- })
34
- .join("\n");
35
- const layoutMap = layouts
36
- .map(
37
- (r, i) =>
38
- ` { path: ${JSON.stringify(r.path)}, component: __Layout${i}, load: __Layout${i}.load },`,
39
- )
40
- .join("\n");
41
-
42
- return `${layoutImports}\nexport const routes = {\n${map}\n};\nexport const layouts = [\n${layoutMap}\n];\n`;
43
- }
1
+ import type { RouteFile } from "./scanner";
2
+
3
+ /**
4
+ * Generates a manifest module that exposes page routes keyed by route path.
5
+ * Emits plain JS so the same output is valid as both `.ts` and `.js`.
6
+ *
7
+ * Pages are emitted as lazy entries (`{ __lazy: () => import(...) }`) so a
8
+ * route module — including its module-level $state/$effect code — only
9
+ * executes when that route is actually visited. Layouts stay eager: they are
10
+ * needed for every render.
11
+ *
12
+ * If `fileMap` is provided, original `filePath`s are remapped to compiled
13
+ * `.js` paths (used after pre-transforming routes to plain JS).
14
+ */
15
+ export function generateManifest(
16
+ routes: RouteFile[],
17
+ fileMap?: Map<string, string>,
18
+ paramMatcherFiles: { name: string; filePath: string }[] = [],
19
+ ): string {
20
+ const pages = routes.filter((r) => r.type === "page" || r.type === "simple");
21
+ const layouts = routes.filter((r) => r.type === "layout");
22
+
23
+ const layoutImports = layouts
24
+ .map((r, i) => {
25
+ const path = fileMap?.get(r.filePath) ?? r.filePath;
26
+ return `import __Layout${i} from ${JSON.stringify(path)};`;
27
+ })
28
+ .join("\n");
29
+
30
+ // param matchers are eager: the client router validates on every match
31
+ const matcherImports = paramMatcherFiles
32
+ .map(
33
+ (pm) =>
34
+ `import * as __param_${pm.name} from ${JSON.stringify(pm.filePath)};`,
35
+ )
36
+ .join("\n");
37
+ const matcherRecord = `export const matchers = {\n${paramMatcherFiles
38
+ .map((pm) => ` ${JSON.stringify(pm.name)}: __param_${pm.name}.match,`)
39
+ .join("\n")}\n};`;
40
+
41
+ const map = pages
42
+ .map((r) => {
43
+ const path = fileMap?.get(r.filePath) ?? r.filePath;
44
+ return ` ${JSON.stringify(r.path)}: { __lazy: () => import(${JSON.stringify(path)}) },`;
45
+ })
46
+ .join("\n");
47
+ const layoutMap = layouts
48
+ .map(
49
+ (r, i) =>
50
+ ` { path: ${JSON.stringify(r.path)}, component: __Layout${i}, load: __Layout${i}.load },`,
51
+ )
52
+ .join("\n");
53
+
54
+ return `${layoutImports}\n${matcherImports}\nexport const routes = {\n${map}\n};\nexport const layouts = [\n${layoutMap}\n];\n${matcherRecord}\n`;
55
+ }