@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 +3 -3
- package/src/client/router.ts +100 -17
- package/src/rendering/images.ts +9 -0
- package/src/rendering/index.ts +27 -3
- package/src/rendering/preload.ts +94 -0
- package/src/rendering/timing.ts +40 -0
- package/src/routing/router.ts +63 -12
- package/src/server/cached.ts +114 -0
- package/src/server/index.ts +55 -22
- 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/server.test.ts +40 -0
- package/test/warm.test.ts +96 -0
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";
|
|
@@ -15,7 +17,7 @@ import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
|
|
|
15
17
|
import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
|
|
16
18
|
import { renderErrorPage, renderRoute } from "../rendering";
|
|
17
19
|
import { registerSSRPlugin } from "../rendering/ssrPlugin";
|
|
18
|
-
import { matchRoute } from "../routing/router";
|
|
20
|
+
import { matchNotFound, matchRoute } from "../routing/router";
|
|
19
21
|
import { isErrorResult } from "../sentinels/error.ts";
|
|
20
22
|
import { isFailResult } from "../sentinels/fail.ts";
|
|
21
23
|
import { isRedirectResult } from "../sentinels/redirect.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");
|
|
@@ -508,7 +511,6 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
508
511
|
if (staticAsset) return staticAsset;
|
|
509
512
|
|
|
510
513
|
return runRequestHooks(plugins, req, async () => {
|
|
511
|
-
|
|
512
514
|
const HTTP_METHODS = [
|
|
513
515
|
"GET",
|
|
514
516
|
"POST",
|
|
@@ -554,18 +556,18 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
554
556
|
// matching happens here — after handle() has run
|
|
555
557
|
let matched = matchRoute(tree, evt.url, paramMatcherFns);
|
|
556
558
|
if (!matched) {
|
|
557
|
-
// the nearest +error.tsx
|
|
558
|
-
//
|
|
559
|
-
return (
|
|
560
|
-
(
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
559
|
+
// the nearest +error.tsx inside the layouts that cover the
|
|
560
|
+
// address, like a page whose load throws error(404)
|
|
561
|
+
return renderRoute(
|
|
562
|
+
matchNotFound(tree, evt.url),
|
|
563
|
+
evt.request,
|
|
564
|
+
tree.errors,
|
|
565
|
+
loader,
|
|
566
|
+
evt.locals,
|
|
567
|
+
plugins,
|
|
568
|
+
cspNonce,
|
|
569
|
+
dev,
|
|
570
|
+
patchedFetch,
|
|
569
571
|
);
|
|
570
572
|
}
|
|
571
573
|
|
|
@@ -855,10 +857,7 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
855
857
|
);
|
|
856
858
|
if (page) return page;
|
|
857
859
|
} catch (pageErr) {
|
|
858
|
-
logger.error(
|
|
859
|
-
"+error.tsx failed while rendering an error:",
|
|
860
|
-
pageErr,
|
|
861
|
-
);
|
|
860
|
+
logger.error("+error.tsx failed while rendering an error:", pageErr);
|
|
862
861
|
}
|
|
863
862
|
const errorHtmlPath = `${process.cwd()}/error.html`;
|
|
864
863
|
try {
|
|
@@ -932,20 +931,54 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
932
931
|
// Bun.serve is called here rather than alongside the websocket config
|
|
933
932
|
// because handleRequest is referenced before its declaration; function
|
|
934
933
|
// hoisting makes that safe, and this keeps the two blocks readable.
|
|
934
|
+
// Wrapping is what makes afterResponse() mean "after the response",
|
|
935
|
+
// including for streaming responses: the tasks fire when the body
|
|
936
|
+
// finishes, not when the handler returns.
|
|
937
|
+
const fetchHandler = (req: Request) => withAfterResponse(req, handleRequest);
|
|
938
|
+
|
|
939
|
+
// Before the port opens, so the first visitor never pays for compiling a
|
|
940
|
+
// route: a worker only reports ready once this has finished.
|
|
941
|
+
const warmConfig = finalConfig.warm;
|
|
942
|
+
if (!dev && warmConfig?.preload !== false) {
|
|
943
|
+
const files = [
|
|
944
|
+
...tree.routes,
|
|
945
|
+
...tree.layouts,
|
|
946
|
+
...tree.servers,
|
|
947
|
+
...tree.errors,
|
|
948
|
+
].map((rf: { filePath: string }) => rf.filePath);
|
|
949
|
+
const t0 = performance.now();
|
|
950
|
+
const loaded = await preloadModules(files, loader, (msg, err) =>
|
|
951
|
+
logger.warn(msg, err),
|
|
952
|
+
);
|
|
953
|
+
logger.info(
|
|
954
|
+
`preloaded ${loaded}/${new Set(files).size} route modules in ${Math.round(performance.now() - t0)}ms`,
|
|
955
|
+
);
|
|
956
|
+
}
|
|
957
|
+
|
|
935
958
|
const server = Bun.serve({
|
|
936
959
|
port,
|
|
937
960
|
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),
|
|
961
|
+
fetch: fetchHandler,
|
|
942
962
|
...wsConfig,
|
|
943
963
|
});
|
|
944
964
|
|
|
965
|
+
let warmer: Warmer | null = null;
|
|
966
|
+
if (!dev && warmConfig?.paths?.length) {
|
|
967
|
+
warmer = startWarming({
|
|
968
|
+
paths: warmConfig.paths,
|
|
969
|
+
every: warmConfig.every,
|
|
970
|
+
origin: `http://${host}:${server.port}`,
|
|
971
|
+
headers: finalConfig._warmHeaders,
|
|
972
|
+
handle: async (req) => fetchHandler(req),
|
|
973
|
+
log: (msg) => logger.info(msg),
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
|
|
945
977
|
let stopping = false;
|
|
946
978
|
const handleShutdown = async () => {
|
|
947
979
|
if (stopping) return;
|
|
948
980
|
stopping = true;
|
|
981
|
+
warmer?.stop();
|
|
949
982
|
await runHook(plugins, "onStop", "shutdown");
|
|
950
983
|
// Drain before stopping, so a task already registered for a response
|
|
951
984
|
// 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
|
+
});
|
package/test/server.test.ts
CHANGED
|
@@ -532,6 +532,26 @@ describe("Server — error pages", () => {
|
|
|
532
532
|
join(dir, "boom", "+page.tsx"),
|
|
533
533
|
"export default () => 'never';",
|
|
534
534
|
);
|
|
535
|
+
// a root layout with its own server data, a nested error page, and
|
|
536
|
+
// one in a [param] folder
|
|
537
|
+
await writeFile(
|
|
538
|
+
join(dir, "+layout.tsx"),
|
|
539
|
+
'export default ({ data, children }) => `<main data-site="${data.site}">${children}</main>`;',
|
|
540
|
+
);
|
|
541
|
+
await writeFile(
|
|
542
|
+
join(dir, "+layout.server.ts"),
|
|
543
|
+
'export function load() { return { site: "meow" }; }',
|
|
544
|
+
);
|
|
545
|
+
await mkdir(join(dir, "shop"), { recursive: true });
|
|
546
|
+
await writeFile(
|
|
547
|
+
join(dir, "shop", "+error.tsx"),
|
|
548
|
+
"export default ({ status }) => `<h1>shop ${status}</h1>`;",
|
|
549
|
+
);
|
|
550
|
+
await mkdir(join(dir, "items", "[id]"), { recursive: true });
|
|
551
|
+
await writeFile(
|
|
552
|
+
join(dir, "items", "[id]", "+error.tsx"),
|
|
553
|
+
"export default ({ status }) => `<h1>item ${status}</h1>`;",
|
|
554
|
+
);
|
|
535
555
|
server = await createServer({ port: 3012, routes: dir, _skipBuild: true });
|
|
536
556
|
});
|
|
537
557
|
|
|
@@ -545,6 +565,26 @@ describe("Server — error pages", () => {
|
|
|
545
565
|
expect(html).toContain("oops 404: Not Found");
|
|
546
566
|
});
|
|
547
567
|
|
|
568
|
+
test("an unknown URL's error page sits in the layouts, with their data", async () => {
|
|
569
|
+
const html = await (await fetch(`${base}/nowhere/at/all`)).text();
|
|
570
|
+
expect(html).toContain('<main data-site="meow">');
|
|
571
|
+
expect(html).toContain("oops 404: Not Found");
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
test("an unknown URL gets the closest +error.tsx", async () => {
|
|
575
|
+
const res = await fetch(`${base}/shop/no-such-thing`);
|
|
576
|
+
expect(res.status).toBe(404);
|
|
577
|
+
expect(await res.text()).toContain("shop 404");
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
test("a +error.tsx in a [param] folder covers the addresses under it", async () => {
|
|
581
|
+
expect(await (await fetch(`${base}/items/42/missing`)).text()).toContain(
|
|
582
|
+
"item 404",
|
|
583
|
+
);
|
|
584
|
+
// /items itself is above the [id] folder
|
|
585
|
+
expect(await (await fetch(`${base}/items`)).text()).toContain("oops 404");
|
|
586
|
+
});
|
|
587
|
+
|
|
548
588
|
test("an unexpected error renders +error.tsx with a generic message", async () => {
|
|
549
589
|
const res = await fetch(`${base}/boom`);
|
|
550
590
|
expect(res.status).toBe(500);
|