@sigil-dev/grimoire 0.9.21 → 0.9.23

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