@sigil-dev/grimoire 0.9.14 → 0.9.15
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 +3 -3
- package/src/client/router.ts +71 -12
- package/src/rendering/images.ts +9 -0
- package/src/rendering/index.ts +13 -3
- package/src/rendering/preload.ts +94 -0
- package/src/rendering/timing.ts +40 -0
- package/src/server/cached.ts +114 -0
- package/src/server/index.ts +41 -4
- package/src/server/warm.ts +91 -0
- package/src/server/worker.ts +1 -0
- package/src/types.ts +14 -0
- package/test/cached.test.ts +126 -0
- package/test/client-router.test.ts +132 -0
- package/test/images.test.ts +15 -0
- package/test/preload.test.ts +48 -0
- package/test/rendering.test.ts +33 -0
- package/test/warm.test.ts +96 -0
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.
|
|
7
|
+
"version": "0.9.15",
|
|
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.
|
|
27
|
-
"@sigil-dev/runtime": "0.9.
|
|
26
|
+
"@sigil-dev/compiler": "0.9.15",
|
|
27
|
+
"@sigil-dev/runtime": "0.9.15",
|
|
28
28
|
"vite": "^8.0.16"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
package/src/client/router.ts
CHANGED
|
@@ -186,6 +186,38 @@ function restorePreservedScroll(positions: Map<string, number>): void {
|
|
|
186
186
|
}
|
|
187
187
|
}
|
|
188
188
|
|
|
189
|
+
const TRANSITION_ATTR = "data-sigil-transition";
|
|
190
|
+
|
|
191
|
+
/** key → the one element carrying it; keys that appear twice are dropped,
|
|
192
|
+
* because a duplicate view-transition-name cancels the whole transition. */
|
|
193
|
+
function uniqueTransitionEls(root: ParentNode): Map<string, Element> {
|
|
194
|
+
const seen = new Map<string, Element>();
|
|
195
|
+
const dup = new Set<string>();
|
|
196
|
+
for (const el of root.querySelectorAll(`[${TRANSITION_ATTR}]`)) {
|
|
197
|
+
const key = el.getAttribute(TRANSITION_ATTR);
|
|
198
|
+
if (!key) continue;
|
|
199
|
+
if (seen.has(key)) dup.add(key);
|
|
200
|
+
else seen.set(key, el);
|
|
201
|
+
}
|
|
202
|
+
for (const key of dup) seen.delete(key);
|
|
203
|
+
return seen;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** [key, element on the current page, element on the incoming page] */
|
|
207
|
+
function sharedTransitionKeys(incoming: unknown): Array<[string, Element, Element]> {
|
|
208
|
+
const root = incoming as Partial<ParentNode> | null;
|
|
209
|
+
if (!root || typeof root.querySelectorAll !== "function") return [];
|
|
210
|
+
const next = uniqueTransitionEls(root as ParentNode);
|
|
211
|
+
if (next.size === 0) return [];
|
|
212
|
+
const prev = uniqueTransitionEls(document);
|
|
213
|
+
const both: Array<[string, Element, Element]> = [];
|
|
214
|
+
for (const [key, el] of next) {
|
|
215
|
+
const old = prev.get(key);
|
|
216
|
+
if (old) both.push([key, old, el]);
|
|
217
|
+
}
|
|
218
|
+
return both;
|
|
219
|
+
}
|
|
220
|
+
|
|
189
221
|
// C3: Preloading
|
|
190
222
|
//
|
|
191
223
|
// A prefetch keeps its in-flight Response here and navigate() consumes it.
|
|
@@ -196,6 +228,16 @@ let preloadTimer: Timer | null = null;
|
|
|
196
228
|
const PREFETCH_TTL_MS = 15_000;
|
|
197
229
|
const prefetched = new Map<string, { res: Promise<Response>; at: number }>();
|
|
198
230
|
|
|
231
|
+
/**
|
|
232
|
+
* A held response is only valid for the cookies it was requested with: apps
|
|
233
|
+
* keep preferences (a language, a region, a theme) in cookies the server reads
|
|
234
|
+
* per request, so a page fetched before the visitor changed one is wrong
|
|
235
|
+
* after. Cookies the script can read are part of the key.
|
|
236
|
+
*/
|
|
237
|
+
function prefetchKey(url: URL): string {
|
|
238
|
+
return `${url.pathname}${url.search}\n${typeof document === "undefined" ? "" : document.cookie}`;
|
|
239
|
+
}
|
|
240
|
+
|
|
199
241
|
function navigateFetch(path: string, priority?: "low"): Promise<Response> {
|
|
200
242
|
return fetch(path, {
|
|
201
243
|
headers: { "x-grimoire-navigate": "1" },
|
|
@@ -230,20 +272,21 @@ export function prefetch(href: string): void {
|
|
|
230
272
|
const conn = (navigator as { connection?: { saveData?: boolean } }).connection;
|
|
231
273
|
if (conn?.saveData) return;
|
|
232
274
|
const url = new URL(href, location.origin);
|
|
233
|
-
|
|
275
|
+
// the page already on screen needs no warming
|
|
276
|
+
if (url.pathname === location.pathname && url.search === location.search) return;
|
|
277
|
+
const key = prefetchKey(url);
|
|
234
278
|
const hit = prefetched.get(key);
|
|
235
279
|
if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
|
|
236
280
|
const pattern = findPattern(url.pathname);
|
|
237
281
|
if (pattern) void resolveRoute(pattern).catch(() => {});
|
|
238
|
-
const res = navigateFetch(
|
|
282
|
+
const res = navigateFetch(url.pathname + url.search, "low");
|
|
239
283
|
res.catch(() => prefetched.delete(key));
|
|
240
284
|
prefetched.set(key, { res, at: Date.now() });
|
|
241
285
|
}
|
|
242
286
|
|
|
243
287
|
/** The held prefetch for `path` if it is still fresh; each is used once. */
|
|
244
288
|
function takePrefetched(path: string): Promise<Response> | null {
|
|
245
|
-
const
|
|
246
|
-
const key = url.pathname + url.search;
|
|
289
|
+
const key = prefetchKey(new URL(path, location.origin));
|
|
247
290
|
const hit = prefetched.get(key);
|
|
248
291
|
prefetched.delete(key);
|
|
249
292
|
if (!hit || Date.now() - hit.at >= PREFETCH_TTL_MS) return null;
|
|
@@ -554,19 +597,33 @@ export async function navigate(
|
|
|
554
597
|
// View transitions: animate the swap when the browser supports it and the
|
|
555
598
|
// user hasn't asked for reduced motion. The callback must stay synchronous.
|
|
556
599
|
const preserved = capturePreservedScroll();
|
|
600
|
+
const doc = document as Document & {
|
|
601
|
+
startViewTransition?: (cb: () => void) => { finished?: Promise<unknown> } | undefined;
|
|
602
|
+
};
|
|
603
|
+
const animate =
|
|
604
|
+
typeof doc.startViewTransition === "function" &&
|
|
605
|
+
!window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
606
|
+
// elements the old and new page share by key morph into each other
|
|
607
|
+
const shared = animate ? sharedTransitionKeys(rootNode) : [];
|
|
608
|
+
const named: Element[] = [];
|
|
609
|
+
const name = (el: Element, key: string) => {
|
|
610
|
+
(el as HTMLElement).style.setProperty("view-transition-name", key);
|
|
611
|
+
named.push(el);
|
|
612
|
+
};
|
|
557
613
|
const doSwap = () => {
|
|
558
614
|
document.getElementById("grimoire-root")?.replaceChildren(rootNode);
|
|
615
|
+
for (const [key, , next] of shared) name(next, key);
|
|
559
616
|
restorePreservedScroll(preserved);
|
|
560
617
|
applyScroll();
|
|
561
618
|
};
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
619
|
+
if (animate) {
|
|
620
|
+
// the browser snapshots the old page as startViewTransition is called
|
|
621
|
+
for (const [key, prev] of shared) name(prev, key);
|
|
622
|
+
const transition = doc.startViewTransition?.(doSwap);
|
|
623
|
+
const clear = () => {
|
|
624
|
+
for (const el of named) (el as HTMLElement).style.removeProperty("view-transition-name");
|
|
625
|
+
};
|
|
626
|
+
Promise.resolve(transition?.finished).then(clear, clear);
|
|
570
627
|
} else {
|
|
571
628
|
doSwap();
|
|
572
629
|
}
|
|
@@ -727,5 +784,7 @@ function handleClick(e: MouseEvent) {
|
|
|
727
784
|
return;
|
|
728
785
|
}
|
|
729
786
|
e.preventDefault();
|
|
787
|
+
// a pending hover prefetch would re-request what this click just consumed
|
|
788
|
+
clearTimeout(preloadTimer);
|
|
730
789
|
navigate(href);
|
|
731
790
|
}
|
package/src/rendering/images.ts
CHANGED
|
@@ -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"';
|
package/src/rendering/index.ts
CHANGED
|
@@ -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
|
|
|
@@ -510,7 +513,7 @@ export async function renderRoute(
|
|
|
510
513
|
async start(controller) {
|
|
511
514
|
// 1. skeleton + loading shell — browser paints immediately
|
|
512
515
|
controller.enqueue(
|
|
513
|
-
`${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
|
|
516
|
+
`${buildHtmlSkeleton(nonceAttr, dev)}${preloadLinks(matched.route.path, nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
|
|
514
517
|
</head>
|
|
515
518
|
<body>
|
|
516
519
|
<div id="app">${loadingBody}`,
|
|
@@ -614,6 +617,7 @@ export async function renderRoute(
|
|
|
614
617
|
: pageData;
|
|
615
618
|
extractDeferred(mergedData, deferred, deferredCounter);
|
|
616
619
|
|
|
620
|
+
timer.mark("load");
|
|
617
621
|
const pageHtml = await Promise.resolve(
|
|
618
622
|
pageMod.default({
|
|
619
623
|
data: renderable(mergedData),
|
|
@@ -627,6 +631,7 @@ export async function renderRoute(
|
|
|
627
631
|
// defaults) only registers once the layout itself has run, so
|
|
628
632
|
// collecting too early silently drops it
|
|
629
633
|
let bodyHtml = applyLayouts(String(pageHtml));
|
|
634
|
+
timer.mark("render");
|
|
630
635
|
|
|
631
636
|
const headHtml = collectHead();
|
|
632
637
|
|
|
@@ -645,6 +650,7 @@ export async function renderRoute(
|
|
|
645
650
|
// raw state payloads rendering as the page after a back navigation.
|
|
646
651
|
// Deliberately still cacheable: hover-prefetch exists to warm this
|
|
647
652
|
// entry, and Vary already keeps document requests from matching it.
|
|
653
|
+
timer.mark("deferred");
|
|
648
654
|
return Response.json(
|
|
649
655
|
{
|
|
650
656
|
data: mergedData ?? {},
|
|
@@ -654,7 +660,7 @@ export async function renderRoute(
|
|
|
654
660
|
head: headHtml,
|
|
655
661
|
deps: [...collectedDeps],
|
|
656
662
|
},
|
|
657
|
-
{ headers: { Vary: NAVIGATE_HEADER } },
|
|
663
|
+
{ headers: { Vary: NAVIGATE_HEADER, ...timer.headers() } },
|
|
658
664
|
);
|
|
659
665
|
}
|
|
660
666
|
|
|
@@ -676,7 +682,10 @@ export async function renderRoute(
|
|
|
676
682
|
|
|
677
683
|
const stream = new ReadableStream({
|
|
678
684
|
async start(controller) {
|
|
679
|
-
controller.enqueue(
|
|
685
|
+
controller.enqueue(
|
|
686
|
+
buildHtmlSkeleton(nonceAttr, dev) +
|
|
687
|
+
preloadLinks(matched.route.path, nonceAttr, dev),
|
|
688
|
+
);
|
|
680
689
|
|
|
681
690
|
if (hoistedCss) {
|
|
682
691
|
controller.enqueue(`\n ${hoistedCss}`);
|
|
@@ -713,6 +722,7 @@ export async function renderRoute(
|
|
|
713
722
|
"Content-Type": "text/html",
|
|
714
723
|
"Set-Cookie": csrfCookie(csrfToken),
|
|
715
724
|
Vary: NAVIGATE_HEADER,
|
|
725
|
+
...timer.headers(),
|
|
716
726
|
},
|
|
717
727
|
});
|
|
718
728
|
});
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|
package/src/server/index.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { existsSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { setServerTiming } from "../rendering/timing.ts";
|
|
3
|
+
import { preloadModules, startWarming, type Warmer } from "./warm.ts";
|
|
2
4
|
import { isAbsolute, join } from "node:path";
|
|
3
5
|
import { plugin as bunPlugin, type ServerWebSocket } from "bun";
|
|
4
6
|
import { getDevModule } from "../dev/compile-module.ts";
|
|
@@ -225,6 +227,7 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
225
227
|
const hmr = dev ? new HmrServer() : null;
|
|
226
228
|
|
|
227
229
|
const aliases = finalConfig.alias ?? {};
|
|
230
|
+
setServerTiming(finalConfig.serverTiming ?? dev);
|
|
228
231
|
|
|
229
232
|
if (dev) {
|
|
230
233
|
const { ensureRuntimeBundle } = await import("../dev/runtime-bundle.ts");
|
|
@@ -932,20 +935,54 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
932
935
|
// Bun.serve is called here rather than alongside the websocket config
|
|
933
936
|
// because handleRequest is referenced before its declaration; function
|
|
934
937
|
// hoisting makes that safe, and this keeps the two blocks readable.
|
|
938
|
+
// Wrapping is what makes afterResponse() mean "after the response",
|
|
939
|
+
// including for streaming responses: the tasks fire when the body
|
|
940
|
+
// finishes, not when the handler returns.
|
|
941
|
+
const fetchHandler = (req: Request) => withAfterResponse(req, handleRequest);
|
|
942
|
+
|
|
943
|
+
// Before the port opens, so the first visitor never pays for compiling a
|
|
944
|
+
// route: a worker only reports ready once this has finished.
|
|
945
|
+
const warmConfig = finalConfig.warm;
|
|
946
|
+
if (!dev && warmConfig?.preload !== false) {
|
|
947
|
+
const files = [
|
|
948
|
+
...tree.routes,
|
|
949
|
+
...tree.layouts,
|
|
950
|
+
...tree.servers,
|
|
951
|
+
...tree.errors,
|
|
952
|
+
].map((rf: { filePath: string }) => rf.filePath);
|
|
953
|
+
const t0 = performance.now();
|
|
954
|
+
const loaded = await preloadModules(files, loader, (msg, err) =>
|
|
955
|
+
logger.warn(msg, err),
|
|
956
|
+
);
|
|
957
|
+
logger.info(
|
|
958
|
+
`preloaded ${loaded}/${new Set(files).size} route modules in ${Math.round(performance.now() - t0)}ms`,
|
|
959
|
+
);
|
|
960
|
+
}
|
|
961
|
+
|
|
935
962
|
const server = Bun.serve({
|
|
936
963
|
port,
|
|
937
964
|
hostname: host,
|
|
938
|
-
|
|
939
|
-
// including for streaming responses: the tasks fire when the body
|
|
940
|
-
// finishes, not when the handler returns.
|
|
941
|
-
fetch: (req) => withAfterResponse(req, handleRequest),
|
|
965
|
+
fetch: fetchHandler,
|
|
942
966
|
...wsConfig,
|
|
943
967
|
});
|
|
944
968
|
|
|
969
|
+
let warmer: Warmer | null = null;
|
|
970
|
+
if (!dev && warmConfig?.paths?.length) {
|
|
971
|
+
warmer = startWarming({
|
|
972
|
+
paths: warmConfig.paths,
|
|
973
|
+
every: warmConfig.every,
|
|
974
|
+
origin: `http://${host}:${server.port}`,
|
|
975
|
+
headers: finalConfig._warmHeaders,
|
|
976
|
+
handle: async (req) => fetchHandler(req),
|
|
977
|
+
log: (msg) => logger.info(msg),
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
|
|
945
981
|
let stopping = false;
|
|
946
982
|
const handleShutdown = async () => {
|
|
947
983
|
if (stopping) return;
|
|
948
984
|
stopping = true;
|
|
985
|
+
warmer?.stop();
|
|
949
986
|
await runHook(plugins, "onStop", "shutdown");
|
|
950
987
|
// Drain before stopping, so a task already registered for a response
|
|
951
988
|
// that has been sent gets to finish rather than being killed with the
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cache warming for a production server.
|
|
3
|
+
*
|
|
4
|
+
* Two independent costs land on whoever visits first after a boot: importing
|
|
5
|
+
* each route's module (compiling it, and everything it imports), and whatever
|
|
6
|
+
* the route's own load functions cache in memory. `preloadModules` pays the
|
|
7
|
+
* first at startup; `startWarming` pays the second by requesting configured
|
|
8
|
+
* paths through the real request handler, so the app's own caches fill exactly
|
|
9
|
+
* as a visitor would fill them.
|
|
10
|
+
*
|
|
11
|
+
* Each `sigil start` worker is its own process with its own memory, which is
|
|
12
|
+
* why this lives in the server and not in a script that hits the public URL:
|
|
13
|
+
* one request would warm one worker and leave the rest cold.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export interface WarmConfig {
|
|
17
|
+
/** Paths requested after startup, one at a time, e.g. ["/costumes", "/songs"]. */
|
|
18
|
+
paths?: string[];
|
|
19
|
+
/** Request them again this often (ms) so in-memory TTL caches never lapse. */
|
|
20
|
+
every?: number;
|
|
21
|
+
/** Import every route module before the server accepts traffic. Default true. */
|
|
22
|
+
preload?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type Loader = (path: string) => Promise<unknown>;
|
|
26
|
+
|
|
27
|
+
export async function preloadModules(
|
|
28
|
+
files: string[],
|
|
29
|
+
load: Loader,
|
|
30
|
+
warn: (msg: string, err: unknown) => void,
|
|
31
|
+
): Promise<number> {
|
|
32
|
+
const unique = [...new Set(files)];
|
|
33
|
+
const results = await Promise.allSettled(unique.map((f) => load(f)));
|
|
34
|
+
let loaded = 0;
|
|
35
|
+
results.forEach((r, i) => {
|
|
36
|
+
if (r.status === "fulfilled") loaded++;
|
|
37
|
+
else warn(`could not preload ${unique[i]}:`, r.reason);
|
|
38
|
+
});
|
|
39
|
+
return loaded;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface Warmer {
|
|
43
|
+
stop(): void;
|
|
44
|
+
/** Resolves when the first pass over `paths` has finished. */
|
|
45
|
+
firstPass: Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function startWarming(opts: {
|
|
49
|
+
paths: string[];
|
|
50
|
+
every?: number;
|
|
51
|
+
origin: string;
|
|
52
|
+
headers?: Record<string, string>;
|
|
53
|
+
handle: (req: Request) => Promise<Response>;
|
|
54
|
+
log: (msg: string) => void;
|
|
55
|
+
}): Warmer {
|
|
56
|
+
const { paths, every, origin, headers, handle, log } = opts;
|
|
57
|
+
let stopped = false;
|
|
58
|
+
|
|
59
|
+
async function pass(): Promise<void> {
|
|
60
|
+
for (const path of paths) {
|
|
61
|
+
if (stopped) return;
|
|
62
|
+
const t0 = performance.now();
|
|
63
|
+
try {
|
|
64
|
+
const res = await handle(new Request(new URL(path, origin), { headers }));
|
|
65
|
+
// drain the body: a streamed page and its deferred data only
|
|
66
|
+
// finish (and only fill their caches) when someone reads it all
|
|
67
|
+
await res.arrayBuffer();
|
|
68
|
+
log(`warmed ${path} (${res.status}) in ${Math.round(performance.now() - t0)}ms`);
|
|
69
|
+
} catch (e) {
|
|
70
|
+
log(`warming ${path} failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const firstPass = pass();
|
|
76
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
77
|
+
if (every && every > 0) {
|
|
78
|
+
timer = setInterval(() => {
|
|
79
|
+
void pass();
|
|
80
|
+
}, every);
|
|
81
|
+
// a warm timer must never keep a stopping process alive
|
|
82
|
+
(timer as { unref?: () => void }).unref?.();
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
firstPass,
|
|
86
|
+
stop() {
|
|
87
|
+
stopped = true;
|
|
88
|
+
if (timer) clearInterval(timer);
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
package/src/server/worker.ts
CHANGED
package/src/types.ts
CHANGED
|
@@ -312,7 +312,21 @@ export interface GrimoireConfig {
|
|
|
312
312
|
alias?: Record<string, string>; // e.g. { "$lib": "src/lib" } — resolved relative to cwd
|
|
313
313
|
cspNonce?: string; // CSP nonce for <script>/<style> tags
|
|
314
314
|
bundleStrategy?: "split" | "single"; // 'split' (default) or 'single' bundle
|
|
315
|
+
/**
|
|
316
|
+
* Send a `Server-Timing` header (load / render durations) on page
|
|
317
|
+
* responses. Default: on in dev, off in production.
|
|
318
|
+
*/
|
|
319
|
+
serverTiming?: boolean;
|
|
315
320
|
_skipBuild?: boolean;
|
|
321
|
+
/**
|
|
322
|
+
* Production cache warming. Route modules are imported before the server
|
|
323
|
+
* takes traffic; `paths` are then requested through the real handler (once
|
|
324
|
+
* per worker, and again every `every` ms) so in-memory caches are full
|
|
325
|
+
* before a visitor arrives.
|
|
326
|
+
*/
|
|
327
|
+
warm?: import("./server/warm.ts").WarmConfig;
|
|
328
|
+
/** Set by the worker: headers the server's own warm-up requests carry. */
|
|
329
|
+
_warmHeaders?: Record<string, string>;
|
|
316
330
|
}
|
|
317
331
|
|
|
318
332
|
export function defineConfig(config: GrimoireConfig): GrimoireConfig {
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { cached, cachedBy } from "../src/server/cached.ts";
|
|
3
|
+
|
|
4
|
+
const tick = (ms: number) => Bun.sleep(ms);
|
|
5
|
+
|
|
6
|
+
describe("cached", () => {
|
|
7
|
+
test("returns the same value while fresh and builds once", async () => {
|
|
8
|
+
let n = 0;
|
|
9
|
+
const get = cached(async () => ++n, { ttl: 1000 });
|
|
10
|
+
expect(await get()).toBe(1);
|
|
11
|
+
expect(await get()).toBe(1);
|
|
12
|
+
expect(n).toBe(1);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test("concurrent first calls share one build", async () => {
|
|
16
|
+
let n = 0;
|
|
17
|
+
const get = cached(
|
|
18
|
+
async () => {
|
|
19
|
+
await tick(20);
|
|
20
|
+
return ++n;
|
|
21
|
+
},
|
|
22
|
+
{ ttl: 1000 },
|
|
23
|
+
);
|
|
24
|
+
expect(await Promise.all([get(), get(), get()])).toEqual([1, 1, 1]);
|
|
25
|
+
expect(n).toBe(1);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("an expired value is served at once while one refresh runs", async () => {
|
|
29
|
+
let n = 0;
|
|
30
|
+
const get = cached(
|
|
31
|
+
async () => {
|
|
32
|
+
await tick(30);
|
|
33
|
+
return ++n;
|
|
34
|
+
},
|
|
35
|
+
{ ttl: 20 },
|
|
36
|
+
);
|
|
37
|
+
await get();
|
|
38
|
+
await tick(40);
|
|
39
|
+
const t0 = performance.now();
|
|
40
|
+
expect(await get()).toBe(1); // stale, instantly
|
|
41
|
+
expect(await get()).toBe(1); // refresh still in flight, still one
|
|
42
|
+
expect(performance.now() - t0).toBeLessThan(25);
|
|
43
|
+
await tick(50);
|
|
44
|
+
expect(n).toBe(2);
|
|
45
|
+
expect(await get()).toBe(2);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("past staleFor the caller waits for the fresh value", async () => {
|
|
49
|
+
let n = 0;
|
|
50
|
+
const get = cached(async () => ++n, { ttl: 10, staleFor: 10 });
|
|
51
|
+
await get();
|
|
52
|
+
await tick(40);
|
|
53
|
+
expect(await get()).toBe(2);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("a failed background refresh keeps the stale value and reports it", async () => {
|
|
57
|
+
let n = 0;
|
|
58
|
+
const errors: unknown[] = [];
|
|
59
|
+
const get = cached(
|
|
60
|
+
async () => {
|
|
61
|
+
if (++n > 1) throw new Error("upstream down");
|
|
62
|
+
return "v1";
|
|
63
|
+
},
|
|
64
|
+
{ ttl: 10, onError: (e) => errors.push(e) },
|
|
65
|
+
);
|
|
66
|
+
await get();
|
|
67
|
+
await tick(20);
|
|
68
|
+
expect(await get()).toBe("v1");
|
|
69
|
+
await tick(10);
|
|
70
|
+
expect(errors).toHaveLength(1);
|
|
71
|
+
expect(await get()).toBe("v1");
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("a failed first build throws and is not cached", async () => {
|
|
75
|
+
let n = 0;
|
|
76
|
+
const get = cached(
|
|
77
|
+
async () => {
|
|
78
|
+
if (++n === 1) throw new Error("first fails");
|
|
79
|
+
return "ok";
|
|
80
|
+
},
|
|
81
|
+
{ ttl: 1000 },
|
|
82
|
+
);
|
|
83
|
+
await expect(get()).rejects.toThrow("first fails");
|
|
84
|
+
expect(await get()).toBe("ok");
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("invalidate forces the next call to rebuild", async () => {
|
|
88
|
+
let n = 0;
|
|
89
|
+
const get = cached(async () => ++n, { ttl: 1000 });
|
|
90
|
+
await get();
|
|
91
|
+
get.invalidate();
|
|
92
|
+
expect(await get()).toBe(2);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
describe("cachedBy", () => {
|
|
97
|
+
test("caches per argument and evicts the least recently used past max", async () => {
|
|
98
|
+
const calls: string[] = [];
|
|
99
|
+
const get = cachedBy(
|
|
100
|
+
async (id: string) => {
|
|
101
|
+
calls.push(id);
|
|
102
|
+
return id.toUpperCase();
|
|
103
|
+
},
|
|
104
|
+
{ ttl: 1000, max: 2 },
|
|
105
|
+
);
|
|
106
|
+
await get("a");
|
|
107
|
+
await get("b");
|
|
108
|
+
await get("a"); // hit: "b" is now the least recently used
|
|
109
|
+
expect(calls).toEqual(["a", "b"]);
|
|
110
|
+
await get("c"); // pushes out "b", not "a"
|
|
111
|
+
await get("a");
|
|
112
|
+
expect(calls).toEqual(["a", "b", "c"]);
|
|
113
|
+
await get("b");
|
|
114
|
+
expect(calls).toEqual(["a", "b", "c", "b"]);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test("invalidate(key) drops only that key", async () => {
|
|
118
|
+
let n = 0;
|
|
119
|
+
const get = cachedBy(async (_id: string) => ++n, { ttl: 1000 });
|
|
120
|
+
await get("x");
|
|
121
|
+
await get("y");
|
|
122
|
+
get.invalidate("x");
|
|
123
|
+
expect(await get("y")).toBe(2);
|
|
124
|
+
expect(await get("x")).toBe(3);
|
|
125
|
+
});
|
|
126
|
+
});
|
|
@@ -241,6 +241,96 @@ describe("navigate — view transitions", () => {
|
|
|
241
241
|
});
|
|
242
242
|
});
|
|
243
243
|
|
|
244
|
+
describe("shared-element view transitions", () => {
|
|
245
|
+
const nameOf = (el: Element) =>
|
|
246
|
+
(el as HTMLElement).style.getPropertyValue("view-transition-name");
|
|
247
|
+
|
|
248
|
+
test("elements sharing data-sigil-transition are named on both pages", async () => {
|
|
249
|
+
const root = document.createElement("div");
|
|
250
|
+
root.id = "grimoire-root";
|
|
251
|
+
const oldHero = document.createElement("img");
|
|
252
|
+
oldHero.setAttribute("data-sigil-transition", "hero-7");
|
|
253
|
+
const other = document.createElement("img");
|
|
254
|
+
other.setAttribute("data-sigil-transition", "hero-8"); // not on the new page
|
|
255
|
+
root.append(oldHero, other);
|
|
256
|
+
document.body.appendChild(root);
|
|
257
|
+
|
|
258
|
+
let newHero: Element | undefined;
|
|
259
|
+
const page = () => {
|
|
260
|
+
const main = document.createElement("main");
|
|
261
|
+
newHero = document.createElement("img");
|
|
262
|
+
newHero.setAttribute("data-sigil-transition", "hero-7");
|
|
263
|
+
main.appendChild(newHero);
|
|
264
|
+
return main;
|
|
265
|
+
};
|
|
266
|
+
const docEnv = document as unknown as {
|
|
267
|
+
startViewTransition?: (cb: () => void) => unknown;
|
|
268
|
+
};
|
|
269
|
+
const seen: { oldNamed: string; otherNamed: string; newNamed: string }[] = [];
|
|
270
|
+
docEnv.startViewTransition = (cb: () => void) => {
|
|
271
|
+
const before = { oldNamed: nameOf(oldHero), otherNamed: nameOf(other), newNamed: "" };
|
|
272
|
+
cb();
|
|
273
|
+
before.newNamed = nameOf(newHero!);
|
|
274
|
+
seen.push(before);
|
|
275
|
+
return { finished: Promise.resolve() };
|
|
276
|
+
};
|
|
277
|
+
const shim = captureFetch();
|
|
278
|
+
try {
|
|
279
|
+
router.initRouter({ "/shared": page }, []);
|
|
280
|
+
await router.navigate("/shared");
|
|
281
|
+
// the old element is named when the browser snapshots, the new one
|
|
282
|
+
// once the swap ran; an element with no partner is left alone
|
|
283
|
+
expect(seen).toEqual([{ oldNamed: "hero-7", otherNamed: "", newNamed: "hero-7" }]);
|
|
284
|
+
await Promise.resolve();
|
|
285
|
+
await Promise.resolve();
|
|
286
|
+
expect(nameOf(newHero!)).toBe(""); // cleaned up when it finished
|
|
287
|
+
} finally {
|
|
288
|
+
delete docEnv.startViewTransition;
|
|
289
|
+
shim.restore();
|
|
290
|
+
root.remove();
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
test("a key used twice on a page is skipped", async () => {
|
|
295
|
+
const root = document.createElement("div");
|
|
296
|
+
root.id = "grimoire-root";
|
|
297
|
+
for (let i = 0; i < 2; i++) {
|
|
298
|
+
const el = document.createElement("div");
|
|
299
|
+
el.setAttribute("data-sigil-transition", "dup");
|
|
300
|
+
root.appendChild(el);
|
|
301
|
+
}
|
|
302
|
+
document.body.appendChild(root);
|
|
303
|
+
const docEnv = document as unknown as {
|
|
304
|
+
startViewTransition?: (cb: () => void) => unknown;
|
|
305
|
+
};
|
|
306
|
+
let named = 0;
|
|
307
|
+
docEnv.startViewTransition = (cb: () => void) => {
|
|
308
|
+
named = document.querySelectorAll('[style*="view-transition-name"]').length;
|
|
309
|
+
cb();
|
|
310
|
+
return undefined;
|
|
311
|
+
};
|
|
312
|
+
const shim = captureFetch();
|
|
313
|
+
try {
|
|
314
|
+
router.initRouter(
|
|
315
|
+
{
|
|
316
|
+
"/dup": () => {
|
|
317
|
+
const el = document.createElement("div");
|
|
318
|
+
el.setAttribute("data-sigil-transition", "dup");
|
|
319
|
+
return el;
|
|
320
|
+
},
|
|
321
|
+
},
|
|
322
|
+
[],
|
|
323
|
+
);
|
|
324
|
+
await router.navigate("/dup");
|
|
325
|
+
expect(named).toBe(0);
|
|
326
|
+
} finally {
|
|
327
|
+
delete docEnv.startViewTransition;
|
|
328
|
+
shim.restore();
|
|
329
|
+
root.remove();
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
});
|
|
333
|
+
|
|
244
334
|
describe("hover prefetch", () => {
|
|
245
335
|
// The 80ms debounce is real timer logic under test — fake timers advance
|
|
246
336
|
// it deterministically instead of sleeping past it.
|
|
@@ -323,6 +413,48 @@ describe("prefetch reuse", () => {
|
|
|
323
413
|
}
|
|
324
414
|
});
|
|
325
415
|
|
|
416
|
+
test("a click cancels the hover prefetch it just consumed", async () => {
|
|
417
|
+
const root = document.createElement("div");
|
|
418
|
+
root.id = "grimoire-root";
|
|
419
|
+
document.body.appendChild(root);
|
|
420
|
+
router.initRouter({ "/hov": () => document.createElement("main") }, []);
|
|
421
|
+
const shim = captureFetch();
|
|
422
|
+
try {
|
|
423
|
+
const a = document.createElement("a");
|
|
424
|
+
a.setAttribute("href", "/hov");
|
|
425
|
+
document.body.appendChild(a);
|
|
426
|
+
a.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
427
|
+
a.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
|
428
|
+
await Bun.sleep(200); // past the 80ms hover delay
|
|
429
|
+
expect(root.childNodes.length).toBeGreaterThan(0); // the click navigated
|
|
430
|
+
expect(shim.calls.length).toBe(1); // its own request, not a second
|
|
431
|
+
} finally {
|
|
432
|
+
shim.restore();
|
|
433
|
+
root.remove();
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
test("a prefetch made before a cookie changed is not reused", async () => {
|
|
438
|
+
const root = document.createElement("div");
|
|
439
|
+
root.id = "grimoire-root";
|
|
440
|
+
document.body.appendChild(root);
|
|
441
|
+
router.initRouter({ "/pref": () => document.createElement("main") }, []);
|
|
442
|
+
const shim = captureFetch();
|
|
443
|
+
try {
|
|
444
|
+
document.cookie = "region=jp";
|
|
445
|
+
router.prefetch("/pref");
|
|
446
|
+
expect(shim.calls.length).toBe(1);
|
|
447
|
+
document.cookie = "region=en"; // the visitor switched server
|
|
448
|
+
await router.navigate("/pref");
|
|
449
|
+
// the held response was fetched as jp, so the click asks again
|
|
450
|
+
expect(shim.calls.length).toBe(2);
|
|
451
|
+
} finally {
|
|
452
|
+
document.cookie = "region=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
|
|
453
|
+
shim.restore();
|
|
454
|
+
root.remove();
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
|
|
326
458
|
test("invalidateAll never serves a prefetched response", async () => {
|
|
327
459
|
const root = document.createElement("div");
|
|
328
460
|
root.id = "grimoire-root";
|
package/test/images.test.ts
CHANGED
|
@@ -28,6 +28,21 @@ describe("optimizeImages", () => {
|
|
|
28
28
|
expect(out).toContain(`<img src="/y.png" loading="lazy" decoding="async" />`);
|
|
29
29
|
});
|
|
30
30
|
|
|
31
|
+
test("a priority image is fetched first and does not use up the eager budget", () => {
|
|
32
|
+
const hero = `<img src="/hero.png" data-sigil-priority>`;
|
|
33
|
+
const out = optimizeImages(hero + imgs(EAGER_IMAGE_COUNT + 1));
|
|
34
|
+
const tags = out.match(/<img[^>]*>/g)!;
|
|
35
|
+
expect(tags[0]).toBe(`<img src="/hero.png" data-sigil-priority fetchpriority="high">`);
|
|
36
|
+
// the four after it are still eager, the fifth is deferred
|
|
37
|
+
for (const t of tags.slice(1, 1 + EAGER_IMAGE_COUNT)) expect(t).not.toContain("loading");
|
|
38
|
+
expect(tags.at(-1)).toContain('loading="lazy"');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("an explicit fetchpriority on a priority image is kept", () => {
|
|
42
|
+
const t = `<img src="/h.png" data-sigil-priority fetchpriority="low">`;
|
|
43
|
+
expect(optimizeImages(t)).toBe(t);
|
|
44
|
+
});
|
|
45
|
+
|
|
31
46
|
test("html without images is returned as is", () => {
|
|
32
47
|
expect(optimizeImages("<p>hi</p>")).toBe("<p>hi</p>");
|
|
33
48
|
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
chunksFor,
|
|
4
|
+
parseChunkGraph,
|
|
5
|
+
preloadLinks,
|
|
6
|
+
resetChunkGraph,
|
|
7
|
+
} from "../src/rendering/preload.ts";
|
|
8
|
+
|
|
9
|
+
// the shape Bun writes into hydrate.js for a split build
|
|
10
|
+
const SOURCE = `var x = 1;
|
|
11
|
+
__chunks(import.meta.url,["hy","home","cards","shared","leaf"],[["./hydrate.js",3],["./chunk-home.js",3],["./chunk-cards.js",3,4],["./chunk-shared.js"],["./chunk-leaf.js",3]],0);
|
|
12
|
+
var routes = {
|
|
13
|
+
"/": { __lazy: () => (__preload("home"), import("./chunk-home.js")) },
|
|
14
|
+
"/cards/:id": { __lazy: () => (__preload("cards"), import("./chunk-cards.js")) },
|
|
15
|
+
};`;
|
|
16
|
+
|
|
17
|
+
afterEach(() => resetChunkGraph());
|
|
18
|
+
|
|
19
|
+
describe("chunk graph", () => {
|
|
20
|
+
test("routes map to chunks and closures include shared imports", () => {
|
|
21
|
+
const g = parseChunkGraph(SOURCE)!;
|
|
22
|
+
expect(g.routes.get("/")).toBe("home");
|
|
23
|
+
expect(chunksFor(g, "/").sort()).toEqual(["chunk-home.js", "chunk-shared.js"]);
|
|
24
|
+
expect(chunksFor(g, "/cards/:id").sort()).toEqual([
|
|
25
|
+
"chunk-cards.js",
|
|
26
|
+
"chunk-leaf.js",
|
|
27
|
+
"chunk-shared.js",
|
|
28
|
+
]);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("hydrate.js itself is never listed, unknown routes give nothing", () => {
|
|
32
|
+
const g = parseChunkGraph(SOURCE)!;
|
|
33
|
+
expect(chunksFor(g, "/cards/:id")).not.toContain("hydrate.js");
|
|
34
|
+
expect(chunksFor(g, "/missing")).toEqual([]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test("output without a chunk graph parses to null", () => {
|
|
38
|
+
expect(parseChunkGraph("console.log(1)")).toBeNull();
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
describe("preloadLinks", () => {
|
|
43
|
+
test("is empty in dev and when no build exists", () => {
|
|
44
|
+
expect(preloadLinks("/", "", true)).toBe("");
|
|
45
|
+
// cwd here has no public/__grimoire__/hydrate.js
|
|
46
|
+
expect(preloadLinks("/", "")).toBe("");
|
|
47
|
+
});
|
|
48
|
+
});
|
package/test/rendering.test.ts
CHANGED
|
@@ -763,3 +763,36 @@ describe("server-side depends()", () => {
|
|
|
763
763
|
expect(html).toContain('"deps":["user:1"]');
|
|
764
764
|
});
|
|
765
765
|
});
|
|
766
|
+
|
|
767
|
+
describe("Server-Timing", () => {
|
|
768
|
+
async function render(path: string, headers: Record<string, string> = {}) {
|
|
769
|
+
const tree = await scanRoutes(tmpDir);
|
|
770
|
+
const matched = matchRoute(tree, new URL(`http://localhost${path}`));
|
|
771
|
+
return renderRoute(
|
|
772
|
+
matched!,
|
|
773
|
+
new Request(`http://localhost${path}`, { headers }),
|
|
774
|
+
);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
test("page responses report load and render when enabled", async () => {
|
|
778
|
+
const { setServerTiming } = await import("../src/rendering/timing.ts");
|
|
779
|
+
setServerTiming(true);
|
|
780
|
+
try {
|
|
781
|
+
const res = await render("/blog");
|
|
782
|
+
expect(res.headers.get("server-timing")).toMatch(
|
|
783
|
+
/^load;dur=[\d.]+, render;dur=[\d.]+$/,
|
|
784
|
+
);
|
|
785
|
+
const nav = await render("/blog", { "x-grimoire-navigate": "1" });
|
|
786
|
+
expect(nav.headers.get("server-timing")).toMatch(
|
|
787
|
+
/^load;dur=[\d.]+, render;dur=[\d.]+, deferred;dur=[\d.]+$/,
|
|
788
|
+
);
|
|
789
|
+
} finally {
|
|
790
|
+
setServerTiming(false);
|
|
791
|
+
}
|
|
792
|
+
});
|
|
793
|
+
|
|
794
|
+
test("nothing is sent when disabled", async () => {
|
|
795
|
+
const res = await render("/blog");
|
|
796
|
+
expect(res.headers.get("server-timing")).toBeNull();
|
|
797
|
+
});
|
|
798
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { preloadModules, startWarming } from "../src/server/warm.ts";
|
|
3
|
+
|
|
4
|
+
describe("preloadModules", () => {
|
|
5
|
+
test("imports each file once and reports failures without throwing", async () => {
|
|
6
|
+
const seen: string[] = [];
|
|
7
|
+
const warnings: string[] = [];
|
|
8
|
+
const loaded = await preloadModules(
|
|
9
|
+
["/a.tsx", "/b.tsx", "/a.tsx", "/bad.tsx"],
|
|
10
|
+
async (f) => {
|
|
11
|
+
seen.push(f);
|
|
12
|
+
if (f === "/bad.tsx") throw new Error("boom");
|
|
13
|
+
},
|
|
14
|
+
(msg) => warnings.push(msg),
|
|
15
|
+
);
|
|
16
|
+
expect(loaded).toBe(2);
|
|
17
|
+
expect(seen.sort()).toEqual(["/a.tsx", "/b.tsx", "/bad.tsx"]);
|
|
18
|
+
expect(warnings).toEqual(["could not preload /bad.tsx:"]);
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe("startWarming", () => {
|
|
23
|
+
test("requests paths in order, with the given headers, and drains bodies", async () => {
|
|
24
|
+
const calls: Array<{ path: string; header: string | null }> = [];
|
|
25
|
+
let drained = 0;
|
|
26
|
+
const warmer = startWarming({
|
|
27
|
+
paths: ["/one", "/two"],
|
|
28
|
+
origin: "http://127.0.0.1:1234",
|
|
29
|
+
headers: { "x-grimoire-internal": "s3cret" },
|
|
30
|
+
handle: async (req) => {
|
|
31
|
+
calls.push({
|
|
32
|
+
path: new URL(req.url).pathname,
|
|
33
|
+
header: req.headers.get("x-grimoire-internal"),
|
|
34
|
+
});
|
|
35
|
+
const stream = new ReadableStream({
|
|
36
|
+
pull(c) {
|
|
37
|
+
drained++;
|
|
38
|
+
c.enqueue(new TextEncoder().encode("x"));
|
|
39
|
+
c.close();
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
return new Response(stream);
|
|
43
|
+
},
|
|
44
|
+
log: () => {},
|
|
45
|
+
});
|
|
46
|
+
await warmer.firstPass;
|
|
47
|
+
warmer.stop();
|
|
48
|
+
expect(calls).toEqual([
|
|
49
|
+
{ path: "/one", header: "s3cret" },
|
|
50
|
+
{ path: "/two", header: "s3cret" },
|
|
51
|
+
]);
|
|
52
|
+
expect(drained).toBe(2);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("a failing path is logged and does not stop the rest", async () => {
|
|
56
|
+
const logs: string[] = [];
|
|
57
|
+
const paths: string[] = [];
|
|
58
|
+
const warmer = startWarming({
|
|
59
|
+
paths: ["/bad", "/good"],
|
|
60
|
+
origin: "http://x",
|
|
61
|
+
handle: async (req) => {
|
|
62
|
+
const p = new URL(req.url).pathname;
|
|
63
|
+
paths.push(p);
|
|
64
|
+
if (p === "/bad") throw new Error("nope");
|
|
65
|
+
return new Response("ok");
|
|
66
|
+
},
|
|
67
|
+
log: (m) => logs.push(m),
|
|
68
|
+
});
|
|
69
|
+
await warmer.firstPass;
|
|
70
|
+
warmer.stop();
|
|
71
|
+
expect(paths).toEqual(["/bad", "/good"]);
|
|
72
|
+
expect(logs[0]).toContain("/bad failed: nope");
|
|
73
|
+
expect(logs[1]).toContain("warmed /good (200)");
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("every repeats the pass until stopped", async () => {
|
|
77
|
+
let n = 0;
|
|
78
|
+
const warmer = startWarming({
|
|
79
|
+
paths: ["/p"],
|
|
80
|
+
every: 20,
|
|
81
|
+
origin: "http://x",
|
|
82
|
+
handle: async () => {
|
|
83
|
+
n++;
|
|
84
|
+
return new Response("ok");
|
|
85
|
+
},
|
|
86
|
+
log: () => {},
|
|
87
|
+
});
|
|
88
|
+
await warmer.firstPass;
|
|
89
|
+
await Bun.sleep(90);
|
|
90
|
+
warmer.stop();
|
|
91
|
+
const seen = n;
|
|
92
|
+
expect(seen).toBeGreaterThanOrEqual(3);
|
|
93
|
+
await Bun.sleep(60);
|
|
94
|
+
expect(n).toBe(seen);
|
|
95
|
+
});
|
|
96
|
+
});
|