@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.
Files changed (88) hide show
  1. package/index.ts +35 -35
  2. package/package.json +8 -8
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +13 -7
  6. package/src/client/enhance.ts +98 -98
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +2 -2
  9. package/src/client/router.ts +445 -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 +98 -79
  36. package/src/rendering/index.ts +455 -372
  37. package/src/rendering/ssrPlugin.ts +69 -69
  38. package/src/routing/manifest-gen.ts +12 -11
  39. package/src/routing/router.ts +109 -109
  40. package/src/routing/scanner.ts +141 -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 +243 -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 +655 -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 +356 -356
  55. package/src/types.ts +4 -4
  56. package/test/client-router.test.ts +37 -31
  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 +615 -579
  67. package/test/routing.test.ts +81 -81
  68. package/test/scanning.test.ts +200 -200
  69. package/test/scope.test.ts +195 -195
  70. package/test/server.test.ts +249 -249
  71. package/test/streaming.test.ts +125 -125
  72. package/test/transform-routes.test.ts +84 -84
  73. package/test/typegen.test.ts +682 -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,371 +1,445 @@
1
- import {popHydrationNodes, pushHydrationNodes} from "@sigil-dev/runtime";
2
- import {withEffectScope} from "./scope";
3
-
4
- // ── Dependency tracking ──────────────────────────────────────────────────────
5
- const routeDeps = new Map<string, Set<string>>(); // pattern → dep keys
6
- let _collectingDeps: Set<string> | null = null;
7
-
8
- /**
9
- * Call from inside a load() function to register a dependency key.
10
- * When invalidate(key) is called, any route that depends on that key
11
- * will refetch if it's the current route.
12
- */
13
- export function depends(key: string): void {
14
- _collectingDeps?.add(key);
15
- }
16
-
17
- async function refetchCurrent(): Promise<void> {
18
- if (!lastState) return;
19
- await navigate(location.pathname, true); // true = replace, no pushState
20
- }
21
-
22
- export async function invalidate(...keys: string[]): Promise<void> {
23
- const current = lastState?.pattern;
24
- if (!current) return;
25
- const deps = routeDeps.get(current);
26
- if (!deps) return;
27
- if (keys.some(k => deps.has(k))) await refetchCurrent();
28
- }
29
-
30
- export async function invalidateAll(): Promise<void> {
31
- await refetchCurrent();
32
- }
33
-
34
- let routeMap: Record<
35
- string,
36
- ((props: any) => any) & {
37
- load?: (ctx: any) => Promise<any>;
38
- loading?: () => any;
39
- error?: (props: { error: unknown }) => any;
40
- }
41
- > = {};
42
- let layoutList: { path: string; component: (props: any) => any }[] = [];
43
- let disposeCurrentPage: (() => void) | null = null;
44
- let currentPath = location.pathname;
45
-
46
- // C1: Navigation hooks
47
- let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
48
- let onNavigateCb: ((url: URL) => void) | null = null;
49
- let afterNavigateCb: ((url: URL) => void) | null = null;
50
-
51
- // // HMR
52
- // (globalThis as any).__grimoire_routes__ = routeMap;
53
- // (globalThis as any).__grimoire_current_pattern__ = currentPath;
54
- // (globalThis as any).__grimoire_navigate__ = navigate;
55
-
56
- export async function hmrRerender(): Promise<void> {
57
- if (!lastState) {
58
- location.reload();
59
- return;
60
- }
61
- disposeCurrentPage?.();
62
- pushHydrationNodes([]);
63
- let rootNode: any;
64
- disposeCurrentPage = withEffectScope(() => {
65
- rootNode = buildRouteTree(lastState!);
66
- });
67
- popHydrationNodes();
68
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
69
- }
70
-
71
- // (globalThis as any).__grimoire_rerender__ = hmrRerender;
72
-
73
- export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
74
- beforeNavigateCb = cb;
75
- }
76
-
77
- export function onNavigate(cb: (url: URL) => void): void {
78
- onNavigateCb = cb;
79
- }
80
-
81
- export function afterNavigate(cb: (url: URL) => void): void {
82
- afterNavigateCb = cb;
83
- }
84
-
85
- // C2: Scroll restoration
86
- const scrollPositions = new Map<string, number>();
87
-
88
- function saveScrollPosition(): void {
89
- scrollPositions.set(currentPath, window.scrollY);
90
- }
91
-
92
- function restoreScrollPosition(path: string): void {
93
- const saved = scrollPositions.get(path);
94
- if (saved !== undefined) {
95
- requestAnimationFrame(() => window.scrollTo(0, saved));
96
- } else {
97
- requestAnimationFrame(() => window.scrollTo(0, 0));
98
- }
99
- }
100
-
101
- // C3: Preloading
102
- let preloadTimer: Timer | null = null;
103
-
104
- function setupPreload(): void {
105
- document.addEventListener("mouseover", (e) => {
106
- const a = (e.target as Element).closest("a");
107
- if (!a) return;
108
- const href = a.getAttribute("href");
109
- if (!href) return;
110
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
111
-
112
- const preloadData = a.hasAttribute("data-sigil-preload-data");
113
- const preloadCode = a.hasAttribute("data-sigil-preload-code");
114
- if (!preloadData && !preloadCode) return;
115
-
116
- if (preloadTimer) clearTimeout(preloadTimer);
117
- preloadTimer = setTimeout(() => {
118
- if (preloadCode) {
119
- const link = document.createElement("link");
120
- link.rel = "prefetch";
121
- link.href = href;
122
- document.head.appendChild(link);
123
- }
124
- if (preloadData) {
125
- fetch(href, {
126
- headers: {"x-grimoire-navigate": "1"},
127
- priority: "low",
128
- }).catch(() => {
129
- });
130
- }
131
- }, 80);
132
- });
133
-
134
- document.addEventListener("mouseout", (e) => {
135
- const a = (e.target as Element).closest("a");
136
- if (!a) return;
137
- if (preloadTimer) clearTimeout(preloadTimer);
138
- });
139
- }
140
-
141
- let lastState: {
142
- data: any;
143
- layoutData: any[];
144
- params: any;
145
- pattern: string;
146
- } | null = null;
147
-
148
- function buildRouteTree(state: typeof lastState): any {
149
- const {data, layoutData, params, pattern} = state!;
150
- const Page = routeMap[pattern];
151
- if (!Page) throw new Error(`no component for pattern ${pattern}`);
152
-
153
- const matchedLayouts = layoutList
154
- .filter(
155
- (l) =>
156
- l.path === "/" ||
157
- pattern === l.path ||
158
- pattern.startsWith(`${l.path}/`),
159
- )
160
- .sort((a, b) => a.path.length - b.path.length);
161
-
162
- let renderFn = () => {
163
- const pageNode = Page({data, params});
164
- const pageDiv = document.createElement("div");
165
- pageDiv.id = "grimoire-page";
166
- pageDiv.appendChild(pageNode);
167
- return pageDiv;
168
- };
169
-
170
- for (let i = matchedLayouts.length - 1; i >= 0; i--) {
171
- const LayoutComponent = matchedLayouts[i].component;
172
- const innerRender = renderFn;
173
- const currentLayoutData = layoutData?.[i];
174
- renderFn = () => {
175
- const childNode = innerRender();
176
- return LayoutComponent({
177
- data: currentLayoutData,
178
- params,
179
- children: childNode,
180
- });
181
- };
182
- }
183
-
184
- return renderFn();
185
- }
186
-
187
- function matchClientPattern(pattern: string, pathname: string): boolean {
188
- // haha pp and ph
189
- const pp = pattern.split("/").filter(Boolean);
190
- const ph = pathname.split("/").filter(Boolean);
191
- let pi = 0, pj = 0;
192
- while (pi < pp.length) {
193
- if (pp[pi]!.startsWith("*")) return true;
194
- if (pj >= ph.length) return false;
195
- if (!pp[pi]!.startsWith(":") && pp[pi] !== ph[pj]) return false;
196
- pi++;
197
- pj++;
198
- }
199
- return pj === ph.length;
200
- }
201
-
202
- function findPattern(pathname: string): string | null {
203
- for (const pattern of Object.keys(routeMap)) {
204
- if (matchClientPattern(pattern, pathname)) return pattern;
205
- }
206
- return null;
207
- }
208
-
209
- export async function navigate(path: string, replace = false) {
210
- const url = new URL(path, location.origin);
211
-
212
- if (beforeNavigateCb) {
213
- const shouldProceed = beforeNavigateCb(url);
214
- if (shouldProceed === false) return;
215
- }
216
- onNavigateCb?.(url);
217
- saveScrollPosition();
218
-
219
- // load the loading immediately
220
- const destPattern = findPattern(url.pathname);
221
- const DestPage = destPattern ? routeMap[destPattern] : null;
222
- if (DestPage?.loading) {
223
- disposeCurrentPage?.();
224
- disposeCurrentPage = null;
225
- pushHydrationNodes([]);
226
- let loadingNode: any;
227
- disposeCurrentPage = withEffectScope(() => {
228
- loadingNode = (DestPage as any).loading();
229
- });
230
- popHydrationNodes();
231
- // replace only grimoire-page, keeps layout stable during transition
232
- const pageEl = document.getElementById("grimoire-page");
233
- if (pageEl) pageEl.replaceChildren(loadingNode);
234
- else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
235
- }
236
-
237
- const res = await fetch(path, {headers: {"x-grimoire-navigate": "1"}});
238
- const contentType = res.headers.get("content-type") ?? "";
239
- if (!contentType.includes("application/json")) {
240
- window.location.href = path;
241
- return;
242
- }
243
- const json = await res.json();
244
- const {data, layoutData, params, pattern, head} = json;
245
- const Page = routeMap[pattern];
246
- if (!Page) {
247
- window.location.href = path;
248
- return;
249
- }
250
-
251
- let mergedData = data;
252
- if (Page.load) {
253
- try {
254
- _collectingDeps = new Set()
255
- const clientData = await Page.load({
256
- params,
257
- url,
258
- request: new Request(url),
259
- });
260
- routeDeps.set(pattern, _collectingDeps);
261
- _collectingDeps = null;
262
- mergedData = {...clientData, ...data};
263
- } catch (e: any) {
264
- _collectingDeps = null;
265
- if (e?.location) {
266
- window.location.href = e.location;
267
- return;
268
- }
269
- console.error("[grimoire] universal load error:", e);
270
- }
271
- }
272
-
273
- // track state for HMR rerender
274
- lastState = {data: mergedData, layoutData, params, pattern};
275
- (globalThis as any).__grimoire_current_pattern__ = pattern;
276
-
277
- disposeCurrentPage?.();
278
- disposeCurrentPage = null;
279
- pushHydrationNodes([]);
280
- let rootNode: any;
281
- disposeCurrentPage = withEffectScope(() => {
282
- try {
283
- rootNode = buildRouteTree(lastState!);
284
- } catch (e) {
285
- console.error(e);
286
- }
287
- });
288
- popHydrationNodes();
289
-
290
- updateHead(head);
291
- document.title = head?.title ?? document.title;
292
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
293
- currentPath = path;
294
-
295
- history[replace ? "replaceState" : "pushState"](null, "", path);
296
- restoreScrollPosition(path);
297
- afterNavigateCb?.(url);
298
- }
299
-
300
- export function initRouter(
301
- routes: Record<
302
- string,
303
- ((props: any) => any) & { load?: (ctx: any) => Promise<any> }
304
- >,
305
- layouts: any[],
306
- initialDispose?: () => void,
307
- ) {
308
- routeMap = routes;
309
- layoutList = layouts;
310
- disposeCurrentPage = initialDispose ?? null;
311
- currentPath = location.pathname;
312
-
313
- // set initial HMR state from SSR
314
- const stateEl = document.getElementById("__grimoire_state__");
315
- if (stateEl) {
316
- const state = JSON.parse(stateEl.textContent!);
317
- lastState = {
318
- data: state.data,
319
- layoutData: state.layoutData,
320
- params: state.params,
321
- pattern: state.pattern,
322
- };
323
- (globalThis as any).__grimoire_current_pattern__ = state.pattern;
324
- (globalThis as any).__grimoire_routes__ = routeMap;
325
- (globalThis as any).__grimoire_rerender__ = hmrRerender;
326
- (globalThis as any).__grimoire_navigate__ = (path: string) =>
327
- navigate(path);
328
- }
329
-
330
- saveScrollPosition();
331
- document.addEventListener("click", handleClick);
332
- window.addEventListener("popstate", () => {
333
- if (location.pathname !== currentPath) {
334
- saveScrollPosition();
335
- currentPath = location.pathname;
336
- navigate(location.pathname);
337
- }
338
- });
339
- setupPreload();
340
- }
341
-
342
- function updateHead(headHtml: string) {
343
- document
344
- .querySelectorAll("[data-grimoire-head]")
345
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
346
- .forEach((el) => el.remove());
347
- const parsed = headHtml
348
- ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
349
- : null;
350
- const incomingTitle = parsed?.querySelector("title");
351
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
352
- document.querySelectorAll("title").forEach((el) => el.remove());
353
- document.title = incomingTitle?.textContent ?? document.title;
354
- if (parsed) {
355
- for (const el of Array.from(parsed.head.children)) {
356
- if (el.tagName === "TITLE") continue;
357
- (el as HTMLElement).dataset.grimoireHead = "1";
358
- document.head.appendChild(el);
359
- }
360
- }
361
- }
362
-
363
- function handleClick(e: MouseEvent) {
364
- const a = (e.target as Element).closest("a");
365
- if (!a) return;
366
- const href = a.getAttribute("href");
367
- if (!href) return;
368
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
369
- e.preventDefault();
370
- navigate(href);
371
- }
1
+ import { popHydrationNodes, pushHydrationNodes } from "@sigil-dev/runtime";
2
+ import { withEffectScope } from "./scope";
3
+
4
+ // ── Dependency tracking ──────────────────────────────────────────────────────
5
+ const routeDeps = new Map<string, Set<string>>(); // pattern → dep keys
6
+ let _collectingDeps: Set<string> | null = null;
7
+
8
+ /**
9
+ * Call from inside a load() function to register a dependency key.
10
+ * When invalidate(key) is called, any route that depends on that key
11
+ * will refetch if it's the current route.
12
+ */
13
+ export function depends(key: string): void {
14
+ _collectingDeps?.add(key);
15
+ }
16
+
17
+ async function refetchCurrent(): Promise<void> {
18
+ if (!lastState) return;
19
+ await navigate(location.pathname, { history: "replace" });
20
+ }
21
+
22
+ export async function invalidate(...keys: string[]): Promise<void> {
23
+ const current = lastState?.pattern;
24
+ if (!current) return;
25
+ const deps = routeDeps.get(current);
26
+ if (!deps) return;
27
+ if (keys.some((k) => deps.has(k))) await refetchCurrent();
28
+ }
29
+
30
+ export async function invalidateAll(): Promise<void> {
31
+ await refetchCurrent();
32
+ }
33
+
34
+ type PageComponent = ((props: any) => any) & {
35
+ load?: (ctx: any) => Promise<any>;
36
+ loading?: () => any;
37
+ error?: (props: { error: unknown }) => any;
38
+ };
39
+ /** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
40
+ * component functions are also accepted (tests, HMR replacements). */
41
+ type RouteEntry = PageComponent | { __lazy: () => Promise<{ default: PageComponent }> };
42
+
43
+ let routeMap: Record<string, RouteEntry> = {};
44
+ const resolvedRoutes: Record<string, PageComponent> = {};
45
+
46
+ async function resolveRoute(pattern: string): Promise<PageComponent | null> {
47
+ const entry = routeMap[pattern];
48
+ if (!entry) return null;
49
+ // plain function: eager component or an HMR hot-swap — always wins over cache
50
+ if (typeof entry === "function") return entry;
51
+ return (resolvedRoutes[pattern] ??= (await entry.__lazy()).default);
52
+ }
53
+ let layoutList: { path: string; component: (props: any) => any }[] = [];
54
+ let disposeCurrentPage: (() => void) | null = null;
55
+ let currentPath = location.pathname;
56
+
57
+ // C1: Navigation hooks
58
+ let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
59
+ let onNavigateCb: ((url: URL) => void) | null = null;
60
+ let afterNavigateCb: ((url: URL) => void) | null = null;
61
+
62
+ // // HMR
63
+ // (globalThis as any).__grimoire_routes__ = routeMap;
64
+ // (globalThis as any).__grimoire_current_pattern__ = currentPath;
65
+ // (globalThis as any).__grimoire_navigate__ = navigate;
66
+
67
+ export async function hmrRerender(): Promise<void> {
68
+ if (!lastState) {
69
+ location.reload();
70
+ return;
71
+ }
72
+ const Page = await resolveRoute(lastState.pattern);
73
+ if (!Page) {
74
+ location.reload();
75
+ return;
76
+ }
77
+ disposeCurrentPage?.();
78
+ pushHydrationNodes([]);
79
+ let rootNode: any;
80
+ disposeCurrentPage = withEffectScope(() => {
81
+ rootNode = buildRouteTree(lastState!, Page);
82
+ });
83
+ popHydrationNodes();
84
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
85
+ }
86
+
87
+ // (globalThis as any).__grimoire_rerender__ = hmrRerender;
88
+
89
+ export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
90
+ beforeNavigateCb = cb;
91
+ }
92
+
93
+ export function onNavigate(cb: (url: URL) => void): void {
94
+ onNavigateCb = cb;
95
+ }
96
+
97
+ export function afterNavigate(cb: (url: URL) => void): void {
98
+ afterNavigateCb = cb;
99
+ }
100
+
101
+ // C2: Scroll restoration
102
+ const scrollPositions = new Map<string, number>();
103
+
104
+ function saveScrollPosition(): void {
105
+ scrollPositions.set(currentPath, window.scrollY);
106
+ }
107
+
108
+ function restoreScrollPosition(path: string): void {
109
+ const saved = scrollPositions.get(path);
110
+ if (saved !== undefined) {
111
+ requestAnimationFrame(() => window.scrollTo(0, saved));
112
+ } else {
113
+ requestAnimationFrame(() => window.scrollTo(0, 0));
114
+ }
115
+ }
116
+
117
+ // C3: Preloading
118
+ let preloadTimer: Timer | null = null;
119
+
120
+ function setupPreload(): void {
121
+ document.addEventListener("mouseover", (e) => {
122
+ const a = (e.target as Element).closest("a");
123
+ if (!a) return;
124
+ const href = a.getAttribute("href");
125
+ if (!href) return;
126
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
127
+
128
+ const preloadData = a.hasAttribute("data-sigil-preload-data");
129
+ const preloadCode = a.hasAttribute("data-sigil-preload-code");
130
+ if (!preloadData && !preloadCode) return;
131
+
132
+ if (preloadTimer) clearTimeout(preloadTimer);
133
+ preloadTimer = setTimeout(() => {
134
+ if (preloadCode) {
135
+ const link = document.createElement("link");
136
+ link.rel = "prefetch";
137
+ link.href = href;
138
+ document.head.appendChild(link);
139
+ }
140
+ if (preloadData) {
141
+ fetch(href, {
142
+ headers: { "x-grimoire-navigate": "1" },
143
+ redirect: "manual",
144
+ priority: "low",
145
+ }).catch(() => {});
146
+ }
147
+ }, 80);
148
+ });
149
+
150
+ document.addEventListener("mouseout", (e) => {
151
+ const a = (e.target as Element).closest("a");
152
+ if (!a) return;
153
+ if (preloadTimer) clearTimeout(preloadTimer);
154
+ });
155
+ }
156
+
157
+ let lastState: {
158
+ data: any;
159
+ layoutData: any[];
160
+ params: any;
161
+ pattern: string;
162
+ } | null = null;
163
+
164
+ function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
165
+ const { data, layoutData, params, pattern } = state!;
166
+ if (!Page) throw new Error(`no component for pattern ${pattern}`);
167
+
168
+ const matchedLayouts = layoutList
169
+ .filter(
170
+ (l) =>
171
+ l.path === "/" ||
172
+ pattern === l.path ||
173
+ pattern.startsWith(`${l.path}/`),
174
+ )
175
+ .sort((a, b) => a.path.length - b.path.length);
176
+
177
+ let renderFn = () => {
178
+ const pageNode = Page({ data, params });
179
+ const pageDiv = document.createElement("div");
180
+ pageDiv.id = "grimoire-page";
181
+ pageDiv.appendChild(pageNode);
182
+ return pageDiv;
183
+ };
184
+
185
+ for (let i = matchedLayouts.length - 1; i >= 0; i--) {
186
+ const LayoutComponent = matchedLayouts[i].component;
187
+ const innerRender = renderFn;
188
+ const currentLayoutData = layoutData?.[i];
189
+ renderFn = () => {
190
+ const childNode = innerRender();
191
+ return LayoutComponent({
192
+ data: currentLayoutData,
193
+ params,
194
+ children: childNode,
195
+ });
196
+ };
197
+ }
198
+
199
+ return renderFn();
200
+ }
201
+
202
+ function matchClientPattern(pattern: string, pathname: string): boolean {
203
+ // haha pp and ph
204
+ const pp = pattern.split("/").filter(Boolean);
205
+ const ph = pathname.split("/").filter(Boolean);
206
+ let pi = 0,
207
+ pj = 0;
208
+ while (pi < pp.length) {
209
+ if (pp[pi]!.startsWith("*")) return true;
210
+ if (pj >= ph.length) return false;
211
+ if (!pp[pi]!.startsWith(":") && pp[pi] !== ph[pj]) return false;
212
+ pi++;
213
+ pj++;
214
+ }
215
+ return pj === ph.length;
216
+ }
217
+
218
+ function findPattern(pathname: string): string | null {
219
+ for (const pattern of Object.keys(routeMap)) {
220
+ if (matchClientPattern(pattern, pathname)) return pattern;
221
+ }
222
+ return null;
223
+ }
224
+
225
+ export interface NavigateOptions {
226
+ /** "push" (default) adds a history entry, "replace" swaps the current one,
227
+ * "none" leaves history untouched (popstate — the browser already moved). */
228
+ history?: "push" | "replace" | "none";
229
+ }
230
+
231
+ // monotonically increasing id — a navigation aborts silently the moment a
232
+ // newer one starts, so overlapping navigations can't commit stale responses
233
+ let navigationId = 0;
234
+
235
+ export async function navigate(
236
+ path: string,
237
+ opts: NavigateOptions | boolean = {},
238
+ ) {
239
+ // boolean back-compat: navigate(path, true) meant "replace"
240
+ const historyMode =
241
+ typeof opts === "boolean"
242
+ ? opts
243
+ ? "replace"
244
+ : "push"
245
+ : (opts.history ?? "push");
246
+ const navId = ++navigationId;
247
+ const url = new URL(path, location.origin);
248
+
249
+ if (beforeNavigateCb) {
250
+ const shouldProceed = beforeNavigateCb(url);
251
+ if (shouldProceed === false) return;
252
+ }
253
+ onNavigateCb?.(url);
254
+ saveScrollPosition();
255
+
256
+ // load the loading immediately
257
+ const destPattern = findPattern(url.pathname);
258
+ const DestPage = destPattern ? await resolveRoute(destPattern) : null;
259
+ if (navId !== navigationId) return;
260
+ if (DestPage?.loading) {
261
+ disposeCurrentPage?.();
262
+ disposeCurrentPage = null;
263
+ pushHydrationNodes([]);
264
+ let loadingNode: any;
265
+ disposeCurrentPage = withEffectScope(() => {
266
+ loadingNode = (DestPage as any).loading();
267
+ });
268
+ popHydrationNodes();
269
+ // replace only grimoire-page, keeps layout stable during transition
270
+ const pageEl = document.getElementById("grimoire-page");
271
+ if (pageEl) pageEl.replaceChildren(loadingNode);
272
+ else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
273
+ }
274
+
275
+ const res = await fetch(path, { headers: { "x-grimoire-navigate": "1" }, redirect: "manual" });
276
+ if (navId !== navigationId) return;
277
+ const contentType = res.headers.get("content-type") ?? "";
278
+ if (!contentType.includes("application/json")) {
279
+ window.location.href = path;
280
+ return;
281
+ }
282
+ const json = await res.json();
283
+ if (navId !== navigationId) return;
284
+ const { data, layoutData, params, pattern, head } = json;
285
+ const Page = await resolveRoute(pattern);
286
+ if (navId !== navigationId) return;
287
+ if (!Page) {
288
+ window.location.href = path;
289
+ return;
290
+ }
291
+
292
+ let mergedData = data;
293
+ if (Page.load) {
294
+ try {
295
+ _collectingDeps = new Set();
296
+ const clientData = await Page.load({
297
+ params,
298
+ url,
299
+ request: new Request(url),
300
+ });
301
+ routeDeps.set(pattern, _collectingDeps);
302
+ _collectingDeps = null;
303
+ mergedData = { ...clientData, ...data };
304
+ } catch (e: any) {
305
+ _collectingDeps = null;
306
+ if (e?.location) {
307
+ window.location.href = e.location;
308
+ return;
309
+ }
310
+ console.error("[grimoire] universal load error:", e);
311
+ }
312
+ if (navId !== navigationId) return;
313
+ }
314
+
315
+ // track state for HMR rerender
316
+ lastState = { data: mergedData, layoutData, params, pattern };
317
+ (globalThis as any).__grimoire_current_pattern__ = pattern;
318
+
319
+ disposeCurrentPage?.();
320
+ disposeCurrentPage = null;
321
+ pushHydrationNodes([]);
322
+ let rootNode: any;
323
+ disposeCurrentPage = withEffectScope(() => {
324
+ try {
325
+ rootNode = buildRouteTree(lastState!, Page);
326
+ } catch (e) {
327
+ console.error(e);
328
+ }
329
+ });
330
+ popHydrationNodes();
331
+
332
+ updateHead(head);
333
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
334
+ currentPath = url.pathname;
335
+
336
+ if (historyMode !== "none") {
337
+ history[historyMode === "replace" ? "replaceState" : "pushState"](
338
+ null,
339
+ "",
340
+ path,
341
+ );
342
+ }
343
+ if (url.hash) {
344
+ const target = document.getElementById(url.hash.slice(1));
345
+ if (target) requestAnimationFrame(() => target.scrollIntoView());
346
+ else restoreScrollPosition(url.pathname);
347
+ } else {
348
+ restoreScrollPosition(url.pathname);
349
+ }
350
+ afterNavigateCb?.(url);
351
+ }
352
+
353
+ export function initRouter(
354
+ routes: Record<string, RouteEntry>,
355
+ layouts: any[] = [],
356
+ initialDispose?: () => void,
357
+ ) {
358
+ routeMap = routes;
359
+ layoutList = layouts;
360
+ disposeCurrentPage = initialDispose ?? null;
361
+ currentPath = location.pathname;
362
+
363
+ // set initial HMR state from SSR
364
+ const stateEl = document.getElementById("__grimoire_state__");
365
+ if (stateEl) {
366
+ const state = JSON.parse(stateEl.textContent!);
367
+ lastState = {
368
+ data: state.data,
369
+ layoutData: state.layoutData,
370
+ params: state.params,
371
+ pattern: state.pattern,
372
+ };
373
+ (globalThis as any).__grimoire_current_pattern__ = state.pattern;
374
+ (globalThis as any).__grimoire_routes__ = routeMap;
375
+ (globalThis as any).__grimoire_rerender__ = hmrRerender;
376
+ (globalThis as any).__grimoire_navigate__ = (
377
+ path: string,
378
+ replace?: boolean,
379
+ ) => navigate(path, replace ?? false);
380
+ }
381
+
382
+ saveScrollPosition();
383
+ document.addEventListener("click", handleClick);
384
+ window.addEventListener("popstate", () => {
385
+ if (location.pathname !== currentPath) {
386
+ // the browser already moved through history — render only, never
387
+ // push/replace here or the forward stack gets clobbered
388
+ navigate(location.pathname, { history: "none" });
389
+ }
390
+ });
391
+ setupPreload();
392
+ }
393
+
394
+ function updateHead(headHtml: string) {
395
+ document
396
+ .querySelectorAll("[data-grimoire-head]")
397
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
398
+ .forEach((el) => el.remove());
399
+ const parsed = headHtml
400
+ ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
401
+ : null;
402
+ const incomingTitle = parsed?.querySelector("title");
403
+ if (incomingTitle) {
404
+ // capture before removing <title> elements — reading document.title
405
+ // after removal returns "" and would wipe the title
406
+ const prevTitle = document.title;
407
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
408
+ document.querySelectorAll("title").forEach((el) => el.remove());
409
+ document.title = incomingTitle.textContent ?? prevTitle;
410
+ }
411
+ if (parsed) {
412
+ for (const el of Array.from(parsed.head.children)) {
413
+ if (el.tagName === "TITLE") continue;
414
+ (el as HTMLElement).dataset.grimoireHead = "1";
415
+ document.head.appendChild(el);
416
+ }
417
+ }
418
+ }
419
+
420
+ function handleClick(e: MouseEvent) {
421
+ // let the browser handle modified clicks (new tab/window/download)
422
+ if (e.defaultPrevented || e.button !== 0) return;
423
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
424
+ const a = (e.target as Element).closest("a");
425
+ if (!a) return;
426
+ if (a.target && a.target !== "_self") return;
427
+ if (a.hasAttribute("download")) return;
428
+ if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
429
+ const href = a.getAttribute("href");
430
+ if (!href) return;
431
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
432
+ // Only intercept clicks for known page routes — let server routes
433
+ // (redirects, API endpoints, etc.) navigate normally so the browser
434
+ // follows the response without the extra fetch-then-redirect dance.
435
+ try {
436
+ const url = new URL(href, location.origin);
437
+ if (!findPattern(url.pathname)) return;
438
+ // same-page anchor: native behavior scrolls to it, no re-render needed
439
+ if (url.pathname === location.pathname && url.hash) return;
440
+ } catch {
441
+ return;
442
+ }
443
+ e.preventDefault();
444
+ navigate(href);
445
+ }