@sigil-dev/grimoire 0.9.14 → 0.9.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "private": false,
7
- "version": "0.9.14",
7
+ "version": "0.9.16",
8
8
  "exports": {
9
9
  ".": "./index.ts",
10
10
  "./server": "./server.ts",
@@ -23,8 +23,8 @@
23
23
  "test": "bun test"
24
24
  },
25
25
  "dependencies": {
26
- "@sigil-dev/compiler": "0.9.14",
27
- "@sigil-dev/runtime": "0.9.14",
26
+ "@sigil-dev/compiler": "0.9.16",
27
+ "@sigil-dev/runtime": "0.9.16",
28
28
  "vite": "^8.0.16"
29
29
  },
30
30
  "peerDependencies": {
@@ -1,4 +1,8 @@
1
- import { popHydrationNodes, pushHydrationNodes } from "@sigil-dev/runtime";
1
+ import {
2
+ collectEffects,
3
+ popHydrationNodes,
4
+ pushHydrationNodes,
5
+ } from "@sigil-dev/runtime";
2
6
  import { onSubmitEnsureCsrf } from "./csrf.ts";
3
7
  import {
4
8
  clearDeps,
@@ -91,12 +95,16 @@ export async function hmrRerender(): Promise<void> {
91
95
  disposeCurrentPage?.();
92
96
  pushHydrationNodes([]);
93
97
  let rootNode: any;
98
+ let flush = () => {};
94
99
  disposeCurrentPage = withEffectScope(() => {
95
- rootNode = buildRouteTree(lastState!, Page);
100
+ ({ value: rootNode, flush } = collectEffects(() =>
101
+ buildRouteTree(lastState!, Page),
102
+ ));
96
103
  });
97
104
  popHydrationNodes();
98
105
  const preserved = capturePreservedScroll();
99
106
  document.getElementById("grimoire-root")?.replaceChildren(rootNode);
107
+ flush();
100
108
  restorePreservedScroll(preserved);
101
109
  }
102
110
 
@@ -186,6 +194,40 @@ function restorePreservedScroll(positions: Map<string, number>): void {
186
194
  }
187
195
  }
188
196
 
197
+ const TRANSITION_ATTR = "data-sigil-transition";
198
+
199
+ /** key → the one element carrying it; keys that appear twice are dropped,
200
+ * because a duplicate view-transition-name cancels the whole transition. */
201
+ function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
202
+ const seen = new Map<string, Element>();
203
+ const dup = new Set<string>();
204
+ for (const el of root.querySelectorAll(`[${TRANSITION_ATTR}]`)) {
205
+ const key = el.getAttribute(TRANSITION_ATTR);
206
+ if (!key) continue;
207
+ if (seen.has(key)) dup.add(key);
208
+ else seen.set(key, el);
209
+ }
210
+ for (const key of dup) seen.delete(key);
211
+ return seen;
212
+ }
213
+
214
+ /** [key, element on the current page, element on the incoming page] */
215
+ function sharedTransitionKeys(
216
+ incoming: unknown,
217
+ ): Array<[string, Element, Element]> {
218
+ const root = incoming as Partial<ParentNode> | null;
219
+ if (!root || typeof root.querySelectorAll !== "function") return [];
220
+ const next = uniqueTransitionEls(root as ParentNode);
221
+ if (next.size === 0) return [];
222
+ const prev = uniqueTransitionEls(document);
223
+ const both: Array<[string, Element, Element]> = [];
224
+ for (const [key, el] of next) {
225
+ const old = prev.get(key);
226
+ if (old) both.push([key, old, el]);
227
+ }
228
+ return both;
229
+ }
230
+
189
231
  // C3: Preloading
190
232
  //
191
233
  // A prefetch keeps its in-flight Response here and navigate() consumes it.
@@ -196,6 +238,16 @@ let preloadTimer: Timer | null = null;
196
238
  const PREFETCH_TTL_MS = 15_000;
197
239
  const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
198
240
 
241
+ /**
242
+ * A held response is only valid for the cookies it was requested with: apps
243
+ * keep preferences (a language, a region, a theme) in cookies the server reads
244
+ * per request, so a page fetched before the visitor changed one is wrong
245
+ * after. Cookies the script can read are part of the key.
246
+ */
247
+ function prefetchKey(url: URL): string {
248
+ return `${url.pathname}${url.search}\n${typeof document === "undefined" ? "" : document.cookie}`;
249
+ }
250
+
199
251
  function navigateFetch(path: string, priority?: "low"): Promise<Response> {
200
252
  return fetch(path, {
201
253
  headers: { "x-grimoire-navigate": "1" },
@@ -227,23 +279,26 @@ function prefetchHref(a: Element | null): string | null {
227
279
  * response is held for a short while so the click that follows reuses it.
228
280
  */
229
281
  export function prefetch(href: string): void {
230
- const conn = (navigator as { connection?: { saveData?: boolean } }).connection;
282
+ const conn = (navigator as { connection?: { saveData?: boolean } })
283
+ .connection;
231
284
  if (conn?.saveData) return;
232
285
  const url = new URL(href, location.origin);
233
- const key = url.pathname + url.search;
286
+ // the page already on screen needs no warming
287
+ if (url.pathname === location.pathname && url.search === location.search)
288
+ return;
289
+ const key = prefetchKey(url);
234
290
  const hit = prefetched.get(key);
235
291
  if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
236
292
  const pattern = findPattern(url.pathname);
237
293
  if (pattern) void resolveRoute(pattern).catch(() => {});
238
- const res = navigateFetch(key, "low");
294
+ const res = navigateFetch(url.pathname + url.search, "low");
239
295
  res.catch(() => prefetched.delete(key));
240
296
  prefetched.set(key, { res, at: Date.now() });
241
297
  }
242
298
 
243
299
  /** The held prefetch for `path` if it is still fresh; each is used once. */
244
300
  function takePrefetched(path: string): Promise<Response> | null {
245
- const url = new URL(path, location.origin);
246
- const key = url.pathname + url.search;
301
+ const key = prefetchKey(new URL(path, location.origin));
247
302
  const hit = prefetched.get(key);
248
303
  prefetched.delete(key);
249
304
  if (!hit || Date.now() - hit.at >= PREFETCH_TTL_MS) return null;
@@ -429,14 +484,18 @@ export async function navigate(
429
484
  disposeCurrentPage = null;
430
485
  pushHydrationNodes([]);
431
486
  let loadingNode: any;
487
+ let flush = () => {};
432
488
  disposeCurrentPage = withEffectScope(() => {
433
- loadingNode = (DestPage as any).loading();
489
+ ({ value: loadingNode, flush } = collectEffects(() =>
490
+ (DestPage as any).loading(),
491
+ ));
434
492
  });
435
493
  popHydrationNodes();
436
494
  // replace only grimoire-page, keeps layout stable during transition
437
495
  const pageEl = document.getElementById("grimoire-page");
438
496
  if (pageEl) pageEl.replaceChildren(loadingNode);
439
497
  else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
498
+ flush();
440
499
  }
441
500
 
442
501
  let res: Response;
@@ -510,9 +569,13 @@ export async function navigate(
510
569
  disposeCurrentPage = null;
511
570
  pushHydrationNodes([]);
512
571
  let rootNode: any;
572
+ // the page's effects (and use: directives) run once it is in the document
573
+ let flushEffects = () => {};
513
574
  disposeCurrentPage = withEffectScope(() => {
514
575
  try {
515
- rootNode = buildRouteTree(lastState!, Page);
576
+ ({ value: rootNode, flush: flushEffects } = collectEffects(() =>
577
+ buildRouteTree(lastState!, Page),
578
+ ));
516
579
  } catch (e) {
517
580
  console.error(e);
518
581
  }
@@ -554,19 +617,37 @@ export async function navigate(
554
617
  // View transitions: animate the swap when the browser supports it and the
555
618
  // user hasn't asked for reduced motion. The callback must stay synchronous.
556
619
  const preserved = capturePreservedScroll();
620
+ const doc = document as Document & {
621
+ startViewTransition?: (
622
+ cb: () => void,
623
+ ) => { finished?: Promise<unknown> } | undefined;
624
+ };
625
+ const animate =
626
+ typeof doc.startViewTransition === "function" &&
627
+ !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
628
+ // elements the old and new page share by key morph into each other
629
+ const shared = animate ? sharedTransitionKeys(rootNode) : [];
630
+ const named: Element[] = [];
631
+ const name = (el: Element, key: string) => {
632
+ (el as HTMLElement).style.setProperty("view-transition-name", key);
633
+ named.push(el);
634
+ };
557
635
  const doSwap = () => {
558
636
  document.getElementById("grimoire-root")?.replaceChildren(rootNode);
637
+ flushEffects();
638
+ for (const [key, , next] of shared) name(next, key);
559
639
  restorePreservedScroll(preserved);
560
640
  applyScroll();
561
641
  };
562
- const doc = document as Document & {
563
- startViewTransition?: (cb: () => void) => unknown;
564
- };
565
- if (
566
- typeof doc.startViewTransition === "function" &&
567
- !window.matchMedia("(prefers-reduced-motion: reduce)").matches
568
- ) {
569
- doc.startViewTransition(doSwap);
642
+ if (animate) {
643
+ // the browser snapshots the old page as startViewTransition is called
644
+ for (const [key, prev] of shared) name(prev, key);
645
+ const transition = doc.startViewTransition?.(doSwap);
646
+ const clear = () => {
647
+ for (const el of named)
648
+ (el as HTMLElement).style.removeProperty("view-transition-name");
649
+ };
650
+ Promise.resolve(transition?.finished).then(clear, clear);
570
651
  } else {
571
652
  doSwap();
572
653
  }
@@ -727,5 +808,7 @@ function handleClick(e: MouseEvent) {
727
808
  return;
728
809
  }
729
810
  e.preventDefault();
811
+ // a pending hover prefetch would re-request what this click just consumed
812
+ clearTimeout(preloadTimer);
730
813
  navigate(href);
731
814
  }
@@ -6,6 +6,10 @@
6
6
  * gets `loading="lazy"` and `decoding="async"` so a long grid of thumbnails
7
7
  * does not compete with the stylesheet and scripts for the first seconds of
8
8
  * bandwidth. An author's own `loading` / `decoding` always wins.
9
+ *
10
+ * `data-sigil-priority` marks the image that should paint first (the hero,
11
+ * the likely largest paint): it stays eager and is fetched at high priority,
12
+ * and does not count toward the eager budget above.
9
13
  */
10
14
  export const EAGER_IMAGE_COUNT = 4;
11
15
 
@@ -17,6 +21,11 @@ export function optimizeImages(html: string): string {
17
21
  if (!html.includes("<img")) return html;
18
22
  let seen = 0;
19
23
  const tag = (t: string) => {
24
+ if (/\sdata-sigil-priority\b/i.test(t)) {
25
+ return /\sfetchpriority\s*=/i.test(t)
26
+ ? t
27
+ : t.replace(/(\s*\/?>)$/, ' fetchpriority="high"$1');
28
+ }
20
29
  if (seen++ < EAGER_IMAGE_COUNT) return t;
21
30
  let extra = "";
22
31
  if (!/\sloading\s*=/i.test(t)) extra += ' loading="lazy"';
@@ -1,4 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import { preloadLinks } from "./preload.ts";
3
+ import { createTimer } from "./timing.ts";
2
4
  import { optimizeImages } from "./images.ts";
3
5
  import { SafeHtml } from "@sigil-dev/runtime";
4
6
  import { startCollecting, stopCollecting } from "../client/deps";
@@ -289,6 +291,7 @@ export async function renderRoute(
289
291
  parent: async () => ({}),
290
292
  };
291
293
 
294
+ const timer = createTimer();
292
295
  initHead(cspNonce);
293
296
  const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
294
297
 
@@ -415,6 +418,20 @@ export async function renderRoute(
415
418
  }
416
419
  }
417
420
 
421
+ // no page at this address: its layouts are loaded, the 404 goes in them
422
+ if (matched.notFound)
423
+ return (
424
+ (await renderErrorPage(
425
+ errorRoutes,
426
+ context.url.pathname,
427
+ 404,
428
+ "Not Found",
429
+ null,
430
+ loadModule,
431
+ { layoutPairs, params: matched.params, nonceAttr, dev },
432
+ )) ?? new Response("Not Found", { status: 404 })
433
+ );
434
+
418
435
  // page loads see every layout's data merged
419
436
  context.parent = async () => ({ ...parentData });
420
437
 
@@ -510,7 +527,7 @@ export async function renderRoute(
510
527
  async start(controller) {
511
528
  // 1. skeleton + loading shell — browser paints immediately
512
529
  controller.enqueue(
513
- `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
530
+ `${buildHtmlSkeleton(nonceAttr, dev)}${preloadLinks(matched.route.path, nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
514
531
  </head>
515
532
  <body>
516
533
  <div id="app">${loadingBody}`,
@@ -614,6 +631,7 @@ export async function renderRoute(
614
631
  : pageData;
615
632
  extractDeferred(mergedData, deferred, deferredCounter);
616
633
 
634
+ timer.mark("load");
617
635
  const pageHtml = await Promise.resolve(
618
636
  pageMod.default({
619
637
  data: renderable(mergedData),
@@ -627,6 +645,7 @@ export async function renderRoute(
627
645
  // defaults) only registers once the layout itself has run, so
628
646
  // collecting too early silently drops it
629
647
  let bodyHtml = applyLayouts(String(pageHtml));
648
+ timer.mark("render");
630
649
 
631
650
  const headHtml = collectHead();
632
651
 
@@ -645,6 +664,7 @@ export async function renderRoute(
645
664
  // raw state payloads rendering as the page after a back navigation.
646
665
  // Deliberately still cacheable: hover-prefetch exists to warm this
647
666
  // entry, and Vary already keeps document requests from matching it.
667
+ timer.mark("deferred");
648
668
  return Response.json(
649
669
  {
650
670
  data: mergedData ?? {},
@@ -654,7 +674,7 @@ export async function renderRoute(
654
674
  head: headHtml,
655
675
  deps: [...collectedDeps],
656
676
  },
657
- { headers: { Vary: NAVIGATE_HEADER } },
677
+ { headers: { Vary: NAVIGATE_HEADER, ...timer.headers() } },
658
678
  );
659
679
  }
660
680
 
@@ -676,7 +696,10 @@ export async function renderRoute(
676
696
 
677
697
  const stream = new ReadableStream({
678
698
  async start(controller) {
679
- controller.enqueue(buildHtmlSkeleton(nonceAttr, dev));
699
+ controller.enqueue(
700
+ buildHtmlSkeleton(nonceAttr, dev) +
701
+ preloadLinks(matched.route.path, nonceAttr, dev),
702
+ );
680
703
 
681
704
  if (hoistedCss) {
682
705
  controller.enqueue(`\n ${hoistedCss}`);
@@ -713,6 +736,7 @@ export async function renderRoute(
713
736
  "Content-Type": "text/html",
714
737
  "Set-Cookie": csrfCookie(csrfToken),
715
738
  Vary: NAVIGATE_HEADER,
739
+ ...timer.headers(),
716
740
  },
717
741
  });
718
742
  });
@@ -0,0 +1,94 @@
1
+ /**
2
+ * `<link rel="modulepreload">` for the chunks a route needs.
3
+ *
4
+ * The client bundle loads a route's code with a lazy `import()`, which only
5
+ * starts once hydrate.js has downloaded and run: HTML, then hydrate.js, then
6
+ * the route chunk, then whatever that chunk imports. Naming those chunks in
7
+ * the HTML lets the browser fetch them alongside hydrate.js instead of behind
8
+ * it.
9
+ *
10
+ * The chunk graph is read back out of the built hydrate.js (the bundler
11
+ * writes it there for its own preloading), so no build step has to cooperate.
12
+ */
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+
16
+ interface ChunkGraph {
17
+ /** route pattern → chunk id */
18
+ routes: Map<string, string>;
19
+ /** chunk id → [file, ...ids it imports] */
20
+ nodes: Map<string, { file: string; deps: string[] }>;
21
+ }
22
+
23
+ const BASE = "/__grimoire__/";
24
+ let graph: ChunkGraph | null | undefined;
25
+
26
+ export function parseChunkGraph(source: string): ChunkGraph | null {
27
+ const call = /^__chunks\(import\.meta\.url,(\[.*?\]),(\[\[.*?\]\]),(\d+)\)/m.exec(
28
+ source,
29
+ );
30
+ if (!call) return null;
31
+ let ids: string[];
32
+ let raw: Array<Array<string | number>>;
33
+ try {
34
+ ids = JSON.parse(call[1]);
35
+ raw = JSON.parse(call[2]);
36
+ } catch {
37
+ return null;
38
+ }
39
+ const nodes: ChunkGraph["nodes"] = new Map();
40
+ ids.forEach((id, i) => {
41
+ const [file, ...deps] = raw[i] ?? [];
42
+ if (typeof file !== "string") return;
43
+ nodes.set(id, { file, deps: deps.map((d) => ids[Number(d)]).filter(Boolean) });
44
+ });
45
+ const routes = new Map<string, string>();
46
+ for (const m of source.matchAll(
47
+ /^\s*("(?:[^"\\]|\\.)*"):\s*\{\s*__lazy:\s*\(\)\s*=>\s*\(__preload\("([^"]+)"\)/gm,
48
+ )) {
49
+ routes.set(JSON.parse(m[1]), m[2]);
50
+ }
51
+ return { routes, nodes };
52
+ }
53
+
54
+ function load(): ChunkGraph | null {
55
+ if (graph !== undefined) return graph;
56
+ const file = join(process.cwd(), "public", "__grimoire__", "hydrate.js");
57
+ graph = existsSync(file) ? parseChunkGraph(readFileSync(file, "utf-8")) : null;
58
+ return graph;
59
+ }
60
+
61
+ /** Files (relative to /__grimoire__/) the route's chunk needs, closure included. */
62
+ export function chunksFor(g: ChunkGraph, pattern: string): string[] {
63
+ const start = g.routes.get(pattern);
64
+ if (!start) return [];
65
+ const seen = new Set<string>();
66
+ const stack = [start];
67
+ const files: string[] = [];
68
+ while (stack.length) {
69
+ const id = stack.pop() as string;
70
+ if (seen.has(id)) continue;
71
+ seen.add(id);
72
+ const node = g.nodes.get(id);
73
+ if (!node) continue;
74
+ // hydrate.js itself is already a <script> in the head
75
+ if (!/(^|\/)hydrate\.js$/.test(node.file)) files.push(node.file.replace(/^\.\//, ""));
76
+ stack.push(...node.deps);
77
+ }
78
+ return files;
79
+ }
80
+
81
+ /** The preload tags for a route, or "" in dev / when there is no built graph. */
82
+ export function preloadLinks(pattern: string, nonceAttr: string, dev?: boolean): string {
83
+ if (dev) return "";
84
+ const g = load();
85
+ if (!g) return "";
86
+ return chunksFor(g, pattern)
87
+ .map((f) => `\n <link rel="modulepreload" href="${BASE}${f}" crossorigin${nonceAttr}>`)
88
+ .join("");
89
+ }
90
+
91
+ /** For tests: forget the cached graph. */
92
+ export function resetChunkGraph(): void {
93
+ graph = undefined;
94
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `Server-Timing` for route renders, so the browser's network panel shows
3
+ * where a slow page spent its time (`load` = layout and page server loads,
4
+ * `render` = components to HTML) without any extra tooling.
5
+ *
6
+ * On in dev; in production only when `serverTiming: true`, since durations are
7
+ * visible to every visitor.
8
+ */
9
+ let enabled = false;
10
+
11
+ export function setServerTiming(on: boolean): void {
12
+ enabled = on;
13
+ }
14
+
15
+ export interface Timer {
16
+ /** Close the phase that has been running since the last mark. */
17
+ mark(name: string): void;
18
+ /** `{ "Server-Timing": ... }`, or nothing when disabled or no marks. */
19
+ headers(): Record<string, string>;
20
+ }
21
+
22
+ export function createTimer(): Timer {
23
+ const marks: Array<[string, number]> = [];
24
+ let last = performance.now();
25
+ return {
26
+ mark(name) {
27
+ const now = performance.now();
28
+ marks.push([name, now - last]);
29
+ last = now;
30
+ },
31
+ headers() {
32
+ if (!enabled || marks.length === 0) return {};
33
+ return {
34
+ "Server-Timing": marks
35
+ .map(([n, d]) => `${n};dur=${d.toFixed(1)}`)
36
+ .join(", "),
37
+ };
38
+ },
39
+ };
40
+ }
@@ -6,6 +6,8 @@ export interface MatchedRoute {
6
6
  layouts: RouteFile[]; // was: layout?: RouteFile
7
7
  layoutServers: RouteFile[]; // was: layoutServer?: RouteFile
8
8
  pageServer?: RouteFile;
9
+ /** No page has this address: the layouts that cover it render the closest +error.tsx with a 404. */
10
+ notFound?: boolean;
9
11
  }
10
12
 
11
13
  export function matchRoute(
@@ -68,23 +70,72 @@ export function matchRoute(
68
70
  return null;
69
71
  }
70
72
 
73
+ /** Whether a folder's pattern (a layout's or an error page's path) covers pathname. */
74
+ function covers(
75
+ folder: string,
76
+ pathname: string,
77
+ ): Record<string, string> | null {
78
+ if (folder === "/" || folder === "") return {};
79
+ const params = matchPattern(`${folder.replace(/\/$/, "")}/*__rest`, pathname);
80
+ if (params) delete params.__rest;
81
+ return params;
82
+ }
83
+
84
+ /** How specific a folder pattern is: deeper first, then fixed segments over params. */
85
+ function depth(folder: string): number {
86
+ const parts = folder.split("/").filter(Boolean);
87
+ return (
88
+ parts.length * 2 -
89
+ (parts.some((p) => p.startsWith(":") || p.startsWith("*")) ? 1 : 0)
90
+ );
91
+ }
92
+
93
+ /**
94
+ * The +error.tsx closest to pathname: the deepest folder whose pattern covers
95
+ * it, so routes/events/[id]/+error.tsx catches /events/42/anything.
96
+ */
71
97
  export function findClosestError(
72
98
  errors: RouteFile[],
73
99
  pathname: string,
74
100
  ): RouteFile | null {
75
- const segments = pathname.split("/").filter(Boolean);
76
-
77
- // walk from most specific to root
78
- while (segments.length >= 0) {
79
- const prefix = `/${segments.join("/")}`;
80
- const error = errors.find(
81
- (e) => e.path === prefix || e.path === `${prefix}/`,
82
- );
83
- if (error) return error;
84
- if (segments.length === 0) break;
85
- segments.pop();
101
+ let best: RouteFile | null = null;
102
+ let bestDepth = -1;
103
+ for (const e of errors) {
104
+ const d = depth(e.path);
105
+ if (d > bestDepth && covers(e.path, pathname)) {
106
+ best = e;
107
+ bestDepth = d;
108
+ }
86
109
  }
87
- return null;
110
+ return best;
111
+ }
112
+
113
+ /**
114
+ * A match for an address no page has: the layouts (and their server loads)
115
+ * of every folder that covers it, so the 404 renders the closest +error.tsx
116
+ * inside the site's own layout, exactly like a page whose load throws
117
+ * error(404). Without this an unknown address got the error page bare.
118
+ */
119
+ export function matchNotFound(tree: RouteTree, url: URL): MatchedRoute {
120
+ const pathname = url.pathname;
121
+ const params: Record<string, string> = {};
122
+ const within = (l: RouteFile) => {
123
+ const p = covers(l.path, pathname);
124
+ if (p) Object.assign(params, p);
125
+ return p !== null;
126
+ };
127
+ const byDepth = (a: RouteFile, b: RouteFile) => a.path.length - b.path.length;
128
+ return {
129
+ route: { path: pathname, filePath: "", type: "page" } as RouteFile,
130
+ params,
131
+ layouts: tree.layouts
132
+ .filter((l) => l.type === "layout" && within(l))
133
+ .sort(byDepth),
134
+ layoutServers: tree.layouts
135
+ .filter((l) => l.type === "layoutServer" && within(l))
136
+ .sort(byDepth),
137
+ notFound: true,
138
+ };
88
139
  }
89
140
 
90
141
  function matchPattern(
@@ -0,0 +1,114 @@
1
+ /**
2
+ * In-memory stale-while-revalidate cache for expensive server-side values.
3
+ *
4
+ * The common hand-rolled version is "if the entry is older than an hour,
5
+ * rebuild it inline", which makes one unlucky visitor per hour (per worker)
6
+ * wait for the rebuild. Here, once a value exists it is always returned at
7
+ * once; an expired one is refreshed in the background, by a single shared
8
+ * call, while callers keep getting the old value.
9
+ *
10
+ * const costumeIndex = cached(() => buildIndex(), { ttl: 3600_000 });
11
+ * const index = await costumeIndex();
12
+ *
13
+ * const player = cachedBy((id: string) => fetchPlayer(id), { ttl: 60_000 });
14
+ * await player("123");
15
+ */
16
+
17
+ export interface CachedOptions {
18
+ /** How long (ms) a value is fresh. */
19
+ ttl: number;
20
+ /**
21
+ * How long (ms) past `ttl` a stale value may still be served while the
22
+ * refresh runs. Past it, the next caller waits. Default: forever.
23
+ */
24
+ staleFor?: number;
25
+ /** cachedBy only: the most keys held; the least recently used goes first. */
26
+ max?: number;
27
+ /** Called when a background refresh fails; the stale value stays. */
28
+ onError?: (error: unknown) => void;
29
+ }
30
+
31
+ interface Entry<T> {
32
+ value: T;
33
+ at: number;
34
+ }
35
+
36
+ export interface CachedFn<A extends unknown[], T> {
37
+ (...args: A): Promise<T>;
38
+ /** Drop one entry (or all with no argument); the next call refetches. */
39
+ invalidate(...args: A | []): void;
40
+ }
41
+
42
+ function build<A extends unknown[], T>(
43
+ fn: (...args: A) => Promise<T>,
44
+ keyOf: (args: A) => string,
45
+ opts: CachedOptions,
46
+ ): CachedFn<A, T> {
47
+ const { ttl, staleFor = Number.POSITIVE_INFINITY, max = 500, onError } = opts;
48
+ const entries = new Map<string, Entry<T>>();
49
+ const running = new Map<string, Promise<T>>();
50
+
51
+ function refresh(key: string, args: A): Promise<T> {
52
+ const existing = running.get(key);
53
+ if (existing) return existing;
54
+ const p = fn(...args).then(
55
+ (value) => {
56
+ running.delete(key);
57
+ entries.delete(key); // re-insert so insertion order = recency
58
+ entries.set(key, { value, at: Date.now() });
59
+ while (entries.size > max) {
60
+ const oldest = entries.keys().next().value as string;
61
+ entries.delete(oldest);
62
+ }
63
+ return value;
64
+ },
65
+ (e) => {
66
+ running.delete(key);
67
+ throw e;
68
+ },
69
+ );
70
+ running.set(key, p);
71
+ return p;
72
+ }
73
+
74
+ const call = ((...args: A): Promise<T> => {
75
+ const key = keyOf(args);
76
+ const hit = entries.get(key);
77
+ if (hit) {
78
+ const age = Date.now() - hit.at;
79
+ entries.delete(key); // a read counts as use
80
+ entries.set(key, hit);
81
+ if (age < ttl) return Promise.resolve(hit.value);
82
+ if (age < ttl + staleFor) {
83
+ refresh(key, args).catch((e) => onError?.(e));
84
+ return Promise.resolve(hit.value);
85
+ }
86
+ }
87
+ return refresh(key, args);
88
+ }) as CachedFn<A, T>;
89
+
90
+ call.invalidate = (...args: A | []) => {
91
+ if (args.length === 0) {
92
+ entries.clear();
93
+ return;
94
+ }
95
+ entries.delete(keyOf(args as A));
96
+ };
97
+ return call;
98
+ }
99
+
100
+ /** A value with no arguments, cached process-wide. */
101
+ export function cached<T>(
102
+ fn: () => Promise<T>,
103
+ opts: CachedOptions,
104
+ ): CachedFn<[], T> {
105
+ return build(fn, () => "", opts);
106
+ }
107
+
108
+ /** A value per argument list (compared as JSON), with an LRU cap. */
109
+ export function cachedBy<A extends unknown[], T>(
110
+ fn: (...args: A) => Promise<T>,
111
+ opts: CachedOptions,
112
+ ): CachedFn<A, T> {
113
+ return build(fn, (args) => JSON.stringify(args), opts);
114
+ }