@sigil-dev/grimoire 0.9.20 → 0.9.22

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +16 -5
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +870 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -114
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -745
  28. package/src/rendering/preload.ts +101 -95
  29. package/src/rendering/ssrPlugin.ts +108 -108
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -194
  35. package/src/server/asset-cache.ts +57 -55
  36. package/src/server/build.ts +262 -249
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -0
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +1138 -1022
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -0
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -113
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -69
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +92 -92
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +798 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +378 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +805 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +131 -131
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -1,833 +1,870 @@
1
- import {
2
- collectEffects,
3
- popHydrationNodes,
4
- pushHydrationNodes,
5
- } from "@sigil-dev/runtime";
6
- import { onSubmitEnsureCsrf } from "./csrf.ts";
7
- import {
8
- clearDeps,
9
- depends,
10
- getDeps,
11
- setDeps,
12
- startCollecting,
13
- stopCollecting,
14
- } from "./deps";
15
- import { withEffectScope } from "./scope";
16
-
17
- // re-exported for app code that imports depends() from the router module
18
- export { depends };
19
-
20
- async function refetchCurrent(): Promise<void> {
21
- if (!lastState) return;
22
- // a refetch exists because the data changed; never serve it from a prefetch
23
- prefetched.clear();
24
- await navigate(location.pathname, { history: "replace" });
25
- }
26
-
27
- export async function invalidate(...keys: string[]): Promise<void> {
28
- const current = lastState?.pattern;
29
- if (!current) return;
30
- const deps = getDeps(current);
31
- // no recorded deps → conservative refetch; otherwise only on intersection
32
- if (!deps || deps.size === 0 || keys.some((k) => deps.has(k))) {
33
- await refetchCurrent();
34
- }
35
- }
36
-
37
- export async function invalidateAll(): Promise<void> {
38
- await refetchCurrent();
39
- }
40
-
41
- type PageComponent = ((props: any) => any) & {
42
- load?: (ctx: any) => Promise<any>;
43
- loading?: () => any;
44
- error?: (props: { error: unknown }) => any;
45
- };
46
- /** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
47
- * component functions are also accepted (tests, HMR replacements). */
48
- type RouteEntry =
49
- | PageComponent
50
- | { __lazy: () => Promise<{ default: PageComponent; loading?: () => any }> };
51
-
52
- let routeMap: Record<string, RouteEntry> = {};
53
- const resolvedRoutes: Record<string, PageComponent> = {};
54
-
55
- async function resolveRoute(pattern: string): Promise<PageComponent | null> {
56
- const entry = routeMap[pattern];
57
- if (!entry) return null;
58
- // plain function: eager component or an HMR hot-swap — always wins over cache
59
- if (typeof entry === "function") return entry;
60
- if (!resolvedRoutes[pattern]) {
61
- const mod = (await entry.__lazy()) as {
62
- default: PageComponent;
63
- loading?: PageComponent["loading"];
64
- };
65
- // `loading` is a named export of the page module; navigation looks
66
- // for it on the component, and never saw it before
67
- if (mod.loading && !mod.default.loading) mod.default.loading = mod.loading;
68
- resolvedRoutes[pattern] = mod.default;
69
- }
70
- return resolvedRoutes[pattern];
71
- }
72
- let layoutList: { path: string; component: (props: any) => any }[] = [];
73
- let disposeCurrentPage: (() => void) | null = null;
74
- // Scroll keys and same-page refetch detection are pathname-only on purpose.
75
- // currentSearch is tracked alongside so popstate can tell "?page=2" apart
76
- // from "?page=1" without polluting either of those.
77
- let currentPath = location.pathname;
78
- let currentSearch = location.search;
79
-
80
- // C1: Navigation hooks
81
- let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
82
- let onNavigateCb: ((url: URL) => void) | null = null;
83
- let afterNavigateCb: ((url: URL) => void) | null = null;
84
-
85
- /**
86
- * Shows the page again with an enhanced form's failure as its `form` prop,
87
- * which is what a submission without JavaScript gets from the server. The
88
- * same page code then works either way.
89
- */
90
- export function showActionFailure(form: unknown): Promise<void> {
91
- if (!lastState) return Promise.resolve();
92
- lastState = { ...lastState, form };
93
- return hmrRerender();
94
- }
95
-
96
- export async function hmrRerender(): Promise<void> {
97
- if (!lastState) {
98
- location.reload();
99
- return;
100
- }
101
- const Page = await resolveRoute(lastState.pattern);
102
- if (!Page) {
103
- location.reload();
104
- return;
105
- }
106
- disposeCurrentPage?.();
107
- pushHydrationNodes([]);
108
- let rootNode: any;
109
- let flush = () => {};
110
- disposeCurrentPage = withEffectScope(() => {
111
- ({ value: rootNode, flush } = collectEffects(() =>
112
- buildRouteTree(lastState!, Page),
113
- ));
114
- });
115
- popHydrationNodes();
116
- const preserved = capturePreservedScroll();
117
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
118
- flush();
119
- restorePreservedScroll(preserved);
120
- }
121
-
122
- /**
123
- * Dev-only surface the HMR client drives. Route entries are replaced rather
124
- * than mutated in place so a swapped module also wins for later navigations,
125
- * and the resolved-module cache is dropped with them.
126
- */
127
- export interface HmrControl {
128
- setRoute(pattern: string, entry: RouteEntry): void;
129
- setLayout(path: string, component: (props: any) => any): void;
130
- rerender(): Promise<void>;
131
- }
132
-
133
- const hmrControl: HmrControl = {
134
- setRoute(pattern, entry) {
135
- routeMap[pattern] = entry;
136
- delete resolvedRoutes[pattern];
137
- },
138
- setLayout(path: string, component: (props: any) => any) {
139
- const existing = layoutList.find((l) => l.path === path);
140
- if (existing) existing.component = component;
141
- else layoutList.push({ path, component });
142
- },
143
- rerender: hmrRerender,
144
- };
145
-
146
- export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
147
- beforeNavigateCb = cb;
148
- }
149
-
150
- export function onNavigate(cb: (url: URL) => void): void {
151
- onNavigateCb = cb;
152
- }
153
-
154
- export function afterNavigate(cb: (url: URL) => void): void {
155
- afterNavigateCb = cb;
156
- }
157
-
158
- // C2: Scroll restoration
159
- const scrollPositions = new Map<string, number>();
160
-
161
- function saveScrollPosition(): void {
162
- scrollPositions.set(currentPath, window.scrollY);
163
- }
164
-
165
- function restoreScrollPosition(path: string): void {
166
- const y = scrollPositions.get(path) ?? 0;
167
- window.scrollTo(0, y);
168
- // re-assert after layout settles (late effects/images can shift content)
169
- requestAnimationFrame(() => window.scrollTo(0, y));
170
- }
171
-
172
- function scrollToTop(): void {
173
- window.scrollTo(0, 0);
174
- requestAnimationFrame(() => window.scrollTo(0, 0));
175
- }
176
-
177
- // Elements marked `data-sigil-scroll-preserve` keep their internal scrollTop
178
- // across the root swap: the router rebuilds the whole tree on navigation, so a
179
- // long independently-scrollable sidebar would otherwise snap back to the top.
180
- // The attribute value is the matching key; elements without one fall back to
181
- // their id, then to their ordinal position.
182
- const PRESERVE_ATTR = "data-sigil-scroll-preserve";
183
-
184
- function preserveKey(el: Element, ordinal: number): string {
185
- return el.getAttribute(PRESERVE_ATTR) || el.id || `#${ordinal}`;
186
- }
187
-
188
- function capturePreservedScroll(): Map<string, number> {
189
- const positions = new Map<string, number>();
190
- let ordinal = 0;
191
- for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
192
- positions.set(preserveKey(el, ordinal), el.scrollTop);
193
- ordinal++;
194
- }
195
- return positions;
196
- }
197
-
198
- function restorePreservedScroll(positions: Map<string, number>): void {
199
- if (positions.size === 0) return;
200
- let ordinal = 0;
201
- for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
202
- const top = positions.get(preserveKey(el, ordinal));
203
- if (top !== undefined) el.scrollTop = top;
204
- ordinal++;
205
- }
206
- }
207
-
208
- const TRANSITION_ATTR = "data-sigil-transition";
209
-
210
- /** key → the one element carrying it; keys that appear twice are dropped,
211
- * because a duplicate view-transition-name cancels the whole transition. */
212
- function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
213
- const seen = new Map<string, Element>();
214
- const dup = new Set<string>();
215
- for (const el of root.querySelectorAll(`[${TRANSITION_ATTR}]`)) {
216
- const key = el.getAttribute(TRANSITION_ATTR);
217
- if (!key) continue;
218
- if (seen.has(key)) dup.add(key);
219
- else seen.set(key, el);
220
- }
221
- for (const key of dup) seen.delete(key);
222
- return seen;
223
- }
224
-
225
- /** [key, element on the current page, element on the incoming page] */
226
- function sharedTransitionKeys(
227
- incoming: unknown,
228
- ): Array<[string, Element, Element]> {
229
- const root = incoming as Partial<ParentNode> | null;
230
- if (!root || typeof root.querySelectorAll !== "function") return [];
231
- const next = uniqueTransitionEls(root as ParentNode);
232
- if (next.size === 0) return [];
233
- const prev = uniqueTransitionEls(document);
234
- const both: Array<[string, Element, Element]> = [];
235
- for (const [key, el] of next) {
236
- const old = prev.get(key);
237
- if (old) both.push([key, old, el]);
238
- }
239
- return both;
240
- }
241
-
242
- // C3: Preloading
243
- //
244
- // A prefetch keeps its in-flight Response here and navigate() consumes it.
245
- // The HTTP cache cannot do this job: the navigate JSON carries no freshness
246
- // headers and pages are commonly served `no-cache`, so a plain prefetch
247
- // warmed nothing the click could reuse.
248
- let preloadTimer: Timer | null = null;
249
- const PREFETCH_TTL_MS = 15_000;
250
- const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
251
-
252
- /**
253
- * A held response is only valid for the cookies it was requested with: apps
254
- * keep preferences (a language, a region, a theme) in cookies the server reads
255
- * per request, so a page fetched before the visitor changed one is wrong
256
- * after. Cookies the script can read are part of the key.
257
- */
258
- function prefetchKey(url: URL): string {
259
- return `${url.pathname}${url.search}\n${typeof document === "undefined" ? "" : document.cookie}`;
260
- }
261
-
262
- function navigateFetch(path: string, priority?: "low"): Promise<Response> {
263
- return fetch(path, {
264
- headers: { "x-grimoire-navigate": "1" },
265
- redirect: "manual",
266
- ...(priority ? { priority } : {}),
267
- });
268
- }
269
-
270
- /** The route-local href of an anchor worth prefetching, or null. */
271
- function prefetchHref(a: Element | null): string | null {
272
- if (!a) return null;
273
- const href = a.getAttribute("href");
274
- if (!href) return null;
275
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return null;
276
- if (a.getAttribute("data-sigil-preload") === "off") return null;
277
- // Only links that resolve to a known client route — external pages and
278
- // non-page endpoints (API routes, redirects) are skipped.
279
- try {
280
- const url = new URL(href, location.origin);
281
- if (!findPattern(url.pathname)) return null;
282
- } catch {
283
- return null;
284
- }
285
- return href;
286
- }
287
-
288
- /**
289
- * Warm a navigation: load the route's code and start its data request. The
290
- * response is held for a short while so the click that follows reuses it.
291
- */
292
- export function prefetch(href: string): void {
293
- const conn = (navigator as { connection?: { saveData?: boolean } })
294
- .connection;
295
- if (conn?.saveData) return;
296
- const url = new URL(href, location.origin);
297
- // the page already on screen needs no warming
298
- if (url.pathname === location.pathname && url.search === location.search)
299
- return;
300
- const key = prefetchKey(url);
301
- const hit = prefetched.get(key);
302
- if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
303
- const pattern = findPattern(url.pathname);
304
- if (pattern) void resolveRoute(pattern).catch(() => {});
305
- const res = navigateFetch(url.pathname + url.search, "low");
306
- res.catch(() => prefetched.delete(key));
307
- prefetched.set(key, { res, at: Date.now() });
308
- }
309
-
310
- /** The held prefetch for `path` if it is still fresh; each is used once. */
311
- function takePrefetched(path: string): Promise<Response> | null {
312
- const key = prefetchKey(new URL(path, location.origin));
313
- const hit = prefetched.get(key);
314
- prefetched.delete(key);
315
- if (!hit || Date.now() - hit.at >= PREFETCH_TTL_MS) return null;
316
- return hit.res;
317
- }
318
-
319
- function setupPreload(): void {
320
- // Hover is a desktop signal; a short delay ignores cursors passing over.
321
- document.addEventListener("mouseover", (e) => {
322
- const a = (e.target as Element).closest("a");
323
- const href = prefetchHref(a);
324
- if (!a || !href) return;
325
- clearTimeout(preloadTimer);
326
- preloadTimer = setTimeout(() => {
327
- if (a.hasAttribute("data-sigil-preload-code")) {
328
- const link = document.createElement("link");
329
- link.rel = "prefetch";
330
- link.href = href;
331
- document.head.appendChild(link);
332
- }
333
- prefetch(href);
334
- }, 80);
335
- });
336
-
337
- document.addEventListener("mouseout", (e) => {
338
- const a = (e.target as Element).closest("a");
339
- if (!a) return;
340
- clearTimeout(preloadTimer);
341
- });
342
-
343
- // Touch has no hover, but a tap lands 100-300ms after the finger goes
344
- // down; start the request then.
345
- document.addEventListener(
346
- "touchstart",
347
- (e) => {
348
- const href = prefetchHref((e.target as Element).closest("a"));
349
- if (href) prefetch(href);
350
- },
351
- { passive: true },
352
- );
353
-
354
- // Opt-in: `data-sigil-preload="viewport"` warms a link once it scrolls
355
- // into view, for navs whose next tap is predictable.
356
- if (typeof IntersectionObserver !== "undefined") {
357
- const io = new IntersectionObserver((entries) => {
358
- for (const entry of entries) {
359
- if (!entry.isIntersecting) continue;
360
- io.unobserve(entry.target);
361
- const href = prefetchHref(entry.target);
362
- if (href) prefetch(href);
363
- }
364
- });
365
- const observe = (root: ParentNode) => {
366
- for (const a of root.querySelectorAll('a[data-sigil-preload="viewport"]'))
367
- io.observe(a);
368
- };
369
- observe(document);
370
- new MutationObserver((muts) => {
371
- for (const m of muts)
372
- for (const n of m.addedNodes)
373
- if (n instanceof Element) {
374
- if (n.matches('a[data-sigil-preload="viewport"]')) io.observe(n);
375
- observe(n);
376
- }
377
- }).observe(document.body, { childList: true, subtree: true });
378
- }
379
- }
380
-
381
- let lastState: {
382
- data: any;
383
- layoutData: any[];
384
- params: any;
385
- pattern: string;
386
- /** What the page's last failed action passed to fail(); cleared by navigation. */
387
- form?: unknown;
388
- } | null = null;
389
-
390
- function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
391
- const { data, layoutData, params, pattern, form } = state!;
392
- if (!Page) throw new Error(`no component for pattern ${pattern}`);
393
-
394
- const matchedLayouts = layoutList
395
- .filter(
396
- (l) =>
397
- l.path === "/" ||
398
- pattern === l.path ||
399
- pattern.startsWith(`${l.path}/`),
400
- )
401
- .sort((a, b) => a.path.length - b.path.length);
402
-
403
- let renderFn = () => {
404
- const pageNode = Page({ data, params, form });
405
- const pageDiv = document.createElement("div");
406
- pageDiv.id = "grimoire-page";
407
- pageDiv.appendChild(pageNode);
408
- return pageDiv;
409
- };
410
-
411
- for (let i = matchedLayouts.length - 1; i >= 0; i--) {
412
- const LayoutComponent = matchedLayouts[i].component;
413
- const innerRender = renderFn;
414
- const currentLayoutData = layoutData?.[i];
415
- renderFn = () => {
416
- const childNode = innerRender();
417
- return LayoutComponent({
418
- data: currentLayoutData,
419
- params,
420
- path: pattern,
421
- children: childNode,
422
- });
423
- };
424
- }
425
-
426
- return renderFn();
427
- }
428
-
429
- function matchClientPattern(pattern: string, pathname: string): boolean {
430
- // haha pp and ph
431
- const pp = pattern.split("/").filter(Boolean);
432
- const ph = pathname.split("/").filter(Boolean);
433
-
434
- // Depth-first walk; optional segments (:x?) try consuming one segment
435
- // before consuming zero, mirroring the server's matchPattern.
436
- function walk(pi: number, pj: number): boolean {
437
- if (pi === pp.length) return pj === ph.length;
438
- const part = pp[pi]!;
439
- if (part.startsWith("*")) return true;
440
- const optional = part.startsWith(":") && part.endsWith("?");
441
- if (optional && pj < ph.length && walk(pi + 1, pj + 1)) return true;
442
- if (!optional) {
443
- if (pj >= ph.length) return false;
444
- if (!part.startsWith(":") && part !== ph[pj]) return false;
445
- return walk(pi + 1, pj + 1);
446
- }
447
- return walk(pi + 1, pj);
448
- }
449
-
450
- return walk(0, 0);
451
- }
452
-
453
- function findPattern(pathname: string): string | null {
454
- for (const pattern of Object.keys(routeMap)) {
455
- if (matchClientPattern(pattern, pathname)) return pattern;
456
- }
457
- return null;
458
- }
459
-
460
- export interface NavigateOptions {
461
- /** "push" (default) adds a history entry, "replace" swaps the current one,
462
- * "none" leaves history untouched (popstate — the browser already moved). */
463
- history?: "push" | "replace" | "none";
464
- }
465
-
466
- // monotonically increasing id — a navigation aborts silently the moment a
467
- // newer one starts, so overlapping navigations can't commit stale responses
468
- let navigationId = 0;
469
-
470
- export async function navigate(
471
- path: string,
472
- opts: NavigateOptions | boolean = {},
473
- ) {
474
- // boolean back-compat: navigate(path, true) meant "replace"
475
- const historyMode =
476
- typeof opts === "boolean"
477
- ? opts
478
- ? "replace"
479
- : "push"
480
- : (opts.history ?? "push");
481
- const navId = ++navigationId;
482
- const url = new URL(path, location.origin);
483
-
484
- if (beforeNavigateCb) {
485
- const shouldProceed = beforeNavigateCb(url);
486
- if (shouldProceed === false) return;
487
- }
488
- onNavigateCb?.(url);
489
- saveScrollPosition();
490
-
491
- // load the loading immediately
492
- const destPattern = findPattern(url.pathname);
493
- const DestPage = destPattern ? await resolveRoute(destPattern) : null;
494
- if (navId !== navigationId) return;
495
- if (DestPage?.loading) {
496
- disposeCurrentPage?.();
497
- disposeCurrentPage = null;
498
- pushHydrationNodes([]);
499
- let loadingNode: any;
500
- let flush = () => {};
501
- disposeCurrentPage = withEffectScope(() => {
502
- ({ value: loadingNode, flush } = collectEffects(() =>
503
- (DestPage as any).loading(),
504
- ));
505
- });
506
- popHydrationNodes();
507
- // replace only grimoire-page, keeps layout stable during transition
508
- const pageEl = document.getElementById("grimoire-page");
509
- if (pageEl) pageEl.replaceChildren(loadingNode);
510
- else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
511
- flush();
512
- }
513
-
514
- let res: Response;
515
- try {
516
- res = await (takePrefetched(path) ?? navigateFetch(path));
517
- } catch {
518
- // a failed prefetch must not fail the click
519
- res = await navigateFetch(path);
520
- }
521
- if (navId !== navigationId) return;
522
- const contentType = res.headers.get("content-type") ?? "";
523
- if (!contentType.includes("application/json")) {
524
- window.location.href = path;
525
- return;
526
- }
527
- const json = await res.json();
528
- if (navId !== navigationId) return;
529
- const { data, layoutData, params, pattern, head, deps } = json;
530
- const Page = await resolveRoute(pattern);
531
- if (navId !== navigationId) return;
532
- if (!Page) {
533
- window.location.href = path;
534
- return;
535
- }
536
-
537
- let mergedData = data;
538
- if (Page.load) {
539
- try {
540
- startCollecting();
541
- const clientData = await Page.load({
542
- params,
543
- url,
544
- request: new Request(url),
545
- // layout loads run server-side; their data arrives in layoutData —
546
- // parent() merges it outermost-first, mirroring the server context
547
- parent: async () =>
548
- Object.assign(
549
- {},
550
- ...(Array.isArray(layoutData) ? layoutData : []).filter(
551
- (d) => d && typeof d === "object",
552
- ),
553
- ),
554
- });
555
- // merge server-collected keys (page/layout server loads) with
556
- // whatever this client-side load itself registered
557
- setDeps(pattern, [
558
- ...(Array.isArray(deps) ? deps : []),
559
- ...stopCollecting(),
560
- ]);
561
- mergedData = { ...clientData, ...data };
562
- } catch (e: unknown) {
563
- stopCollecting();
564
- if (e && typeof e === "object" && "location" in e) {
565
- window.location.href = String((e as { location: unknown }).location);
566
- return;
567
- }
568
- console.error("[grimoire] universal load error:", e);
569
- }
570
- if (navId !== navigationId) return;
571
- } else if (Array.isArray(deps)) {
572
- // no client-side load to run — the server's collected depends() keys
573
- // (from +page.server.ts / +layout.server.ts) are the whole story
574
- setDeps(pattern, deps);
575
- }
576
-
577
- // track state for HMR rerender
578
- lastState = { data: mergedData, layoutData, params, pattern };
579
- (globalThis as any).__grimoire_current_pattern__ = pattern;
580
-
581
- disposeCurrentPage?.();
582
- disposeCurrentPage = null;
583
- pushHydrationNodes([]);
584
- let rootNode: any;
585
- // the page's effects (and use: directives) run once it is in the document
586
- let flushEffects = () => {};
587
- disposeCurrentPage = withEffectScope(() => {
588
- try {
589
- ({ value: rootNode, flush: flushEffects } = collectEffects(() =>
590
- buildRouteTree(lastState!, Page),
591
- ));
592
- } catch (e) {
593
- console.error(e);
594
- }
595
- });
596
- popHydrationNodes();
597
-
598
- updateHead(head);
599
- // isRefetch is read before currentPath moves, and captured, because
600
- // applyScroll may run after this function has returned.
601
- const isRefetch = url.pathname === currentPath;
602
-
603
- // Scroll has to be decided in the same frame the content lands. Running it
604
- // here, outside doSwap, meant the hash lookup hit the *outgoing* DOM: a
605
- // same-page anchor was already present and worked, while an anchor on the
606
- // incoming page did not exist yet and fell through to scrollToTop().
607
- const applyScroll = () => {
608
- if (url.hash) {
609
- const target = document.getElementById(url.hash.slice(1));
610
- if (!target) {
611
- scrollToTop();
612
- return;
613
- }
614
- target.scrollIntoView();
615
- // re-assert after layout settles (late effects/images can shift content)
616
- requestAnimationFrame(() => target.scrollIntoView());
617
- return;
618
- }
619
- if (historyMode === "none") {
620
- // popstate: the browser already moved through history — restore what
621
- // we saved for this path (back/forward semantics)
622
- restoreScrollPosition(url.pathname);
623
- return;
624
- }
625
- // fresh navigation starts at the top; a same-path replace
626
- // (invalidate/refetch) keeps the current scroll
627
- if (!isRefetch) scrollToTop();
628
- };
629
-
630
- // View transitions: animate the swap when the browser supports it and the
631
- // user hasn't asked for reduced motion. The callback must stay synchronous.
632
- const preserved = capturePreservedScroll();
633
- const doc = document as Document & {
634
- startViewTransition?: (
635
- cb: () => void,
636
- ) => { finished?: Promise<unknown>; ready?: Promise<unknown> } | undefined;
637
- };
638
- const animate =
639
- typeof doc.startViewTransition === "function" &&
640
- !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
641
- // elements the old and new page share by key morph into each other
642
- const shared = animate ? sharedTransitionKeys(rootNode) : [];
643
- const named: Element[] = [];
644
- const name = (el: Element, key: string) => {
645
- (el as HTMLElement).style.setProperty("view-transition-name", key);
646
- named.push(el);
647
- };
648
- const doSwap = () => {
649
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
650
- flushEffects();
651
- for (const [key, , next] of shared) name(next, key);
652
- restorePreservedScroll(preserved);
653
- applyScroll();
654
- };
655
- if (animate) {
656
- // the browser snapshots the old page as startViewTransition is called
657
- for (const [key, prev] of shared) name(prev, key);
658
- const transition = doc.startViewTransition?.(doSwap);
659
- const clear = () => {
660
- for (const el of named)
661
- (el as HTMLElement).style.removeProperty("view-transition-name");
662
- };
663
- Promise.resolve(transition?.finished).then(clear, clear);
664
- // a skipped transition (another navigation, a hidden tab) rejects
665
- // ready; the swap still runs, so it is not an error worth reporting
666
- transition?.ready?.catch(() => {});
667
- } else {
668
- doSwap();
669
- }
670
- currentPath = url.pathname;
671
- currentSearch = url.search;
672
-
673
- if (historyMode !== "none") {
674
- history[historyMode === "replace" ? "replaceState" : "pushState"](
675
- null,
676
- "",
677
- path,
678
- );
679
- }
680
- afterNavigateCb?.(url);
681
- }
682
-
683
- export interface RouterExtensions {
684
- /** [param=matcher] validators from src/params/*.ts (manifest-generated). */
685
- matchers?: Record<string, (value: string) => boolean>;
686
- /** Server-collected depends() keys per route pattern (from SSR state). */
687
- deps?: Record<string, string[]>;
688
- }
689
-
690
- let paramMatcherFns: Record<string, (value: string) => boolean> = {};
691
-
692
- export function initRouter(
693
- routes: Record<string, RouteEntry>,
694
- layouts: any[] = [],
695
- initialDispose?: () => void,
696
- ext?: RouterExtensions,
697
- ) {
698
- paramMatcherFns = ext?.matchers ?? {};
699
- routeMap = routes;
700
- layoutList = layouts;
701
- prefetched.clear();
702
- disposeCurrentPage = initialDispose ?? null;
703
- currentPath = location.pathname;
704
- currentSearch = location.search;
705
-
706
- // the app owns scroll: the browser's automatic restoration fires after
707
- // the router's own scroll and clobbers scroll-to-top / saved positions
708
- if ("scrollRestoration" in history) history.scrollRestoration = "manual";
709
- // dev HMR surface: available even without SSR state so the client can tell
710
- // a missing router apart from a missing initial payload
711
- const globals = globalThis as unknown as {
712
- __grimoire_current_pattern__?: string;
713
- __grimoire_routes__?: Record<string, RouteEntry>;
714
- __grimoire_rerender__?: () => Promise<void>;
715
- __grimoire_navigate__?: (path: string, replace?: boolean) => void;
716
- __grimoire_form__?: (form: unknown) => Promise<void>;
717
- __grimoire_hmr__?: HmrControl;
718
- };
719
- globals.__grimoire_routes__ = routeMap;
720
- globals.__grimoire_rerender__ = hmrRerender;
721
- globals.__grimoire_hmr__ = hmrControl;
722
- globals.__grimoire_form__ = showActionFailure;
723
- globals.__grimoire_navigate__ = (path, replace) =>
724
- navigate(path, replace ?? false);
725
-
726
- // initial HMR state from SSR
727
- const stateEl = document.getElementById("__grimoire_state__");
728
- if (stateEl) {
729
- const state = JSON.parse(stateEl.textContent!);
730
- lastState = {
731
- data: state.data,
732
- layoutData: state.layoutData,
733
- params: state.params,
734
- pattern: state.pattern,
735
- form: state.form,
736
- };
737
- if (Array.isArray(state.deps)) {
738
- setDeps(state.pattern, state.deps);
739
- }
740
- globals.__grimoire_current_pattern__ = state.pattern;
741
- }
742
-
743
- saveScrollPosition();
744
- document.addEventListener("click", handleClick);
745
- // forms rendered client-side have no SSR-injected _csrf input
746
- document.addEventListener("submit", onSubmitEnsureCsrf, true);
747
- window.addEventListener("popstate", () => {
748
- if (
749
- location.pathname === currentPath &&
750
- location.search === currentSearch
751
- ) {
752
- return;
753
- }
754
- // the browser already moved through history — render only, never
755
- // push/replace here or the forward stack gets clobbered.
756
- // The search has to come along: refetching the bare pathname served
757
- // unfiltered data while the address bar still showed the query.
758
- // The hash deliberately does not, so back/forward restores the saved
759
- // scroll offset instead of re-jumping to the anchor, matching the
760
- // browser's own behaviour for document history navigation.
761
- navigate(location.pathname + location.search, { history: "none" });
762
- });
763
- setupPreload();
764
- }
765
-
766
- /**
767
- * Swap the page's <head> tags for the incoming page's. Server-rendered tags
768
- * sit between `<!--grimoire-head-->` markers; tags added by an earlier
769
- * navigation carry `data-grimoire-head`. Both are replaced, so the first
770
- * navigation doesn't leave the server-rendered description or icon behind
771
- * next to the new ones. With no incoming <title>, the current title stays.
772
- */
773
- function updateHead(headHtml: string) {
774
- const prevTitle = document.title;
775
- const markers = Array.from(document.head.childNodes).filter(
776
- (n): n is Comment => n.nodeType === Node.COMMENT_NODE,
777
- );
778
- const start = markers.find((c) => c.data === "grimoire-head");
779
- const end = markers.find((c) => c.data === "/grimoire-head");
780
- if (start && end) {
781
- while (start.nextSibling && start.nextSibling !== end) {
782
- start.nextSibling.remove();
783
- }
784
- }
785
- document
786
- .querySelectorAll("[data-grimoire-head]")
787
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
788
- .forEach((el) => el.remove());
789
- const parsed = headHtml
790
- ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
791
- : null;
792
- const incomingTitle = parsed?.querySelector("title");
793
- //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
794
- document.querySelectorAll("title").forEach((el) => el.remove());
795
- document.title = incomingTitle?.textContent ?? prevTitle;
796
- if (parsed) {
797
- for (const el of Array.from(parsed.head.children)) {
798
- if (el.tagName === "TITLE") continue;
799
- (el as HTMLElement).dataset.grimoireHead = "1";
800
- if (end) document.head.insertBefore(el, end);
801
- else document.head.appendChild(el);
802
- }
803
- }
804
- }
805
-
806
- function handleClick(e: MouseEvent) {
807
- // let the browser handle modified clicks (new tab/window/download)
808
- if (e.defaultPrevented || e.button !== 0) return;
809
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
810
- const a = (e.target as Element).closest("a");
811
- if (!a) return;
812
- if (a.target && a.target !== "_self") return;
813
- if (a.hasAttribute("download")) return;
814
- if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
815
- const href = a.getAttribute("href");
816
- if (!href) return;
817
- if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
818
- // Only intercept clicks for known page routes — let server routes
819
- // (redirects, API endpoints, etc.) navigate normally so the browser
820
- // follows the response without the extra fetch-then-redirect dance.
821
- try {
822
- const url = new URL(href, location.origin);
823
- if (!findPattern(url.pathname)) return;
824
- // same-page anchor: native behavior scrolls to it, no re-render needed
825
- if (url.pathname === location.pathname && url.hash) return;
826
- } catch {
827
- return;
828
- }
829
- e.preventDefault();
830
- // a pending hover prefetch would re-request what this click just consumed
831
- clearTimeout(preloadTimer);
832
- navigate(href);
833
- }
1
+ import {
2
+ collectEffects,
3
+ popHydrationNodes,
4
+ pushHydrationNodes,
5
+ } from "@sigil-dev/runtime";
6
+ import { onSubmitEnsureCsrf } from "./csrf.ts";
7
+ import {
8
+ clearDeps,
9
+ depends,
10
+ getDeps,
11
+ setDeps,
12
+ startCollecting,
13
+ stopCollecting,
14
+ } from "./deps";
15
+ import { withEffectScope } from "./scope";
16
+
17
+ // re-exported for app code that imports depends() from the router module
18
+ export { depends };
19
+
20
+ async function refetchCurrent(): Promise<void> {
21
+ if (!lastState) return;
22
+ // a refetch exists because the data changed; never serve it from a prefetch
23
+ prefetched.clear();
24
+ await navigate(location.pathname, { history: "replace" });
25
+ }
26
+
27
+ export async function invalidate(...keys: string[]): Promise<void> {
28
+ const current = lastState?.pattern;
29
+ if (!current) return;
30
+ const deps = getDeps(current);
31
+ // no recorded deps → conservative refetch; otherwise only on intersection
32
+ if (!deps || deps.size === 0 || keys.some((k) => deps.has(k))) {
33
+ await refetchCurrent();
34
+ }
35
+ }
36
+
37
+ export async function invalidateAll(): Promise<void> {
38
+ await refetchCurrent();
39
+ }
40
+
41
+ type PageComponent = ((props: any) => any) & {
42
+ load?: (ctx: any) => Promise<any>;
43
+ loading?: () => any;
44
+ error?: (props: { error: unknown }) => any;
45
+ };
46
+ /** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
47
+ * component functions are also accepted (tests, HMR replacements). */
48
+ type RouteEntry =
49
+ | PageComponent
50
+ | { __lazy: () => Promise<{ default: PageComponent; loading?: () => any }> };
51
+
52
+ let routeMap: Record<string, RouteEntry> = {};
53
+ const resolvedRoutes: Record<string, PageComponent> = {};
54
+
55
+ async function resolveRoute(pattern: string): Promise<PageComponent | null> {
56
+ const entry = routeMap[pattern];
57
+ if (!entry) return null;
58
+ // plain function: eager component or an HMR hot-swap — always wins over cache
59
+ if (typeof entry === "function") return entry;
60
+ if (!resolvedRoutes[pattern]) {
61
+ const mod = (await entry.__lazy()) as {
62
+ default: PageComponent;
63
+ loading?: PageComponent["loading"];
64
+ };
65
+ // `loading` is a named export of the page module; navigation looks
66
+ // for it on the component, and never saw it before
67
+ if (mod.loading && !mod.default.loading) mod.default.loading = mod.loading;
68
+ resolvedRoutes[pattern] = mod.default;
69
+ }
70
+ return resolvedRoutes[pattern];
71
+ }
72
+ let layoutList: { path: string; component: (props: any) => any }[] = [];
73
+ let disposeCurrentPage: (() => void) | null = null;
74
+ // Scroll keys and same-page refetch detection are pathname-only on purpose.
75
+ // currentSearch is tracked alongside so popstate can tell "?page=2" apart
76
+ // from "?page=1" without polluting either of those.
77
+ let currentPath = location.pathname;
78
+ let currentSearch = location.search;
79
+
80
+ // C1: Navigation hooks
81
+ let beforeNavigateCb: ((url: URL) => boolean | undefined) | null = null;
82
+ let onNavigateCb: ((url: URL) => void) | null = null;
83
+ let afterNavigateCb: ((url: URL) => void) | null = null;
84
+
85
+ /**
86
+ * Shows the page again with an enhanced form's failure as its `form` prop,
87
+ * which is what a submission without JavaScript gets from the server. The
88
+ * same page code then works either way.
89
+ */
90
+ export function showActionFailure(form: unknown): Promise<void> {
91
+ if (!lastState) return Promise.resolve();
92
+ lastState = { ...lastState, form };
93
+ return hmrRerender();
94
+ }
95
+
96
+ export async function hmrRerender(): Promise<void> {
97
+ if (!lastState) {
98
+ location.reload();
99
+ return;
100
+ }
101
+ const Page = await resolveRoute(lastState.pattern);
102
+ if (!Page) {
103
+ location.reload();
104
+ return;
105
+ }
106
+ disposeCurrentPage?.();
107
+ pushHydrationNodes([]);
108
+ let rootNode: any;
109
+ let flush = () => {};
110
+ disposeCurrentPage = withEffectScope(() => {
111
+ ({ value: rootNode, flush } = collectEffects(() =>
112
+ buildRouteTree(lastState!, Page),
113
+ ));
114
+ });
115
+ popHydrationNodes();
116
+ const preserved = capturePreservedScroll();
117
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
118
+ flush();
119
+ restorePreservedScroll(preserved);
120
+ }
121
+
122
+ /**
123
+ * Dev-only surface the HMR client drives. Route entries are replaced rather
124
+ * than mutated in place so a swapped module also wins for later navigations,
125
+ * and the resolved-module cache is dropped with them.
126
+ */
127
+ export interface HmrControl {
128
+ setRoute(pattern: string, entry: RouteEntry): void;
129
+ setLayout(path: string, component: (props: any) => any): void;
130
+ rerender(): Promise<void>;
131
+ }
132
+
133
+ const hmrControl: HmrControl = {
134
+ setRoute(pattern, entry) {
135
+ routeMap[pattern] = entry;
136
+ delete resolvedRoutes[pattern];
137
+ },
138
+ setLayout(path: string, component: (props: any) => any) {
139
+ const existing = layoutList.find((l) => l.path === path);
140
+ if (existing) existing.component = component;
141
+ else layoutList.push({ path, component });
142
+ },
143
+ rerender: hmrRerender,
144
+ };
145
+
146
+ export function beforeNavigate(cb: (url: URL) => boolean | undefined): void {
147
+ beforeNavigateCb = cb;
148
+ }
149
+
150
+ export function onNavigate(cb: (url: URL) => void): void {
151
+ onNavigateCb = cb;
152
+ }
153
+
154
+ export function afterNavigate(cb: (url: URL) => void): void {
155
+ afterNavigateCb = cb;
156
+ }
157
+
158
+ // C2: Scroll restoration
159
+ const scrollPositions = new Map<string, number>();
160
+
161
+ function saveScrollPosition(): void {
162
+ scrollPositions.set(currentPath, window.scrollY);
163
+ }
164
+
165
+ function restoreScrollPosition(path: string): void {
166
+ const y = scrollPositions.get(path) ?? 0;
167
+ window.scrollTo(0, y);
168
+ // re-assert after layout settles (late effects/images can shift content)
169
+ requestAnimationFrame(() => window.scrollTo(0, y));
170
+ }
171
+
172
+ function scrollToTop(): void {
173
+ window.scrollTo(0, 0);
174
+ requestAnimationFrame(() => window.scrollTo(0, 0));
175
+ }
176
+
177
+ // Elements marked `data-sigil-scroll-preserve` keep their internal scrollTop
178
+ // across the root swap: the router rebuilds the whole tree on navigation, so a
179
+ // long independently-scrollable sidebar would otherwise snap back to the top.
180
+ // The attribute value is the matching key; elements without one fall back to
181
+ // their id, then to their ordinal position.
182
+ const PRESERVE_ATTR = "data-sigil-scroll-preserve";
183
+
184
+ function preserveKey(el: Element, ordinal: number): string {
185
+ return el.getAttribute(PRESERVE_ATTR) || el.id || `#${ordinal}`;
186
+ }
187
+
188
+ function capturePreservedScroll(): Map<string, number> {
189
+ const positions = new Map<string, number>();
190
+ let ordinal = 0;
191
+ for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
192
+ positions.set(preserveKey(el, ordinal), el.scrollTop);
193
+ ordinal++;
194
+ }
195
+ return positions;
196
+ }
197
+
198
+ function restorePreservedScroll(positions: Map<string, number>): void {
199
+ if (positions.size === 0) return;
200
+ let ordinal = 0;
201
+ for (const el of document.querySelectorAll(`[${PRESERVE_ATTR}]`)) {
202
+ const top = positions.get(preserveKey(el, ordinal));
203
+ if (top !== undefined) el.scrollTop = top;
204
+ ordinal++;
205
+ }
206
+ }
207
+
208
+ const TRANSITION_ATTR = "data-sigil-transition";
209
+
210
+ /** key → the one element carrying it; keys that appear twice are dropped,
211
+ * because a duplicate view-transition-name cancels the whole transition. */
212
+ function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
213
+ const seen = new Map<string, Element>();
214
+ const dup = new Set<string>();
215
+ for (const el of root.querySelectorAll(`[${TRANSITION_ATTR}]`)) {
216
+ const key = el.getAttribute(TRANSITION_ATTR);
217
+ if (!key) continue;
218
+ if (seen.has(key)) dup.add(key);
219
+ else seen.set(key, el);
220
+ }
221
+ for (const key of dup) seen.delete(key);
222
+ return seen;
223
+ }
224
+
225
+ /** [key, element on the current page, element on the incoming page] */
226
+ function sharedTransitionKeys(
227
+ incoming: unknown,
228
+ ): Array<[string, Element, Element]> {
229
+ const root = incoming as Partial<ParentNode> | null;
230
+ if (!root || typeof root.querySelectorAll !== "function") return [];
231
+ const next = uniqueTransitionEls(root as ParentNode);
232
+ if (next.size === 0) return [];
233
+ const prev = uniqueTransitionEls(document);
234
+ const both: Array<[string, Element, Element]> = [];
235
+ for (const [key, el] of next) {
236
+ const old = prev.get(key);
237
+ if (old) both.push([key, old, el]);
238
+ }
239
+ return both;
240
+ }
241
+
242
+ // C3: Preloading
243
+ //
244
+ // A prefetch keeps its in-flight Response here and navigate() consumes it.
245
+ // The HTTP cache cannot do this job: the navigate JSON carries no freshness
246
+ // headers and pages are commonly served `no-cache`, so a plain prefetch
247
+ // warmed nothing the click could reuse.
248
+ let preloadTimer: Timer | null = null;
249
+ const PREFETCH_TTL_MS = 15_000;
250
+ const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
251
+
252
+ /**
253
+ * A held response is only valid for the cookies it was requested with: apps
254
+ * keep preferences (a language, a region, a theme) in cookies the server reads
255
+ * per request, so a page fetched before the visitor changed one is wrong
256
+ * after. Cookies the script can read are part of the key.
257
+ */
258
+ function prefetchKey(url: URL): string {
259
+ return `${url.pathname}${url.search}\n${typeof document === "undefined" ? "" : document.cookie}`;
260
+ }
261
+
262
+ /**
263
+ * A prerendered site has no server to answer `x-grimoire-navigate`, so
264
+ * `adapterStatic` marks its pages and writes the same payload to
265
+ * `<page>/__data.json`, which any static host serves. The path must match
266
+ * `dataFileFor` in server/prerender.ts.
267
+ */
268
+ function navigateTarget(path: string): string {
269
+ if ((globalThis as { __grimoire_static__?: unknown }).__grimoire_static__ !== 1) {
270
+ return path;
271
+ }
272
+ const { pathname } = new URL(path, location.origin);
273
+ return `${pathname.replace(/\/+$/, "")}/__data.json`;
274
+ }
275
+
276
+ function navigateFetch(path: string, priority?: "low"): Promise<Response> {
277
+ const target = navigateTarget(path);
278
+ return fetch(target, {
279
+ ...(target === path ? { headers: { "x-grimoire-navigate": "1" } } : {}),
280
+ redirect: "manual",
281
+ ...(priority ? { priority } : {}),
282
+ });
283
+ }
284
+
285
+ /** The route-local href of an anchor worth prefetching, or null. */
286
+ function prefetchHref(a: Element | null): string | null {
287
+ if (!a) return null;
288
+ const href = a.getAttribute("href");
289
+ if (!href) return null;
290
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return null;
291
+ if (a.getAttribute("data-sigil-preload") === "off") return null;
292
+ // Only links that resolve to a known client route — external pages and
293
+ // non-page endpoints (API routes, redirects) are skipped.
294
+ try {
295
+ const url = new URL(href, location.origin);
296
+ if (!findPattern(url.pathname)) return null;
297
+ } catch {
298
+ return null;
299
+ }
300
+ return href;
301
+ }
302
+
303
+ /**
304
+ * Warm a navigation: load the route's code and start its data request. The
305
+ * response is held for a short while so the click that follows reuses it.
306
+ */
307
+ export function prefetch(href: string): void {
308
+ const conn = (navigator as { connection?: { saveData?: boolean } })
309
+ .connection;
310
+ if (conn?.saveData) return;
311
+ const url = new URL(href, location.origin);
312
+ // the page already on screen needs no warming
313
+ if (url.pathname === location.pathname && url.search === location.search)
314
+ return;
315
+ const key = prefetchKey(url);
316
+ const hit = prefetched.get(key);
317
+ if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
318
+ const pattern = findPattern(url.pathname);
319
+ if (pattern) void resolveRoute(pattern).catch(() => {});
320
+ const res = navigateFetch(url.pathname + url.search, "low");
321
+ res.catch(() => prefetched.delete(key));
322
+ prefetched.set(key, { res, at: Date.now() });
323
+ }
324
+
325
+ /** The held prefetch for `path` if it is still fresh; each is used once. */
326
+ function takePrefetched(path: string): Promise<Response> | null {
327
+ const key = prefetchKey(new URL(path, location.origin));
328
+ const hit = prefetched.get(key);
329
+ prefetched.delete(key);
330
+ if (!hit || Date.now() - hit.at >= PREFETCH_TTL_MS) return null;
331
+ return hit.res;
332
+ }
333
+
334
+ function setupPreload(): void {
335
+ // Hover is a desktop signal; a short delay ignores cursors passing over.
336
+ document.addEventListener("mouseover", (e) => {
337
+ const a = (e.target as Element).closest("a");
338
+ const href = prefetchHref(a);
339
+ if (!a || !href) return;
340
+ clearTimeout(preloadTimer);
341
+ preloadTimer = setTimeout(() => {
342
+ if (a.hasAttribute("data-sigil-preload-code")) {
343
+ const link = document.createElement("link");
344
+ link.rel = "prefetch";
345
+ link.href = href;
346
+ document.head.appendChild(link);
347
+ }
348
+ prefetch(href);
349
+ }, 80);
350
+ });
351
+
352
+ document.addEventListener("mouseout", (e) => {
353
+ const a = (e.target as Element).closest("a");
354
+ if (!a) return;
355
+ clearTimeout(preloadTimer);
356
+ });
357
+
358
+ // Touch has no hover, but a tap lands 100-300ms after the finger goes
359
+ // down; start the request then.
360
+ document.addEventListener(
361
+ "touchstart",
362
+ (e) => {
363
+ const href = prefetchHref((e.target as Element).closest("a"));
364
+ if (href) prefetch(href);
365
+ },
366
+ { passive: true },
367
+ );
368
+
369
+ // Opt-in: `data-sigil-preload="viewport"` warms a link once it scrolls
370
+ // into view, for navs whose next tap is predictable.
371
+ if (typeof IntersectionObserver !== "undefined") {
372
+ const io = new IntersectionObserver((entries) => {
373
+ for (const entry of entries) {
374
+ if (!entry.isIntersecting) continue;
375
+ io.unobserve(entry.target);
376
+ const href = prefetchHref(entry.target);
377
+ if (href) prefetch(href);
378
+ }
379
+ });
380
+ const observe = (root: ParentNode) => {
381
+ for (const a of root.querySelectorAll('a[data-sigil-preload="viewport"]'))
382
+ io.observe(a);
383
+ };
384
+ observe(document);
385
+ new MutationObserver((muts) => {
386
+ for (const m of muts)
387
+ for (const n of m.addedNodes)
388
+ if (n instanceof Element) {
389
+ if (n.matches('a[data-sigil-preload="viewport"]')) io.observe(n);
390
+ observe(n);
391
+ }
392
+ }).observe(document.body, { childList: true, subtree: true });
393
+ }
394
+ }
395
+
396
+ let lastState: {
397
+ data: any;
398
+ layoutData: any[];
399
+ params: any;
400
+ pattern: string;
401
+ /** What the page's last failed action passed to fail(); cleared by navigation. */
402
+ form?: unknown;
403
+ } | null = null;
404
+
405
+ function buildRouteTree(state: typeof lastState, Page: PageComponent): any {
406
+ const { data, layoutData, params, pattern, form } = state!;
407
+ if (!Page) throw new Error(`no component for pattern ${pattern}`);
408
+
409
+ const matchedLayouts = layoutList
410
+ .filter(
411
+ (l) =>
412
+ l.path === "/" ||
413
+ pattern === l.path ||
414
+ pattern.startsWith(`${l.path}/`),
415
+ )
416
+ .sort((a, b) => a.path.length - b.path.length);
417
+
418
+ let renderFn = () => {
419
+ const pageNode = Page({ data, params, form });
420
+ const pageDiv = document.createElement("div");
421
+ pageDiv.id = "grimoire-page";
422
+ pageDiv.appendChild(pageNode);
423
+ return pageDiv;
424
+ };
425
+
426
+ for (let i = matchedLayouts.length - 1; i >= 0; i--) {
427
+ const LayoutComponent = matchedLayouts[i].component;
428
+ const innerRender = renderFn;
429
+ const currentLayoutData = layoutData?.[i];
430
+ renderFn = () => {
431
+ const childNode = innerRender();
432
+ return LayoutComponent({
433
+ data: currentLayoutData,
434
+ params,
435
+ path: pattern,
436
+ children: childNode,
437
+ });
438
+ };
439
+ }
440
+
441
+ return renderFn();
442
+ }
443
+
444
+ function matchClientPattern(pattern: string, pathname: string): boolean {
445
+ // haha pp and ph
446
+ const pp = pattern.split("/").filter(Boolean);
447
+ const ph = pathname.split("/").filter(Boolean);
448
+
449
+ // Depth-first walk; optional segments (:x?) try consuming one segment
450
+ // before consuming zero, mirroring the server's matchPattern.
451
+ function walk(pi: number, pj: number): boolean {
452
+ if (pi === pp.length) return pj === ph.length;
453
+ const part = pp[pi]!;
454
+ if (part.startsWith("*")) return true;
455
+ const optional = part.startsWith(":") && part.endsWith("?");
456
+ if (optional && pj < ph.length && walk(pi + 1, pj + 1)) return true;
457
+ if (!optional) {
458
+ if (pj >= ph.length) return false;
459
+ if (!part.startsWith(":") && part !== ph[pj]) return false;
460
+ return walk(pi + 1, pj + 1);
461
+ }
462
+ return walk(pi + 1, pj);
463
+ }
464
+
465
+ return walk(0, 0);
466
+ }
467
+
468
+ // The one place the base is stripped. Everything else in the router handles
469
+ // full browser paths (history, fetch, scroll keys, `__data.json`), and a path
470
+ // outside the base matches no route, so the browser loads it as a page.
471
+ function findPattern(pathname: string): string | null {
472
+ const route = stripBase(pathname);
473
+ if (route === null) return null;
474
+ for (const pattern of Object.keys(routeMap)) {
475
+ if (matchClientPattern(pattern, route)) return pattern;
476
+ }
477
+ return null;
478
+ }
479
+
480
+ /** The URL as routes and loads see it: the same on the server, which strips the base from the request. */
481
+ function routeUrl(url: URL): URL {
482
+ const route = new URL(url);
483
+ route.pathname = stripBase(url.pathname) ?? url.pathname;
484
+ return route;
485
+ }
486
+
487
+ export interface NavigateOptions {
488
+ /** "push" (default) adds a history entry, "replace" swaps the current one,
489
+ * "none" leaves history untouched (popstate — the browser already moved). */
490
+ history?: "push" | "replace" | "none";
491
+ }
492
+
493
+ // monotonically increasing id — a navigation aborts silently the moment a
494
+ // newer one starts, so overlapping navigations can't commit stale responses
495
+ let navigationId = 0;
496
+
497
+ export async function navigate(
498
+ path: string,
499
+ opts: NavigateOptions | boolean = {},
500
+ ) {
501
+ // boolean back-compat: navigate(path, true) meant "replace"
502
+ const historyMode =
503
+ typeof opts === "boolean"
504
+ ? opts
505
+ ? "replace"
506
+ : "push"
507
+ : (opts.history ?? "push");
508
+ const navId = ++navigationId;
509
+ const url = new URL(path, location.origin);
510
+ const seen = routeUrl(url);
511
+ if (
512
+ base &&
513
+ url.origin === location.origin &&
514
+ stripBase(url.pathname) === null
515
+ ) {
516
+ console.warn(
517
+ `[grimoire] navigate("${path}") is outside the base "${base}", so it loads as a new page and the server will not find it. Write navigate(withBase("${url.pathname}")).`,
518
+ );
519
+ }
520
+
521
+ if (beforeNavigateCb) {
522
+ const shouldProceed = beforeNavigateCb(seen);
523
+ if (shouldProceed === false) return;
524
+ }
525
+ onNavigateCb?.(seen);
526
+ saveScrollPosition();
527
+
528
+ // load the loading immediately
529
+ const destPattern = findPattern(url.pathname);
530
+ const DestPage = destPattern ? await resolveRoute(destPattern) : null;
531
+ if (navId !== navigationId) return;
532
+ if (DestPage?.loading) {
533
+ disposeCurrentPage?.();
534
+ disposeCurrentPage = null;
535
+ pushHydrationNodes([]);
536
+ let loadingNode: any;
537
+ let flush = () => {};
538
+ disposeCurrentPage = withEffectScope(() => {
539
+ ({ value: loadingNode, flush } = collectEffects(() =>
540
+ (DestPage as any).loading(),
541
+ ));
542
+ });
543
+ popHydrationNodes();
544
+ // replace only grimoire-page, keeps layout stable during transition
545
+ const pageEl = document.getElementById("grimoire-page");
546
+ if (pageEl) pageEl.replaceChildren(loadingNode);
547
+ else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
548
+ flush();
549
+ }
550
+
551
+ let res: Response;
552
+ try {
553
+ res = await (takePrefetched(path) ?? navigateFetch(path));
554
+ } catch {
555
+ // a failed prefetch must not fail the click
556
+ res = await navigateFetch(path);
557
+ }
558
+ if (navId !== navigationId) return;
559
+ const contentType = res.headers.get("content-type") ?? "";
560
+ if (!contentType.includes("application/json")) {
561
+ window.location.href = path;
562
+ return;
563
+ }
564
+ const json = await res.json();
565
+ if (navId !== navigationId) return;
566
+ const { data, layoutData, params, pattern, head, deps } = json;
567
+ const Page = await resolveRoute(pattern);
568
+ if (navId !== navigationId) return;
569
+ if (!Page) {
570
+ window.location.href = path;
571
+ return;
572
+ }
573
+
574
+ let mergedData = data;
575
+ if (Page.load) {
576
+ try {
577
+ startCollecting();
578
+ const clientData = await Page.load({
579
+ params,
580
+ url: seen,
581
+ request: new Request(seen),
582
+ // layout loads run server-side; their data arrives in layoutData —
583
+ // parent() merges it outermost-first, mirroring the server context
584
+ parent: async () =>
585
+ Object.assign(
586
+ {},
587
+ ...(Array.isArray(layoutData) ? layoutData : []).filter(
588
+ (d) => d && typeof d === "object",
589
+ ),
590
+ ),
591
+ });
592
+ // merge server-collected keys (page/layout server loads) with
593
+ // whatever this client-side load itself registered
594
+ setDeps(pattern, [
595
+ ...(Array.isArray(deps) ? deps : []),
596
+ ...stopCollecting(),
597
+ ]);
598
+ mergedData = { ...clientData, ...data };
599
+ } catch (e: unknown) {
600
+ stopCollecting();
601
+ if (e && typeof e === "object" && "location" in e) {
602
+ window.location.href = String((e as { location: unknown }).location);
603
+ return;
604
+ }
605
+ console.error("[grimoire] universal load error:", e);
606
+ }
607
+ if (navId !== navigationId) return;
608
+ } else if (Array.isArray(deps)) {
609
+ // no client-side load to run — the server's collected depends() keys
610
+ // (from +page.server.ts / +layout.server.ts) are the whole story
611
+ setDeps(pattern, deps);
612
+ }
613
+
614
+ // track state for HMR rerender
615
+ lastState = { data: mergedData, layoutData, params, pattern };
616
+ (globalThis as any).__grimoire_current_pattern__ = pattern;
617
+
618
+ disposeCurrentPage?.();
619
+ disposeCurrentPage = null;
620
+ pushHydrationNodes([]);
621
+ let rootNode: any;
622
+ // the page's effects (and use: directives) run once it is in the document
623
+ let flushEffects = () => {};
624
+ disposeCurrentPage = withEffectScope(() => {
625
+ try {
626
+ ({ value: rootNode, flush: flushEffects } = collectEffects(() =>
627
+ buildRouteTree(lastState!, Page),
628
+ ));
629
+ } catch (e) {
630
+ console.error(e);
631
+ }
632
+ });
633
+ popHydrationNodes();
634
+
635
+ updateHead(head);
636
+ // isRefetch is read before currentPath moves, and captured, because
637
+ // applyScroll may run after this function has returned.
638
+ const isRefetch = url.pathname === currentPath;
639
+
640
+ // Scroll has to be decided in the same frame the content lands. Running it
641
+ // here, outside doSwap, meant the hash lookup hit the *outgoing* DOM: a
642
+ // same-page anchor was already present and worked, while an anchor on the
643
+ // incoming page did not exist yet and fell through to scrollToTop().
644
+ const applyScroll = () => {
645
+ if (url.hash) {
646
+ const target = document.getElementById(url.hash.slice(1));
647
+ if (!target) {
648
+ scrollToTop();
649
+ return;
650
+ }
651
+ target.scrollIntoView();
652
+ // re-assert after layout settles (late effects/images can shift content)
653
+ requestAnimationFrame(() => target.scrollIntoView());
654
+ return;
655
+ }
656
+ if (historyMode === "none") {
657
+ // popstate: the browser already moved through history — restore what
658
+ // we saved for this path (back/forward semantics)
659
+ restoreScrollPosition(url.pathname);
660
+ return;
661
+ }
662
+ // fresh navigation starts at the top; a same-path replace
663
+ // (invalidate/refetch) keeps the current scroll
664
+ if (!isRefetch) scrollToTop();
665
+ };
666
+
667
+ // View transitions: animate the swap when the browser supports it and the
668
+ // user hasn't asked for reduced motion. The callback must stay synchronous.
669
+ const preserved = capturePreservedScroll();
670
+ const doc = document as Document & {
671
+ startViewTransition?: (
672
+ cb: () => void,
673
+ ) => { finished?: Promise<unknown>; ready?: Promise<unknown> } | undefined;
674
+ };
675
+ const animate =
676
+ typeof doc.startViewTransition === "function" &&
677
+ !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
678
+ // elements the old and new page share by key morph into each other
679
+ const shared = animate ? sharedTransitionKeys(rootNode) : [];
680
+ const named: Element[] = [];
681
+ const name = (el: Element, key: string) => {
682
+ (el as HTMLElement).style.setProperty("view-transition-name", key);
683
+ named.push(el);
684
+ };
685
+ const doSwap = () => {
686
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
687
+ flushEffects();
688
+ for (const [key, , next] of shared) name(next, key);
689
+ restorePreservedScroll(preserved);
690
+ applyScroll();
691
+ };
692
+ if (animate) {
693
+ // the browser snapshots the old page as startViewTransition is called
694
+ for (const [key, prev] of shared) name(prev, key);
695
+ const transition = doc.startViewTransition?.(doSwap);
696
+ const clear = () => {
697
+ for (const el of named)
698
+ (el as HTMLElement).style.removeProperty("view-transition-name");
699
+ };
700
+ Promise.resolve(transition?.finished).then(clear, clear);
701
+ // a skipped transition (another navigation, a hidden tab) rejects
702
+ // ready; the swap still runs, so it is not an error worth reporting
703
+ transition?.ready?.catch(() => {});
704
+ } else {
705
+ doSwap();
706
+ }
707
+ currentPath = url.pathname;
708
+ currentSearch = url.search;
709
+
710
+ if (historyMode !== "none") {
711
+ history[historyMode === "replace" ? "replaceState" : "pushState"](
712
+ null,
713
+ "",
714
+ path,
715
+ );
716
+ }
717
+ afterNavigateCb?.(seen);
718
+ }
719
+
720
+ export interface RouterExtensions {
721
+ /** [param=matcher] validators from src/params/*.ts (manifest-generated). */
722
+ matchers?: Record<string, (value: string) => boolean>;
723
+ /** Server-collected depends() keys per route pattern (from SSR state). */
724
+ deps?: Record<string, string[]>;
725
+ }
726
+
727
+ let paramMatcherFns: Record<string, (value: string) => boolean> = {};
728
+
729
+ export function initRouter(
730
+ routes: Record<string, RouteEntry>,
731
+ layouts: any[] = [],
732
+ initialDispose?: () => void,
733
+ ext?: RouterExtensions,
734
+ ) {
735
+ paramMatcherFns = ext?.matchers ?? {};
736
+ routeMap = routes;
737
+ layoutList = layouts;
738
+ prefetched.clear();
739
+ disposeCurrentPage = initialDispose ?? null;
740
+ currentPath = location.pathname;
741
+ currentSearch = location.search;
742
+
743
+ // the app owns scroll: the browser's automatic restoration fires after
744
+ // the router's own scroll and clobbers scroll-to-top / saved positions
745
+ if ("scrollRestoration" in history) history.scrollRestoration = "manual";
746
+ // dev HMR surface: available even without SSR state so the client can tell
747
+ // a missing router apart from a missing initial payload
748
+ const globals = globalThis as unknown as {
749
+ __grimoire_current_pattern__?: string;
750
+ __grimoire_routes__?: Record<string, RouteEntry>;
751
+ __grimoire_rerender__?: () => Promise<void>;
752
+ __grimoire_navigate__?: (path: string, replace?: boolean) => void;
753
+ __grimoire_form__?: (form: unknown) => Promise<void>;
754
+ __grimoire_hmr__?: HmrControl;
755
+ };
756
+ globals.__grimoire_routes__ = routeMap;
757
+ globals.__grimoire_rerender__ = hmrRerender;
758
+ globals.__grimoire_hmr__ = hmrControl;
759
+ globals.__grimoire_form__ = showActionFailure;
760
+ globals.__grimoire_navigate__ = (path, replace) =>
761
+ navigate(path, replace ?? false);
762
+
763
+ // initial HMR state from SSR
764
+ const stateEl = document.getElementById("__grimoire_state__");
765
+ if (stateEl) {
766
+ const state = JSON.parse(stateEl.textContent!);
767
+ lastState = {
768
+ data: state.data,
769
+ layoutData: state.layoutData,
770
+ params: state.params,
771
+ pattern: state.pattern,
772
+ form: state.form,
773
+ };
774
+ if (Array.isArray(state.deps)) {
775
+ setDeps(state.pattern, state.deps);
776
+ }
777
+ globals.__grimoire_current_pattern__ = state.pattern;
778
+ }
779
+
780
+ saveScrollPosition();
781
+ document.addEventListener("click", handleClick);
782
+ // forms rendered client-side have no SSR-injected _csrf input
783
+ document.addEventListener("submit", onSubmitEnsureCsrf, true);
784
+ window.addEventListener("popstate", () => {
785
+ if (
786
+ location.pathname === currentPath &&
787
+ location.search === currentSearch
788
+ ) {
789
+ return;
790
+ }
791
+ // the browser already moved through history — render only, never
792
+ // push/replace here or the forward stack gets clobbered.
793
+ // The search has to come along: refetching the bare pathname served
794
+ // unfiltered data while the address bar still showed the query.
795
+ // The hash deliberately does not, so back/forward restores the saved
796
+ // scroll offset instead of re-jumping to the anchor, matching the
797
+ // browser's own behaviour for document history navigation.
798
+ navigate(location.pathname + location.search, { history: "none" });
799
+ });
800
+ setupPreload();
801
+ }
802
+
803
+ /**
804
+ * Swap the page's <head> tags for the incoming page's. Server-rendered tags
805
+ * sit between `<!--grimoire-head-->` markers; tags added by an earlier
806
+ * navigation carry `data-grimoire-head`. Both are replaced, so the first
807
+ * navigation doesn't leave the server-rendered description or icon behind
808
+ * next to the new ones. With no incoming <title>, the current title stays.
809
+ */
810
+ function updateHead(headHtml: string) {
811
+ const prevTitle = document.title;
812
+ const markers = Array.from(document.head.childNodes).filter(
813
+ (n): n is Comment => n.nodeType === Node.COMMENT_NODE,
814
+ );
815
+ const start = markers.find((c) => c.data === "grimoire-head");
816
+ const end = markers.find((c) => c.data === "/grimoire-head");
817
+ if (start && end) {
818
+ while (start.nextSibling && start.nextSibling !== end) {
819
+ start.nextSibling.remove();
820
+ }
821
+ }
822
+ document
823
+ .querySelectorAll("[data-grimoire-head]")
824
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
825
+ .forEach((el) => el.remove());
826
+ const parsed = headHtml
827
+ ? new DOMParser().parseFromString(`<head>${headHtml}</head>`, "text/html")
828
+ : null;
829
+ const incomingTitle = parsed?.querySelector("title");
830
+ //biome-ignore lint/suspicious/useIterableCallbackReturn: shut up
831
+ document.querySelectorAll("title").forEach((el) => el.remove());
832
+ document.title = incomingTitle?.textContent ?? prevTitle;
833
+ if (parsed) {
834
+ for (const el of Array.from(parsed.head.children)) {
835
+ if (el.tagName === "TITLE") continue;
836
+ (el as HTMLElement).dataset.grimoireHead = "1";
837
+ if (end) document.head.insertBefore(el, end);
838
+ else document.head.appendChild(el);
839
+ }
840
+ }
841
+ }
842
+
843
+ function handleClick(e: MouseEvent) {
844
+ // let the browser handle modified clicks (new tab/window/download)
845
+ if (e.defaultPrevented || e.button !== 0) return;
846
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
847
+ const a = (e.target as Element).closest("a");
848
+ if (!a) return;
849
+ if (a.target && a.target !== "_self") return;
850
+ if (a.hasAttribute("download")) return;
851
+ if (a.getAttribute("rel")?.split(/\s+/).includes("external")) return;
852
+ const href = a.getAttribute("href");
853
+ if (!href) return;
854
+ if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
855
+ // Only intercept clicks for known page routes — let server routes
856
+ // (redirects, API endpoints, etc.) navigate normally so the browser
857
+ // follows the response without the extra fetch-then-redirect dance.
858
+ try {
859
+ const url = new URL(href, location.origin);
860
+ if (!findPattern(url.pathname)) return;
861
+ // same-page anchor: native behavior scrolls to it, no re-render needed
862
+ if (url.pathname === location.pathname && url.hash) return;
863
+ } catch {
864
+ return;
865
+ }
866
+ e.preventDefault();
867
+ // a pending hover prefetch would re-request what this click just consumed
868
+ clearTimeout(preloadTimer);
869
+ navigate(href);
870
+ }