@sigil-dev/grimoire 0.9.3 → 0.9.4
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/index.ts +2 -0
- package/package.json +9 -12
- package/src/client/deps.ts +19 -2
- package/src/client/enhance.ts +5 -1
- package/src/client/index.ts +5 -5
- package/src/client/router.ts +145 -61
- package/src/rendering/hydrate.ts +146 -138
- package/src/rendering/index.ts +133 -15
- package/src/routing/manifest-gen.ts +55 -43
- package/src/routing/router.ts +41 -15
- package/src/routing/scanner.ts +56 -10
- package/src/server/build.ts +16 -4
- package/src/server/index.ts +27 -5
- package/src/typegen/index.ts +37 -4
- package/src/types.ts +4 -0
- package/test/client-router.test.ts +256 -2
- package/test/rendering.test.ts +113 -0
- package/test/routing.test.ts +114 -1
- package/test/scanning.test.ts +64 -10
- package/test/server.test.ts +105 -0
- package/test/streaming.test.ts +118 -1
- package/test/transform-routes.test.ts +3 -0
- package/test/typegen.test.ts +15 -0
|
@@ -1,13 +1,79 @@
|
|
|
1
|
-
import { beforeEach, describe, expect, test } from "bun:test";
|
|
1
|
+
import { beforeEach, describe, expect, test, vi } from "bun:test";
|
|
2
|
+
import type { Document, History, Location, Window } from "happy-dom";
|
|
2
3
|
import {
|
|
3
4
|
clearDeps,
|
|
4
5
|
depends,
|
|
5
6
|
hasDep,
|
|
7
|
+
setDeps,
|
|
6
8
|
startCollecting,
|
|
7
9
|
stopCollecting,
|
|
8
10
|
} from "../src/client/deps.ts";
|
|
9
11
|
|
|
10
|
-
|
|
12
|
+
// test/preload.ts installs happy-dom globals at runtime; this package's
|
|
13
|
+
// compiler options have no DOM lib, so declare the shapes we rely on.
|
|
14
|
+
declare global {
|
|
15
|
+
// biome-ignore-all lint/style/noVar: ambient global declarations require var
|
|
16
|
+
var window: Window;
|
|
17
|
+
var document: Document;
|
|
18
|
+
var location: Location;
|
|
19
|
+
var history: History;
|
|
20
|
+
var MouseEvent: Window["MouseEvent"];
|
|
21
|
+
var Event: Window["Event"];
|
|
22
|
+
var requestAnimationFrame: Window["requestAnimationFrame"];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// router.ts reads `location` at module load — DOM globals must exist first.
|
|
26
|
+
// Dynamic import is required because the module under test captures location
|
|
27
|
+
// during evaluation, which static-hoisted imports would race. The default
|
|
28
|
+
// about:blank URL has origin "null", which breaks new URL(href, origin) —
|
|
29
|
+
// point the window at a real origin first.
|
|
30
|
+
window.location.href = "http://localhost/";
|
|
31
|
+
const globalEnv = globalThis as typeof globalThis & {
|
|
32
|
+
location: Location;
|
|
33
|
+
history: History;
|
|
34
|
+
requestAnimationFrame: Window["requestAnimationFrame"];
|
|
35
|
+
};
|
|
36
|
+
globalEnv.location = window.location;
|
|
37
|
+
globalEnv.history = window.history;
|
|
38
|
+
globalEnv.requestAnimationFrame = window.requestAnimationFrame.bind(window);
|
|
39
|
+
const router = await import("../src/client/router.ts");
|
|
40
|
+
|
|
41
|
+
function jsonResponse(pattern: string): Response {
|
|
42
|
+
return new Response(
|
|
43
|
+
JSON.stringify({
|
|
44
|
+
data: {},
|
|
45
|
+
layoutData: [],
|
|
46
|
+
params: {},
|
|
47
|
+
pattern,
|
|
48
|
+
head: "",
|
|
49
|
+
}),
|
|
50
|
+
{ headers: { "content-type": "application/json" } },
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function captureFetch(): {
|
|
55
|
+
calls: Array<{ input: string; init?: RequestInit }>;
|
|
56
|
+
restore: () => void;
|
|
57
|
+
} {
|
|
58
|
+
const calls: Array<{ input: string; init?: RequestInit }> = [];
|
|
59
|
+
const original = globalThis.fetch;
|
|
60
|
+
// test shim over the global — precise fetch typing is impossible here.
|
|
61
|
+
// Echoes the requested pathname as the route pattern, mirroring renderRoute.
|
|
62
|
+
globalThis.fetch = (async (
|
|
63
|
+
input: string,
|
|
64
|
+
init?: RequestInit,
|
|
65
|
+
): Promise<Response> => {
|
|
66
|
+
calls.push({ input, init });
|
|
67
|
+
const pattern = new URL(input, "http://localhost").pathname;
|
|
68
|
+
return jsonResponse(pattern);
|
|
69
|
+
}) as unknown as typeof fetch;
|
|
70
|
+
return {
|
|
71
|
+
calls,
|
|
72
|
+
restore: () => {
|
|
73
|
+
globalThis.fetch = original;
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
11
77
|
|
|
12
78
|
describe("depends", () => {
|
|
13
79
|
test("no-op outside collection", () => {
|
|
@@ -42,3 +108,191 @@ describe("depends", () => {
|
|
|
42
108
|
expect(hasDep("/", "comments")).toBe(true);
|
|
43
109
|
});
|
|
44
110
|
});
|
|
111
|
+
describe("navigate — view transitions", () => {
|
|
112
|
+
test("falls back to direct swap when startViewTransition is missing", async () => {
|
|
113
|
+
const root = document.createElement("div");
|
|
114
|
+
root.id = "grimoire-root";
|
|
115
|
+
document.body.appendChild(root);
|
|
116
|
+
const fetchShim = captureFetch();
|
|
117
|
+
try {
|
|
118
|
+
router.initRouter({ "/": () => document.createElement("main") }, []);
|
|
119
|
+
await router.navigate("/");
|
|
120
|
+
expect(root.childNodes.length).toBeGreaterThan(0);
|
|
121
|
+
} finally {
|
|
122
|
+
fetchShim.restore();
|
|
123
|
+
root.remove();
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test("routes the swap through startViewTransition when available", async () => {
|
|
128
|
+
const root = document.createElement("div");
|
|
129
|
+
root.id = "grimoire-root";
|
|
130
|
+
document.body.appendChild(root);
|
|
131
|
+
let vtCalled = false;
|
|
132
|
+
const docEnv = document as Document & {
|
|
133
|
+
startViewTransition?: (cb: () => void) => unknown;
|
|
134
|
+
};
|
|
135
|
+
docEnv.startViewTransition = (cb: () => void) => {
|
|
136
|
+
vtCalled = true;
|
|
137
|
+
cb();
|
|
138
|
+
return undefined;
|
|
139
|
+
};
|
|
140
|
+
const fetchShim = captureFetch();
|
|
141
|
+
try {
|
|
142
|
+
router.initRouter({ "/vt": () => document.createElement("main") }, []);
|
|
143
|
+
await router.navigate("/vt");
|
|
144
|
+
expect(vtCalled).toBe(true);
|
|
145
|
+
expect(root.childNodes.length).toBeGreaterThan(0);
|
|
146
|
+
} finally {
|
|
147
|
+
delete docEnv.startViewTransition;
|
|
148
|
+
fetchShim.restore();
|
|
149
|
+
root.remove();
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
describe("hover prefetch", () => {
|
|
155
|
+
// The 80ms debounce is real timer logic under test — fake timers advance
|
|
156
|
+
// it deterministically instead of sleeping past it.
|
|
157
|
+
test("plain internal link prefetches route data; preload=off skips", () => {
|
|
158
|
+
vi.useFakeTimers();
|
|
159
|
+
router.initRouter(
|
|
160
|
+
{
|
|
161
|
+
"/": () => document.createElement("div"),
|
|
162
|
+
"/off": () => document.createElement("div"),
|
|
163
|
+
},
|
|
164
|
+
[],
|
|
165
|
+
);
|
|
166
|
+
const fetchShim = captureFetch();
|
|
167
|
+
try {
|
|
168
|
+
const plain = document.createElement("a");
|
|
169
|
+
plain.setAttribute("href", "/");
|
|
170
|
+
document.body.appendChild(plain);
|
|
171
|
+
plain.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
172
|
+
vi.advanceTimersByTime(80);
|
|
173
|
+
expect(fetchShim.calls.length).toBe(1);
|
|
174
|
+
expect(fetchShim.calls[0]?.init?.headers).toEqual({
|
|
175
|
+
"x-grimoire-navigate": "1",
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
const optedOut = document.createElement("a");
|
|
179
|
+
optedOut.setAttribute("href", "/off");
|
|
180
|
+
optedOut.setAttribute("data-sigil-preload", "off");
|
|
181
|
+
document.body.appendChild(optedOut);
|
|
182
|
+
optedOut.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
183
|
+
vi.advanceTimersByTime(80);
|
|
184
|
+
expect(fetchShim.calls.length).toBe(1); // unchanged
|
|
185
|
+
} finally {
|
|
186
|
+
vi.useRealTimers();
|
|
187
|
+
fetchShim.restore();
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test("external links are never prefetched", () => {
|
|
192
|
+
vi.useFakeTimers();
|
|
193
|
+
const fetchShim = captureFetch();
|
|
194
|
+
try {
|
|
195
|
+
const ext = document.createElement("a");
|
|
196
|
+
ext.setAttribute("href", "https://example.com/page");
|
|
197
|
+
document.body.appendChild(ext);
|
|
198
|
+
ext.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
|
199
|
+
vi.advanceTimersByTime(80);
|
|
200
|
+
expect(fetchShim.calls.length).toBe(0);
|
|
201
|
+
} finally {
|
|
202
|
+
vi.useRealTimers();
|
|
203
|
+
fetchShim.restore();
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
describe("enhance — named action URLs", () => {
|
|
209
|
+
test("action starting with ?/ submits to the current pathname", async () => {
|
|
210
|
+
// earlier navigate() tests moved history — reset to a clean path
|
|
211
|
+
window.history.pushState(null, "", "/");
|
|
212
|
+
const { enhance } = await import("../src/client/enhance.ts");
|
|
213
|
+
const calls: string[] = [];
|
|
214
|
+
const original = globalThis.fetch;
|
|
215
|
+
globalThis.fetch = (async (input: string) => {
|
|
216
|
+
calls.push(input);
|
|
217
|
+
return new Response(null, { status: 303, headers: { location: "/" } });
|
|
218
|
+
}) as unknown as typeof fetch;
|
|
219
|
+
|
|
220
|
+
const form = document.createElement("form");
|
|
221
|
+
document.body.appendChild(form);
|
|
222
|
+
const cleanup = enhance(form, { action: "?/create" });
|
|
223
|
+
try {
|
|
224
|
+
form.dispatchEvent(
|
|
225
|
+
new Event("submit", { bubbles: true, cancelable: true }),
|
|
226
|
+
);
|
|
227
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
228
|
+
expect(calls).toEqual([`${window.location.pathname}?/create`]);
|
|
229
|
+
} finally {
|
|
230
|
+
cleanup();
|
|
231
|
+
form.remove();
|
|
232
|
+
globalThis.fetch = original;
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
describe("Page.load — parent()", () => {
|
|
238
|
+
test("parent() merges layoutData entries outermost-first", async () => {
|
|
239
|
+
let seenParent: Record<string, unknown> | undefined;
|
|
240
|
+
const PageWithLoad = Object.assign(
|
|
241
|
+
() => document.createElement("div"),
|
|
242
|
+
{
|
|
243
|
+
load: async (ctx: { parent: () => Promise<Record<string, unknown>> }) => {
|
|
244
|
+
seenParent = await ctx.parent();
|
|
245
|
+
return {};
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
);
|
|
249
|
+
|
|
250
|
+
const original = globalThis.fetch;
|
|
251
|
+
globalThis.fetch = (async (input: string) => {
|
|
252
|
+
const pattern = new URL(input, "http://localhost").pathname;
|
|
253
|
+
return new Response(
|
|
254
|
+
JSON.stringify({
|
|
255
|
+
data: {},
|
|
256
|
+
layoutData: [{ a: 1 }, { b: 2 }],
|
|
257
|
+
params: {},
|
|
258
|
+
pattern,
|
|
259
|
+
head: "",
|
|
260
|
+
}),
|
|
261
|
+
{ headers: { "content-type": "application/json" } },
|
|
262
|
+
);
|
|
263
|
+
}) as unknown as typeof fetch;
|
|
264
|
+
|
|
265
|
+
try {
|
|
266
|
+
router.initRouter({ "/pl": PageWithLoad }, []);
|
|
267
|
+
await router.navigate("/pl");
|
|
268
|
+
expect(seenParent).toEqual({ a: 1, b: 2 });
|
|
269
|
+
} finally {
|
|
270
|
+
globalThis.fetch = original;
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
describe("invalidate", () => {
|
|
276
|
+
test("refetches only on key intersection; empty deps always refetch", async () => {
|
|
277
|
+
router.initRouter({ "/": () => document.createElement("div") }, []);
|
|
278
|
+
const shim = captureFetch();
|
|
279
|
+
try {
|
|
280
|
+
await router.navigate("/"); // establishes lastState.pattern = "/"
|
|
281
|
+
|
|
282
|
+
setDeps("/", ["user:1"]);
|
|
283
|
+
shim.calls.length = 0;
|
|
284
|
+
await router.invalidate("other");
|
|
285
|
+
expect(shim.calls.length).toBe(0); // no intersection → skip
|
|
286
|
+
|
|
287
|
+
await router.invalidate("user:1");
|
|
288
|
+
expect(shim.calls.length).toBe(1); // intersect → refetch
|
|
289
|
+
|
|
290
|
+
clearDeps("/");
|
|
291
|
+
await router.invalidate("anything");
|
|
292
|
+
expect(shim.calls.length).toBe(2); // no deps → conservative refetch
|
|
293
|
+
} finally {
|
|
294
|
+
shim.restore();
|
|
295
|
+
clearDeps("/");
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
});
|
package/test/rendering.test.ts
CHANGED
|
@@ -613,3 +613,116 @@ describe("renderRoute", () => {
|
|
|
613
613
|
expect(html).toContain("dash content");
|
|
614
614
|
});
|
|
615
615
|
});
|
|
616
|
+
describe("load context — await parent()", () => {
|
|
617
|
+
let parentDir: string;
|
|
618
|
+
|
|
619
|
+
beforeAll(async () => {
|
|
620
|
+
parentDir = join(osTmpDir(), `grimoire-parent-${Date.now()}`);
|
|
621
|
+
await mkdir(join(parentDir, "nested", "deep"), { recursive: true });
|
|
622
|
+
|
|
623
|
+
await writeFile(
|
|
624
|
+
join(parentDir, "+layout.tsx"),
|
|
625
|
+
`export default function L({ children }) { return <section innerHTML={children}></section>; }`,
|
|
626
|
+
);
|
|
627
|
+
await writeFile(
|
|
628
|
+
join(parentDir, "+layout.server.ts"),
|
|
629
|
+
`export async function load() { return { a: 1 }; }`,
|
|
630
|
+
);
|
|
631
|
+
await writeFile(
|
|
632
|
+
join(parentDir, "+page.server.ts"),
|
|
633
|
+
`export async function load({ parent }) { return { b: (await parent()).a }; }`,
|
|
634
|
+
);
|
|
635
|
+
await writeFile(
|
|
636
|
+
join(parentDir, "+page.tsx"),
|
|
637
|
+
`export default function P({ data }) { return <div>{JSON.stringify(data)}</div>; }`,
|
|
638
|
+
);
|
|
639
|
+
|
|
640
|
+
await writeFile(
|
|
641
|
+
join(parentDir, "nested", "+layout.tsx"),
|
|
642
|
+
`export default function L({ children }) { return <div innerHTML={children}></div>; }`,
|
|
643
|
+
);
|
|
644
|
+
await writeFile(
|
|
645
|
+
join(parentDir, "nested", "+layout.server.ts"),
|
|
646
|
+
`export async function load({ parent }) { return { b: (await parent()).a + 1 }; }`,
|
|
647
|
+
);
|
|
648
|
+
await writeFile(
|
|
649
|
+
join(parentDir, "nested", "deep", "+page.server.ts"),
|
|
650
|
+
`export async function load({ parent }) { const p = await parent(); return { c: p.a + p.b }; }`,
|
|
651
|
+
);
|
|
652
|
+
await writeFile(
|
|
653
|
+
join(parentDir, "nested", "deep", "+page.tsx"),
|
|
654
|
+
`export default function P({ data }) { return <div>{JSON.stringify(data)}</div>; }`,
|
|
655
|
+
);
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
afterAll(async () => {
|
|
659
|
+
await rm(parentDir, { recursive: true });
|
|
660
|
+
});
|
|
661
|
+
|
|
662
|
+
test("page load sees layout data via await parent()", async () => {
|
|
663
|
+
const tree = await scanRoutes(parentDir);
|
|
664
|
+
const matched = matchRoute(tree, new URL("http://localhost/"));
|
|
665
|
+
const html = await readStream(
|
|
666
|
+
await renderRoute(matched!, new Request("http://localhost/")),
|
|
667
|
+
);
|
|
668
|
+
expect(html).toContain('"b":1');
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
test("nested layouts accumulate outermost-first", async () => {
|
|
672
|
+
const tree = await scanRoutes(parentDir);
|
|
673
|
+
const matched = matchRoute(
|
|
674
|
+
tree,
|
|
675
|
+
new URL("http://localhost/nested/deep"),
|
|
676
|
+
);
|
|
677
|
+
const html = await readStream(
|
|
678
|
+
await renderRoute(matched!, new Request("http://localhost/nested/deep")),
|
|
679
|
+
);
|
|
680
|
+
// outer a=1, inner b=a+1=2, page c=a+b=3
|
|
681
|
+
expect(html).toContain('"c":3');
|
|
682
|
+
});
|
|
683
|
+
});
|
|
684
|
+
|
|
685
|
+
describe("server-side depends()", () => {
|
|
686
|
+
let depsDir: string;
|
|
687
|
+
|
|
688
|
+
beforeAll(async () => {
|
|
689
|
+
depsDir = join(osTmpDir(), `grimoire-deps-${Date.now()}`);
|
|
690
|
+
await mkdir(depsDir, { recursive: true });
|
|
691
|
+
const depsModule = join(
|
|
692
|
+
import.meta.dir,
|
|
693
|
+
"..",
|
|
694
|
+
"src",
|
|
695
|
+
"client",
|
|
696
|
+
"deps.ts",
|
|
697
|
+
)
|
|
698
|
+
.replace(/\\/g, "/")
|
|
699
|
+
.replace(/^([A-Za-z]:)/, "file:///$1");
|
|
700
|
+
await writeFile(
|
|
701
|
+
join(depsDir, "+page.server.ts"),
|
|
702
|
+
[
|
|
703
|
+
"export async function load() {",
|
|
704
|
+
` const { depends } = await import("${depsModule}");`,
|
|
705
|
+
' depends("user:1");',
|
|
706
|
+
" return { x: 1 };",
|
|
707
|
+
"}",
|
|
708
|
+
].join("\n"),
|
|
709
|
+
);
|
|
710
|
+
await writeFile(
|
|
711
|
+
join(depsDir, "+page.tsx"),
|
|
712
|
+
`export default function P({ data }) { return <div>{data.x}</div>; }`,
|
|
713
|
+
);
|
|
714
|
+
});
|
|
715
|
+
|
|
716
|
+
afterAll(async () => {
|
|
717
|
+
await rm(depsDir, { recursive: true });
|
|
718
|
+
});
|
|
719
|
+
|
|
720
|
+
test("depends keys land in the state payload", async () => {
|
|
721
|
+
const tree = await scanRoutes(depsDir);
|
|
722
|
+
const matched = matchRoute(tree, new URL("http://localhost/"));
|
|
723
|
+
const html = await readStream(
|
|
724
|
+
await renderRoute(matched!, new Request("http://localhost/")),
|
|
725
|
+
);
|
|
726
|
+
expect(html).toContain('"deps":["user:1"]');
|
|
727
|
+
});
|
|
728
|
+
});
|
package/test/routing.test.ts
CHANGED
|
@@ -1,21 +1,30 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
2
|
import { matchRoute } from "../src/routing/router";
|
|
3
|
+
import { generateManifest } from "../src/routing/manifest-gen";
|
|
3
4
|
import type { RouteFile, RouteTree } from "../src/routing/scanner";
|
|
4
5
|
|
|
5
6
|
const makeRoute = (path: string, type: RouteFile["type"]): RouteFile => ({
|
|
6
7
|
path,
|
|
7
8
|
filePath: `/app/routes${path}`,
|
|
9
|
+
clientPath: `/src/routes${path}`,
|
|
8
10
|
type,
|
|
9
11
|
paramNames: path
|
|
10
12
|
.split("/")
|
|
11
|
-
.filter((p) => p.startsWith(":"))
|
|
13
|
+
.filter((p) => p.startsWith(":") && !p.endsWith("?"))
|
|
12
14
|
.map((p) => p.slice(1)),
|
|
15
|
+
optionalParamNames: path
|
|
16
|
+
.split("/")
|
|
17
|
+
.filter((p) => p.startsWith(":") && p.endsWith("?"))
|
|
18
|
+
.map((p) => p.slice(1, -1)),
|
|
13
19
|
restParamNames: path
|
|
14
20
|
.split("/")
|
|
15
21
|
.filter((p) => p.startsWith("*"))
|
|
16
22
|
.map((p) => p.slice(1)),
|
|
23
|
+
paramMatchers: {},
|
|
17
24
|
});
|
|
18
25
|
|
|
26
|
+
const noMatcherFiles = { paramMatcherFiles: [] as never[] };
|
|
27
|
+
|
|
19
28
|
const tree: RouteTree = {
|
|
20
29
|
routes: [
|
|
21
30
|
makeRoute("/", "page"),
|
|
@@ -27,6 +36,7 @@ const tree: RouteTree = {
|
|
|
27
36
|
layouts: [makeRoute("/", "layout"), makeRoute("/blog", "layout")],
|
|
28
37
|
servers: [makeRoute("/api/todos", "server")],
|
|
29
38
|
errors: [],
|
|
39
|
+
...noMatcherFiles,
|
|
30
40
|
};
|
|
31
41
|
|
|
32
42
|
describe("matchRoute", () => {
|
|
@@ -54,6 +64,7 @@ describe("matchRoute — rest params (catch-all)", () => {
|
|
|
54
64
|
layouts: [],
|
|
55
65
|
servers: [makeRoute("/docs/*path", "server")],
|
|
56
66
|
errors: [],
|
|
67
|
+
...noMatcherFiles,
|
|
57
68
|
};
|
|
58
69
|
|
|
59
70
|
test("matches single remaining segment", () => {
|
|
@@ -79,3 +90,105 @@ describe("matchRoute — rest params (catch-all)", () => {
|
|
|
79
90
|
expect(match).toBeNull();
|
|
80
91
|
});
|
|
81
92
|
});
|
|
93
|
+
|
|
94
|
+
describe("matchRoute — optional params", () => {
|
|
95
|
+
// ordered as the scanner would: static (0) < optional (1) < required (2)
|
|
96
|
+
const optTree: RouteTree = {
|
|
97
|
+
routes: [
|
|
98
|
+
makeRoute("/about", "simple"),
|
|
99
|
+
makeRoute("/:lang?", "page"),
|
|
100
|
+
makeRoute("/:slug", "page"),
|
|
101
|
+
],
|
|
102
|
+
layouts: [],
|
|
103
|
+
servers: [],
|
|
104
|
+
errors: [],
|
|
105
|
+
...noMatcherFiles,
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
test("optional segment consumes one path segment", () => {
|
|
109
|
+
const match = matchRoute(optTree, new URL("http://localhost/en"));
|
|
110
|
+
expect(match?.route.path).toBe("/:lang?");
|
|
111
|
+
expect(match?.params).toEqual({ lang: "en" });
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("optional segment matches zero segments", () => {
|
|
115
|
+
const match = matchRoute(optTree, new URL("http://localhost/"));
|
|
116
|
+
expect(match?.route.path).toBe("/:lang?");
|
|
117
|
+
expect(match?.params).toEqual({});
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("static beats optional", () => {
|
|
121
|
+
const match = matchRoute(optTree, new URL("http://localhost/about"));
|
|
122
|
+
expect(match?.route.path).toBe("/about");
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("optional beats required param", () => {
|
|
126
|
+
const match = matchRoute(optTree, new URL("http://localhost/en"));
|
|
127
|
+
expect(match?.route.path).toBe("/:lang?");
|
|
128
|
+
expect(match?.route.path).not.toBe("/:slug");
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test("mid-pattern optional backtracks: /about matches /[[lang]]/about", () => {
|
|
132
|
+
const nested: RouteTree = {
|
|
133
|
+
routes: [makeRoute("/:lang?/about", "page")],
|
|
134
|
+
layouts: [],
|
|
135
|
+
servers: [],
|
|
136
|
+
errors: [],
|
|
137
|
+
...noMatcherFiles,
|
|
138
|
+
};
|
|
139
|
+
const zero = matchRoute(nested, new URL("http://localhost/about"));
|
|
140
|
+
expect(zero?.params).toEqual({});
|
|
141
|
+
const one = matchRoute(nested, new URL("http://localhost/en/about"));
|
|
142
|
+
expect(one?.params).toEqual({ lang: "en" });
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
describe("matchRoute — custom matchers", () => {
|
|
147
|
+
const intMatch = (v: string) => /^\d+$/.test(v);
|
|
148
|
+
const matcherTree: RouteTree = {
|
|
149
|
+
routes: [makeRoute("/post/:id", "page")],
|
|
150
|
+
layouts: [],
|
|
151
|
+
servers: [],
|
|
152
|
+
errors: [],
|
|
153
|
+
...noMatcherFiles,
|
|
154
|
+
};
|
|
155
|
+
matcherTree.routes[0]!.paramMatchers = { id: "int" };
|
|
156
|
+
|
|
157
|
+
test("matcher passes → route matches", () => {
|
|
158
|
+
const match = matchRoute(matcherTree, new URL("http://localhost/post/42"), {
|
|
159
|
+
int: intMatch,
|
|
160
|
+
});
|
|
161
|
+
expect(match?.params).toEqual({ id: "42" });
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test("matcher fails → route is rejected (404)", () => {
|
|
165
|
+
const match = matchRoute(matcherTree, new URL("http://localhost/post/abc"), {
|
|
166
|
+
int: intMatch,
|
|
167
|
+
});
|
|
168
|
+
expect(match).toBeNull();
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test("missing matcher module rejects the route", () => {
|
|
172
|
+
const match = matchRoute(matcherTree, new URL("http://localhost/post/42"));
|
|
173
|
+
expect(match).toBeNull();
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
describe("generateManifest — param matchers", () => {
|
|
178
|
+
test("emits eager matcher imports and record", () => {
|
|
179
|
+
const manifest = generateManifest(
|
|
180
|
+
[makeRoute("/", "page")],
|
|
181
|
+
undefined,
|
|
182
|
+
[{ name: "int", filePath: "/app/params/int.ts" }],
|
|
183
|
+
);
|
|
184
|
+
expect(manifest).toContain('import * as __param_int from "/app/params/int.ts"');
|
|
185
|
+
expect(manifest).toContain('"int": __param_int.match');
|
|
186
|
+
expect(manifest).toContain("export const matchers = {");
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test("emits matchers record even when none exist", () => {
|
|
190
|
+
const manifest = generateManifest([makeRoute("/", "page")]);
|
|
191
|
+
expect(manifest).toMatch(/export const matchers = \{\s*\};/);
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
|
package/test/scanning.test.ts
CHANGED
|
@@ -7,32 +7,32 @@ import { filePathToRoutePath, scanRoutes } from "../src/routing/scanner";
|
|
|
7
7
|
describe("File scanning", () => {
|
|
8
8
|
test("index.tsx → /", () => {
|
|
9
9
|
expect(filePathToRoutePath("/app/routes/index.tsx", "/app/routes")).toEqual(
|
|
10
|
-
{ pattern: "/", params: [], restParams: [] },
|
|
10
|
+
{ pattern: "/", params: [], optionalParams: [], paramMatchers: {}, restParams: [] },
|
|
11
11
|
);
|
|
12
12
|
});
|
|
13
13
|
|
|
14
14
|
test("about.tsx → /about", () => {
|
|
15
15
|
expect(filePathToRoutePath("/app/routes/about.tsx", "/app/routes")).toEqual(
|
|
16
|
-
{ pattern: "/about", params: [], restParams: [] },
|
|
16
|
+
{ pattern: "/about", params: [], optionalParams: [], paramMatchers: {}, restParams: [] },
|
|
17
17
|
);
|
|
18
18
|
});
|
|
19
19
|
|
|
20
20
|
test("[slug].tsx → /:slug", () => {
|
|
21
21
|
expect(
|
|
22
22
|
filePathToRoutePath("/app/routes/[slug].tsx", "/app/routes"),
|
|
23
|
-
).toEqual({ pattern: "/:slug", params: ["slug"], restParams: [] });
|
|
23
|
+
).toEqual({ pattern: "/:slug", params: ["slug"], optionalParams: [], paramMatchers: {}, restParams: [] });
|
|
24
24
|
});
|
|
25
25
|
|
|
26
26
|
test("blog/+page.tsx → /blog", () => {
|
|
27
27
|
expect(
|
|
28
28
|
filePathToRoutePath("/app/routes/blog/+page.tsx", "/app/routes"),
|
|
29
|
-
).toEqual({ pattern: "/blog", params: [], restParams: [] });
|
|
29
|
+
).toEqual({ pattern: "/blog", params: [], optionalParams: [], paramMatchers: {}, restParams: [] });
|
|
30
30
|
});
|
|
31
31
|
|
|
32
32
|
test("blog/[slug]/+page.tsx → /blog/:slug", () => {
|
|
33
33
|
expect(
|
|
34
34
|
filePathToRoutePath("/app/routes/blog/[slug]/+page.tsx", "/app/routes"),
|
|
35
|
-
).toEqual({ pattern: "/blog/:slug", params: ["slug"], restParams: [] });
|
|
35
|
+
).toEqual({ pattern: "/blog/:slug", params: ["slug"], optionalParams: [], paramMatchers: {}, restParams: [] });
|
|
36
36
|
});
|
|
37
37
|
|
|
38
38
|
test("blog/[slug]/+page.server.ts → /blog/:slug", () => {
|
|
@@ -41,25 +41,25 @@ describe("File scanning", () => {
|
|
|
41
41
|
"/app/routes/blog/[slug]/+page.server.ts",
|
|
42
42
|
"/app/routes",
|
|
43
43
|
),
|
|
44
|
-
).toEqual({ pattern: "/blog/:slug", params: ["slug"], restParams: [] });
|
|
44
|
+
).toEqual({ pattern: "/blog/:slug", params: ["slug"], optionalParams: [], paramMatchers: {}, restParams: [] });
|
|
45
45
|
});
|
|
46
46
|
|
|
47
47
|
test("+layout.tsx → /", () => {
|
|
48
48
|
expect(
|
|
49
49
|
filePathToRoutePath("/app/routes/+layout.tsx", "/app/routes"),
|
|
50
|
-
).toEqual({ pattern: "/", params: [], restParams: [] });
|
|
50
|
+
).toEqual({ pattern: "/", params: [], optionalParams: [], paramMatchers: {}, restParams: [] });
|
|
51
51
|
});
|
|
52
52
|
|
|
53
53
|
test("nested +layout.tsx → /blog", () => {
|
|
54
54
|
expect(
|
|
55
55
|
filePathToRoutePath("/app/routes/blog/+layout.tsx", "/app/routes"),
|
|
56
|
-
).toEqual({ pattern: "/blog", params: [], restParams: [] });
|
|
56
|
+
).toEqual({ pattern: "/blog", params: [], optionalParams: [], paramMatchers: {}, restParams: [] });
|
|
57
57
|
});
|
|
58
58
|
|
|
59
59
|
test("[...rest].tsx → /*rest (catch-all)", () => {
|
|
60
60
|
expect(
|
|
61
61
|
filePathToRoutePath("/app/routes/[...rest].tsx", "/app/routes"),
|
|
62
|
-
).toEqual({ pattern: "/*rest", params: [], restParams: ["rest"] });
|
|
62
|
+
).toEqual({ pattern: "/*rest", params: [], optionalParams: [], paramMatchers: {}, restParams: ["rest"] });
|
|
63
63
|
});
|
|
64
64
|
|
|
65
65
|
test("docs/[...path]/+server.ts → /docs/*path (nested catch-all)", () => {
|
|
@@ -68,7 +68,7 @@ describe("File scanning", () => {
|
|
|
68
68
|
"/app/routes/docs/[...path]/+server.ts",
|
|
69
69
|
"/app/routes",
|
|
70
70
|
),
|
|
71
|
-
).toEqual({ pattern: "/docs/*path", params: [], restParams: ["path"] });
|
|
71
|
+
).toEqual({ pattern: "/docs/*path", params: [], optionalParams: [], paramMatchers: {}, restParams: ["path"] });
|
|
72
72
|
});
|
|
73
73
|
|
|
74
74
|
test("about/index.tsx, about/+page.tsx, and about.tsx all resolve to /about", () => {
|
|
@@ -119,6 +119,60 @@ describe("File scanning", () => {
|
|
|
119
119
|
);
|
|
120
120
|
expect(pattern).toBe("/login");
|
|
121
121
|
});
|
|
122
|
+
|
|
123
|
+
test("[[lang]]/index.tsx → /:lang? (optional)", () => {
|
|
124
|
+
const result = filePathToRoutePath(
|
|
125
|
+
"/app/routes/[[lang]]/index.tsx",
|
|
126
|
+
"/app/routes",
|
|
127
|
+
);
|
|
128
|
+
expect(result.pattern).toBe("/:lang?");
|
|
129
|
+
expect(result.optionalParams).toEqual(["lang"]);
|
|
130
|
+
expect(result.params).toEqual([]);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test("optional and required params are collected separately", () => {
|
|
134
|
+
const result = filePathToRoutePath(
|
|
135
|
+
"/app/routes/[[lang]]/blog/[slug]/+page.tsx",
|
|
136
|
+
"/app/routes",
|
|
137
|
+
);
|
|
138
|
+
expect(result.pattern).toBe("/:lang?/blog/:slug");
|
|
139
|
+
expect(result.optionalParams).toEqual(["lang"]);
|
|
140
|
+
expect(result.params).toEqual(["slug"]);
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
describe("Custom param matchers", () => {
|
|
145
|
+
test("[id=int].tsx → /:id with matcher recorded", () => {
|
|
146
|
+
const result = filePathToRoutePath(
|
|
147
|
+
"/app/routes/post/[id=int].tsx",
|
|
148
|
+
"/app/routes",
|
|
149
|
+
);
|
|
150
|
+
expect(result.pattern).toBe("/post/:id");
|
|
151
|
+
expect(result.paramMatchers).toEqual({ id: "int" });
|
|
152
|
+
expect(result.params).toEqual(["id"]);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test("scanRoutes picks up src/params/*.ts beside src/routes", async () => {
|
|
156
|
+
const root = join(tmpdir(), `grimoire-matchers-${Date.now()}`);
|
|
157
|
+
const routesDir = join(root, "routes");
|
|
158
|
+
const paramsDir = join(root, "params");
|
|
159
|
+
await mkdir(join(routesDir, "post"), { recursive: true });
|
|
160
|
+
await mkdir(paramsDir, { recursive: true });
|
|
161
|
+
await writeFile(
|
|
162
|
+
join(routesDir, "post", "[id=int].tsx"),
|
|
163
|
+
"export default () => null",
|
|
164
|
+
);
|
|
165
|
+
await writeFile(
|
|
166
|
+
join(paramsDir, "int.ts"),
|
|
167
|
+
"export function match(v: string) { return /^\\d+$/.test(v); }",
|
|
168
|
+
);
|
|
169
|
+
const tree = await scanRoutes(routesDir);
|
|
170
|
+
expect(tree.paramMatcherFiles).toEqual([
|
|
171
|
+
{ name: "int", filePath: join(paramsDir, "int.ts") },
|
|
172
|
+
]);
|
|
173
|
+
expect(tree.routes[0]?.paramMatchers).toEqual({ id: "int" });
|
|
174
|
+
await rm(root, { recursive: true });
|
|
175
|
+
});
|
|
122
176
|
});
|
|
123
177
|
|
|
124
178
|
describe("Duplicate route detection", () => {
|