@sigil-dev/grimoire 0.9.3 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/index.ts +37 -35
  2. package/package.json +9 -12
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +36 -19
  6. package/src/client/enhance.ts +102 -98
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +2 -2
  9. package/src/client/router.ts +174 -68
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +215 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +109 -114
  14. package/src/dev/hmr-client.ts +202 -185
  15. package/src/dev/hmr-server.ts +261 -187
  16. package/src/dev/loader.ts +120 -47
  17. package/src/dev/paths.ts +14 -14
  18. package/src/dev/resolve.ts +70 -0
  19. package/src/dev/runtime-bundle.ts +52 -52
  20. package/src/dev/scan.ts +78 -0
  21. package/src/dev/watcher.ts +69 -47
  22. package/src/env/dynamic-private.ts +19 -19
  23. package/src/env/dynamic-public.ts +22 -22
  24. package/src/env/index.ts +25 -25
  25. package/src/env/plugin.ts +19 -19
  26. package/src/env/private.ts +5 -5
  27. package/src/env/public.ts +7 -7
  28. package/src/env/typegen.ts +61 -61
  29. package/src/headers.ts +114 -114
  30. package/src/integrations/vite.ts +73 -73
  31. package/src/logger/index.ts +4 -4
  32. package/src/logger/instance.ts +6 -6
  33. package/src/logger/logger.ts +113 -113
  34. package/src/logger/request-middleware.ts +24 -24
  35. package/src/logger/transports.ts +117 -117
  36. package/src/logger/types.ts +39 -39
  37. package/src/rendering/head.ts +52 -47
  38. package/src/rendering/hydrate.ts +159 -138
  39. package/src/rendering/index.ts +140 -18
  40. package/src/rendering/ssrPlugin.ts +78 -69
  41. package/src/routing/manifest-gen.ts +13 -1
  42. package/src/routing/router.ts +135 -109
  43. package/src/routing/scanner.ts +196 -141
  44. package/src/routing/transform-routes.ts +102 -102
  45. package/src/sentinels/error.ts +52 -52
  46. package/src/sentinels/fail.ts +41 -41
  47. package/src/sentinels/redirect.ts +35 -35
  48. package/src/server/build.ts +250 -243
  49. package/src/server/context.ts +10 -10
  50. package/src/server/cookie-utils.ts +66 -66
  51. package/src/server/coordinator.ts +364 -364
  52. package/src/server/hooks.ts +114 -114
  53. package/src/server/index.ts +711 -655
  54. package/src/server/interactive.ts +56 -56
  55. package/src/server/plugins.ts +121 -121
  56. package/src/server/worker.ts +58 -58
  57. package/src/typegen/index.ts +389 -356
  58. package/src/types.ts +286 -282
  59. package/test/client-router.test.ts +295 -44
  60. package/test/context.test.ts +52 -52
  61. package/test/env.test.ts +90 -90
  62. package/test/exports.test.ts +37 -37
  63. package/test/fail.test.ts +46 -46
  64. package/test/headers.test.ts +100 -100
  65. package/test/hmr.test.ts +426 -0
  66. package/test/hydration.test.ts +119 -119
  67. package/test/middleware.test.ts +223 -223
  68. package/test/preload.ts +5 -5
  69. package/test/redirect-error.test.ts +112 -112
  70. package/test/rendering.test.ts +719 -615
  71. package/test/routing.test.ts +197 -81
  72. package/test/scanning.test.ts +314 -200
  73. package/test/scope.test.ts +195 -195
  74. package/test/server.test.ts +360 -249
  75. package/test/streaming.test.ts +242 -125
  76. package/test/transform-routes.test.ts +87 -84
  77. package/test/typegen.test.ts +697 -682
  78. package/tsconfig.json +10 -10
@@ -0,0 +1,426 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { DevGraph } from "../src/dev/graph";
6
+ import {
7
+ type DevContext,
8
+ HmrServer,
9
+ handleChange,
10
+ } from "../src/dev/hmr-server";
11
+ import { normalizePath } from "../src/dev/paths";
12
+ import { resolveProjectImport } from "../src/dev/resolve";
13
+ import { crawlFrom } from "../src/dev/scan";
14
+ import type { RouteFile } from "../src/routing/scanner";
15
+
16
+ const route = (
17
+ path: string,
18
+ filePath: string,
19
+ type: RouteFile["type"],
20
+ ): RouteFile => ({
21
+ path,
22
+ filePath,
23
+ clientPath: filePath,
24
+ type,
25
+ paramNames: [],
26
+ optionalParamNames: [],
27
+ restParamNames: [],
28
+ paramMatchers: {},
29
+ });
30
+
31
+ interface Fixture {
32
+ root: string;
33
+ graph: DevGraph;
34
+ files: {
35
+ page: string;
36
+ layout: string;
37
+ pageServer: string;
38
+ beacon: string;
39
+ sigil: string;
40
+ other: string;
41
+ };
42
+ /** Route-ish files the graph is crawled from. */
43
+ entries: string[];
44
+ cleanup: () => Promise<void>;
45
+ }
46
+
47
+ /**
48
+ * A project with a page that renders a component which itself renders another
49
+ * component: page → Beacon → Sigil. The two-hop chain is the case that used to
50
+ * fall through to a full reload.
51
+ */
52
+ async function fixture(): Promise<Fixture> {
53
+ const root = await mkdtemp(join(tmpdir(), "grimoire-hmr-"));
54
+ const routes = join(root, "src/routes");
55
+ const lib = join(root, "src/lib");
56
+ await mkdir(routes, { recursive: true });
57
+ await mkdir(lib, { recursive: true });
58
+
59
+ const page = join(routes, "+page.tsx");
60
+ const layout = join(routes, "+layout.tsx");
61
+ const pageServer = join(routes, "+page.server.ts");
62
+ const beacon = join(lib, "Beacon.tsx");
63
+ const sigil = join(lib, "Sigil.tsx");
64
+ const other = join(routes, "other/+page.tsx");
65
+ await mkdir(join(routes, "other"), { recursive: true });
66
+
67
+ await writeFile(
68
+ page,
69
+ `import Beacon from "../lib/Beacon.tsx";
70
+ const Page = () => <div><Beacon /></div>;
71
+ export default Page;`,
72
+ );
73
+ await writeFile(
74
+ layout,
75
+ `const Layout = (props) => <main>{props.children}</main>;
76
+ export default Layout;`,
77
+ );
78
+ await writeFile(pageServer, `export const load = async () => ({ n: 1 });`);
79
+ await writeFile(
80
+ beacon,
81
+ `import Sigil from "$lib/Sigil.tsx";
82
+ const Beacon = () => <p><Sigil /></p>;
83
+ export default Beacon;`,
84
+ );
85
+ await writeFile(
86
+ sigil,
87
+ `const Sigil = () => <em>alpha</em>;
88
+ export default Sigil;`,
89
+ );
90
+ await writeFile(
91
+ other,
92
+ `import Beacon from "$lib/Beacon.tsx";
93
+ const Other = () => <Beacon />;
94
+ export default Other;`,
95
+ );
96
+
97
+ const graph = new DevGraph();
98
+ const entries = [page, layout, pageServer, beacon, other];
99
+ graph.markRoute(page, route("/", page, "page"));
100
+ graph.markRoute(layout, route("/", layout, "layout"));
101
+ graph.markRoute(pageServer, route("/", pageServer, "pageServer"));
102
+ graph.markRoute(other, route("/other", other, "page"));
103
+ await crawlFrom([page, layout, pageServer, other], {
104
+ graph,
105
+ projectRoot: root,
106
+ aliases: {},
107
+ });
108
+
109
+ return {
110
+ root,
111
+ graph,
112
+ files: { page, layout, pageServer, beacon, sigil, other },
113
+ entries,
114
+ cleanup: () => rm(root, { recursive: true, force: true }),
115
+ };
116
+ }
117
+
118
+ describe("resolveProjectImport", () => {
119
+ test("resolves relative, extensionless, index and $lib specifiers", async () => {
120
+ const f = await fixture();
121
+ try {
122
+ const from = f.files.page;
123
+ expect(resolveProjectImport("../lib/Beacon.tsx", from, f.root)).toBe(
124
+ f.files.beacon,
125
+ );
126
+ expect(resolveProjectImport("../lib/Beacon", from, f.root)).toBe(
127
+ f.files.beacon,
128
+ );
129
+ expect(resolveProjectImport("$lib/Sigil", from, f.root)).toBe(
130
+ f.files.sigil,
131
+ );
132
+ await mkdir(join(f.root, "src/lib/deep"), { recursive: true });
133
+ await writeFile(
134
+ join(f.root, "src/lib/deep/index.ts"),
135
+ "export const a=1;",
136
+ );
137
+ expect(resolveProjectImport("$lib/deep", from, f.root)).toBe(
138
+ join(f.root, "src/lib/deep/index.ts"),
139
+ );
140
+ } finally {
141
+ await f.cleanup();
142
+ }
143
+ });
144
+
145
+ test("resolves configured aliases and skips externals", async () => {
146
+ const f = await fixture();
147
+ try {
148
+ const from = f.files.page;
149
+ expect(
150
+ resolveProjectImport("@ui/Sigil", from, f.root, { "@ui": "src/lib" }),
151
+ ).toBe(f.files.sigil);
152
+ expect(
153
+ resolveProjectImport("@sigil-dev/runtime", from, f.root),
154
+ ).toBeNull();
155
+ expect(
156
+ resolveProjectImport("$env/static/public", from, f.root),
157
+ ).toBeNull();
158
+ expect(resolveProjectImport("some-npm-package", from, f.root)).toBeNull();
159
+ expect(resolveProjectImport("./nope.tsx", from, f.root)).toBeNull();
160
+ } finally {
161
+ await f.cleanup();
162
+ }
163
+ });
164
+ });
165
+
166
+ describe("DevGraph", () => {
167
+ test("crawls transitively and traces a two-hop component to its routes", async () => {
168
+ const f = await fixture();
169
+ try {
170
+ const patterns = f.graph
171
+ .affectedRoutes(f.files.sigil)
172
+ .map((r) => `${r.type} ${r.path}`)
173
+ .sort();
174
+ expect(patterns).toEqual(["page /", "page /other"]);
175
+ } finally {
176
+ await f.cleanup();
177
+ }
178
+ });
179
+
180
+ test("invalidate bumps the whole importer chain, nothing else", async () => {
181
+ const f = await fixture();
182
+ try {
183
+ const bumped = f.graph.invalidate(f.files.sigil);
184
+ expect(bumped.sort()).toEqual(
185
+ [f.files.sigil, f.files.beacon, f.files.page, f.files.other]
186
+ .map(normalizePath)
187
+ .sort(),
188
+ );
189
+ expect(f.graph.get(f.files.sigil)?.version).toBe(1);
190
+ expect(f.graph.get(f.files.page)?.version).toBe(1);
191
+ expect(f.graph.get(f.files.other)?.version).toBe(1);
192
+ // a layout that imports nothing from the chain stays at its version
193
+ expect(f.graph.get(f.files.layout)?.version).toBe(0);
194
+ } finally {
195
+ await f.cleanup();
196
+ }
197
+ });
198
+
199
+ test("setImports drops back-links for removed imports", async () => {
200
+ const f = await fixture();
201
+ try {
202
+ await writeFile(
203
+ f.files.beacon,
204
+ `const Beacon = () => <p>no more Sigil</p>;
205
+ export default Beacon;`,
206
+ );
207
+ await crawlFrom([f.files.beacon], {
208
+ graph: f.graph,
209
+ projectRoot: f.root,
210
+ aliases: {},
211
+ });
212
+ expect(f.graph.get(f.files.sigil)?.importers.size).toBe(0);
213
+ expect(f.graph.affectedRoutes(f.files.sigil)).toEqual([]);
214
+ } finally {
215
+ await f.cleanup();
216
+ }
217
+ });
218
+ });
219
+
220
+ interface RouteEntry {
221
+ pattern: string;
222
+ modUrl: string;
223
+ version: number;
224
+ }
225
+
226
+ interface LayoutEntry {
227
+ path: string;
228
+ modUrl: string;
229
+ version: number;
230
+ }
231
+
232
+ interface Payload {
233
+ kind: string;
234
+ entries?: RouteEntry[] | LayoutEntry[];
235
+ hash?: string;
236
+ text?: string;
237
+ }
238
+
239
+ interface Batch {
240
+ kinds: string[];
241
+ payloads: Payload[];
242
+ }
243
+
244
+ interface Recorder {
245
+ hmr: HmrServer;
246
+ batches: Batch[];
247
+ errors: string[];
248
+ }
249
+
250
+ /** Collects what the HMR server would have pushed to the browser. */
251
+ function recorder(): Recorder {
252
+ const hmr = new HmrServer();
253
+ const batches: Batch[] = [];
254
+ const errors: string[] = [];
255
+ hmr.batch = (raw: object[]) => {
256
+ // handleChange builds these literals; the shape is ours, not external
257
+ const payloads = raw as Payload[];
258
+ batches.push({ kinds: payloads.map((p) => p.kind), payloads });
259
+ };
260
+ hmr.reload = () => batches.push({ kinds: ["reload"], payloads: [] });
261
+ hmr.error = (message: string) => errors.push(message);
262
+ return { hmr, batches, errors };
263
+ }
264
+
265
+ interface Harness extends Recorder {
266
+ ctx: DevContext;
267
+ rebuilds: () => number;
268
+ }
269
+
270
+ function context(f: Fixture): Harness {
271
+ const rec = recorder();
272
+ let rebuilds = 0;
273
+ const ctx: DevContext = {
274
+ graph: f.graph,
275
+ hmr: rec.hmr,
276
+ projectRoot: f.root,
277
+ aliases: {},
278
+ entries: () => f.entries,
279
+ rebuild: async () => {
280
+ rebuilds++;
281
+ },
282
+ scheduleRebuild: () => {
283
+ rebuilds++;
284
+ },
285
+ };
286
+ return { ...rec, ctx, rebuilds: () => rebuilds };
287
+ }
288
+
289
+ describe("handleChange", () => {
290
+ test("a component edit swaps every route that renders it", async () => {
291
+ const f = await fixture();
292
+ const c = await context(f);
293
+ try {
294
+ await handleChange(f.files.sigil, c.ctx);
295
+
296
+ expect(c.errors).toEqual([]);
297
+ expect(c.batches).toHaveLength(1);
298
+ expect(c.batches[0]!.kinds).toEqual(["routes"]);
299
+ // the swapped module is the *route*, not the edited component: the
300
+ // client route table is keyed by pattern and holds page components
301
+ const entries = c.batches[0]!.payloads[0]!.entries ?? [];
302
+ expect(
303
+ [...entries].sort((a, b) => a.modUrl.localeCompare(b.modUrl)),
304
+ ).toEqual([
305
+ { pattern: "/", modUrl: "src/routes/+page.tsx.js", version: 1 },
306
+ {
307
+ pattern: "/other",
308
+ modUrl: "src/routes/other/+page.tsx.js",
309
+ version: 1,
310
+ },
311
+ ]);
312
+ } finally {
313
+ await f.cleanup();
314
+ }
315
+ });
316
+
317
+ test("a layout edit sends a layout payload keyed by layout path", async () => {
318
+ const f = await fixture();
319
+ const c = await context(f);
320
+ try {
321
+ await handleChange(f.files.layout, c.ctx);
322
+
323
+ expect(c.batches[0]!.kinds).toEqual(["layouts"]);
324
+ expect(c.batches[0]!.payloads[0]!.entries).toEqual([
325
+ { path: "/", modUrl: "src/routes/+layout.tsx.js", version: 1 },
326
+ ]);
327
+ } finally {
328
+ await f.cleanup();
329
+ }
330
+ });
331
+
332
+ test("a server load edit invalidates data instead of swapping code", async () => {
333
+ const f = await fixture();
334
+ const c = await context(f);
335
+ try {
336
+ await handleChange(f.files.pageServer, c.ctx);
337
+
338
+ expect(c.batches[0]!.kinds).toEqual(["invalidate"]);
339
+ expect(f.graph.get(f.files.pageServer)?.version).toBe(1);
340
+ } finally {
341
+ await f.cleanup();
342
+ }
343
+ });
344
+
345
+ test("a page that also exports load both swaps and refetches", async () => {
346
+ const f = await fixture();
347
+ const c = await context(f);
348
+ try {
349
+ await writeFile(
350
+ f.files.page,
351
+ `import Beacon from "../lib/Beacon.tsx";
352
+ export const load = async () => ({ n: 2 });
353
+ const Page = () => <div><Beacon /></div>;
354
+ export default Page;`,
355
+ );
356
+ await handleChange(f.files.page, c.ctx);
357
+
358
+ expect(c.batches[0]!.kinds).toEqual(["routes", "invalidate"]);
359
+ } finally {
360
+ await f.cleanup();
361
+ }
362
+ });
363
+
364
+ test("a syntax error reports an overlay and bumps nothing", async () => {
365
+ const f = await fixture();
366
+ const c = await context(f);
367
+ try {
368
+ await writeFile(f.files.sigil, `const Sigil = () => <em>alpha</em>))));`);
369
+ await handleChange(f.files.sigil, c.ctx);
370
+
371
+ expect(c.batches).toEqual([]);
372
+ expect(c.errors).toHaveLength(1);
373
+ // the previous version stays live for the browser and for SSR
374
+ expect(f.graph.get(f.files.sigil)?.version).toBe(0);
375
+ expect(f.graph.get(f.files.page)?.version).toBe(0);
376
+ } finally {
377
+ await f.cleanup();
378
+ }
379
+ });
380
+
381
+ test("a file no route imports rebuilds the client and reloads", async () => {
382
+ const f = await fixture();
383
+ const c = await context(f);
384
+ try {
385
+ const orphan = join(f.root, "src/lib/orphan.ts");
386
+ await writeFile(orphan, "export const x = 1;");
387
+ await handleChange(orphan, c.ctx);
388
+
389
+ expect(c.batches[0]!.kinds).toEqual(["reload"]);
390
+ // stale prebuilt bundles would otherwise survive the reload
391
+ expect(c.rebuilds()).toBe(1);
392
+ } finally {
393
+ await f.cleanup();
394
+ }
395
+ });
396
+
397
+ test("an edit that adds an import picks up the new dependency", async () => {
398
+ const f = await fixture();
399
+ const c = await context(f);
400
+ try {
401
+ const extra = join(f.root, "src/lib/Extra.tsx");
402
+ await writeFile(
403
+ extra,
404
+ `const Extra = () => <b>x</b>;
405
+ export default Extra;`,
406
+ );
407
+ await writeFile(
408
+ f.files.beacon,
409
+ `import Sigil from "$lib/Sigil.tsx";
410
+ import Extra from "$lib/Extra.tsx";
411
+ const Beacon = () => <p><Sigil /><Extra /></p>;
412
+ export default Beacon;`,
413
+ );
414
+ await handleChange(f.files.beacon, c.ctx);
415
+
416
+ expect(
417
+ f.graph
418
+ .affectedRoutes(extra)
419
+ .map((r) => r.path)
420
+ .sort(),
421
+ ).toEqual(["/", "/other"]);
422
+ } finally {
423
+ await f.cleanup();
424
+ }
425
+ });
426
+ });
@@ -1,119 +1,119 @@
1
- import { Window } from "happy-dom";
2
-
3
- // set up DOM globals before tests
4
- const window = new Window();
5
- const document = window.document;
6
-
7
- // @ts-expect-error
8
- globalThis.document = document;
9
- // @ts-expect-error
10
- globalThis.window = window;
11
- // @ts-expect-error
12
- globalThis.HTMLElement = window.HTMLElement;
13
- // @ts-expect-error
14
- globalThis.Event = window.Event;
15
- // @ts-expect-error
16
- globalThis.MouseEvent = window.MouseEvent;
17
- // @ts-expect-error
18
- globalThis.SyntaxError = SyntaxError;
19
-
20
- import { beforeEach, describe, expect, test } from "bun:test";
21
-
22
- // mock routes - simulates what #grimoire-routes generates
23
- const mockRoutes: Record<string, (props: any) => any> = {
24
- "/spells/:id": (props: any) => {
25
- return { params: props.params };
26
- },
27
- };
28
-
29
- // simulate hydrate logic (same as hydrate.ts but without the import)
30
- function runHydrate(routes: Record<string, (props: any) => any>) {
31
- const stateEl = document.getElementById("__grimoire_state__");
32
- if (stateEl) {
33
- const state = JSON.parse(stateEl.textContent!);
34
- const Page = routes[state.pattern];
35
- if (Page) {
36
- Page({ ...state.data, params: state.params });
37
- }
38
- }
39
- }
40
-
41
- // simulate initRouter (same logic as router.ts)
42
- let clickHandlerAttached = false;
43
- function initRouter(_routes: Record<string, (props: any) => any>) {
44
- document.addEventListener("click", () => {});
45
- clickHandlerAttached = true;
46
- }
47
-
48
- describe("hydration", () => {
49
- beforeEach(() => {
50
- clickHandlerAttached = false;
51
- document.body.innerHTML = `
52
- <div id="app">
53
- <div id="grimoire-page">
54
- <div class="spell-detail">
55
- <h1>Fireball</h1>
56
- </div>
57
- </div>
58
- </div>
59
- <script id="__grimoire_state__" type="application/json">
60
- ${JSON.stringify({ params: { id: "fireball" }, data: {}, pattern: "/spells/:id" })}
61
- </script>
62
- `;
63
- });
64
-
65
- // 1. hydrate claims existing DOM, doesn't create new nodes
66
- test("hydrate claims existing h1 instead of creating new one", () => {
67
- const before = document.getElementById("app")!.innerHTML;
68
- runHydrate(mockRoutes);
69
- // DOM unchanged - hydrate only reads state, doesn't write
70
- expect(document.getElementById("app")!.innerHTML).toBe(before);
71
- });
72
-
73
- // 2. router attaches after hydration
74
- test("initRouter attaches click handler", () => {
75
- initRouter(mockRoutes);
76
- expect(clickHandlerAttached).toBe(true);
77
- });
78
-
79
- // 3. state script is readable
80
- test("grimoire state is parseable", () => {
81
- const el = document.getElementById("__grimoire_state__");
82
- const state = JSON.parse(el!.textContent!);
83
- expect(state.pattern).toBe("/spells/:id");
84
- expect(state.params).toEqual({ id: "fireball" });
85
- });
86
-
87
- // 4. hydrate doesn't touch DOM structure
88
- test("hydrate preserves DOM structure", () => {
89
- const before = document.body.innerHTML;
90
- runHydrate(mockRoutes);
91
- expect(document.body.innerHTML).toBe(before);
92
- });
93
-
94
- // 5. hydrate with missing pattern is safe
95
- test("hydrate with unknown pattern does not throw", () => {
96
- const el = document.getElementById("__grimoire_state__");
97
- const state = JSON.parse(el!.textContent!);
98
- state.pattern = "/nonexistent";
99
- el!.textContent = JSON.stringify(state);
100
-
101
- expect(() => runHydrate(mockRoutes)).not.toThrow();
102
- });
103
-
104
- // 6. hydrate passes data and params correctly
105
- test("hydrate passes data and params to page component", () => {
106
- let receivedProps: any = null;
107
- const testRoutes: Record<string, (props: any) => any> = {
108
- "/spells/:id": (props: any) => {
109
- receivedProps = props;
110
- return null;
111
- },
112
- };
113
-
114
- runHydrate(testRoutes);
115
- expect(receivedProps).toEqual({
116
- params: { id: "fireball" },
117
- });
118
- });
119
- });
1
+ import { Window } from "happy-dom";
2
+
3
+ // set up DOM globals before tests
4
+ const window = new Window();
5
+ const document = window.document;
6
+
7
+ // @ts-expect-error
8
+ globalThis.document = document;
9
+ // @ts-expect-error
10
+ globalThis.window = window;
11
+ // @ts-expect-error
12
+ globalThis.HTMLElement = window.HTMLElement;
13
+ // @ts-expect-error
14
+ globalThis.Event = window.Event;
15
+ // @ts-expect-error
16
+ globalThis.MouseEvent = window.MouseEvent;
17
+ // @ts-expect-error
18
+ globalThis.SyntaxError = SyntaxError;
19
+
20
+ import { beforeEach, describe, expect, test } from "bun:test";
21
+
22
+ // mock routes - simulates what #grimoire-routes generates
23
+ const mockRoutes: Record<string, (props: any) => any> = {
24
+ "/spells/:id": (props: any) => {
25
+ return { params: props.params };
26
+ },
27
+ };
28
+
29
+ // simulate hydrate logic (same as hydrate.ts but without the import)
30
+ function runHydrate(routes: Record<string, (props: any) => any>) {
31
+ const stateEl = document.getElementById("__grimoire_state__");
32
+ if (stateEl) {
33
+ const state = JSON.parse(stateEl.textContent!);
34
+ const Page = routes[state.pattern];
35
+ if (Page) {
36
+ Page({ ...state.data, params: state.params });
37
+ }
38
+ }
39
+ }
40
+
41
+ // simulate initRouter (same logic as router.ts)
42
+ let clickHandlerAttached = false;
43
+ function initRouter(_routes: Record<string, (props: any) => any>) {
44
+ document.addEventListener("click", () => {});
45
+ clickHandlerAttached = true;
46
+ }
47
+
48
+ describe("hydration", () => {
49
+ beforeEach(() => {
50
+ clickHandlerAttached = false;
51
+ document.body.innerHTML = `
52
+ <div id="app">
53
+ <div id="grimoire-page">
54
+ <div class="spell-detail">
55
+ <h1>Fireball</h1>
56
+ </div>
57
+ </div>
58
+ </div>
59
+ <script id="__grimoire_state__" type="application/json">
60
+ ${JSON.stringify({ params: { id: "fireball" }, data: {}, pattern: "/spells/:id" })}
61
+ </script>
62
+ `;
63
+ });
64
+
65
+ // 1. hydrate claims existing DOM, doesn't create new nodes
66
+ test("hydrate claims existing h1 instead of creating new one", () => {
67
+ const before = document.getElementById("app")!.innerHTML;
68
+ runHydrate(mockRoutes);
69
+ // DOM unchanged - hydrate only reads state, doesn't write
70
+ expect(document.getElementById("app")!.innerHTML).toBe(before);
71
+ });
72
+
73
+ // 2. router attaches after hydration
74
+ test("initRouter attaches click handler", () => {
75
+ initRouter(mockRoutes);
76
+ expect(clickHandlerAttached).toBe(true);
77
+ });
78
+
79
+ // 3. state script is readable
80
+ test("grimoire state is parseable", () => {
81
+ const el = document.getElementById("__grimoire_state__");
82
+ const state = JSON.parse(el!.textContent!);
83
+ expect(state.pattern).toBe("/spells/:id");
84
+ expect(state.params).toEqual({ id: "fireball" });
85
+ });
86
+
87
+ // 4. hydrate doesn't touch DOM structure
88
+ test("hydrate preserves DOM structure", () => {
89
+ const before = document.body.innerHTML;
90
+ runHydrate(mockRoutes);
91
+ expect(document.body.innerHTML).toBe(before);
92
+ });
93
+
94
+ // 5. hydrate with missing pattern is safe
95
+ test("hydrate with unknown pattern does not throw", () => {
96
+ const el = document.getElementById("__grimoire_state__");
97
+ const state = JSON.parse(el!.textContent!);
98
+ state.pattern = "/nonexistent";
99
+ el!.textContent = JSON.stringify(state);
100
+
101
+ expect(() => runHydrate(mockRoutes)).not.toThrow();
102
+ });
103
+
104
+ // 6. hydrate passes data and params correctly
105
+ test("hydrate passes data and params to page component", () => {
106
+ let receivedProps: any = null;
107
+ const testRoutes: Record<string, (props: any) => any> = {
108
+ "/spells/:id": (props: any) => {
109
+ receivedProps = props;
110
+ return null;
111
+ },
112
+ };
113
+
114
+ runHydrate(testRoutes);
115
+ expect(receivedProps).toEqual({
116
+ params: { id: "fireball" },
117
+ });
118
+ });
119
+ });