@sigil-dev/grimoire 0.9.7 → 0.9.11

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.
@@ -0,0 +1,98 @@
1
+ import { isAbsolute, join } from "node:path";
2
+ import type { BunPlugin } from "bun";
3
+ import { resolveFile } from "../dev/resolve";
4
+ import { ENV_MODULE, envModuleSource } from "../env/modules";
5
+ import type { GrimoireConfig } from "../types";
6
+
7
+ /**
8
+ * Import prefixes → absolute directories: `$lib` for `src/lib` unless the
9
+ * config says otherwise, plus `GrimoireConfig.alias`.
10
+ */
11
+ export function projectAliases(
12
+ config: GrimoireConfig,
13
+ root = process.cwd(),
14
+ ): Record<string, string> {
15
+ const out: Record<string, string> = { $lib: join(root, "src/lib") };
16
+ for (const [prefix, target] of Object.entries(config.alias ?? {})) {
17
+ out[prefix] = isAbsolute(target) ? target : join(root, target);
18
+ }
19
+ return out;
20
+ }
21
+
22
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
23
+
24
+ /**
25
+ * Resolves `$env/*` and aliased imports, for the browser builds (Bun.build)
26
+ * and for the server (Bun.plugin). Bun has no alias option of its own.
27
+ */
28
+ export function resolverPlugin(
29
+ config: GrimoireConfig,
30
+ target: "server" | "browser",
31
+ ): BunPlugin {
32
+ const aliases = projectAliases(config);
33
+ return {
34
+ name: `grimoire-resolve-${target}`,
35
+ setup(build) {
36
+ if (target === "server") {
37
+ // Bun's runtime plugins don't see static imports in onResolve;
38
+ // virtual modules have to be registered by name. Aliases on the
39
+ // server are rewritten by the SSR plugin (rewriteAliases).
40
+ for (const specifier of ENV_SPECIFIERS) {
41
+ build.module(specifier, () => ({
42
+ contents: envModuleSource(specifier, "server"),
43
+ loader: "js",
44
+ }));
45
+ }
46
+ return;
47
+ }
48
+ build.onResolve({ filter: ENV_MODULE }, (args) => ({
49
+ path: args.path,
50
+ namespace: "grimoire-env",
51
+ }));
52
+ build.onLoad({ filter: /.*/, namespace: "grimoire-env" }, (args) => ({
53
+ contents: envModuleSource(args.path, target),
54
+ loader: "js",
55
+ }));
56
+ for (const [prefix, dir] of Object.entries(aliases)) {
57
+ build.onResolve(
58
+ { filter: new RegExp(`^${escapeRegExp(prefix)}(/|$)`) },
59
+ (args) => {
60
+ const file = resolveFile(join(dir, args.path.slice(prefix.length)));
61
+ return file ? { path: file } : undefined;
62
+ },
63
+ );
64
+ }
65
+ },
66
+ };
67
+ }
68
+
69
+ const ENV_SPECIFIERS = [
70
+ "$env/static/public",
71
+ "$env/static/private",
72
+ "$env/dynamic/public",
73
+ "$env/dynamic/private",
74
+ ];
75
+
76
+ const SPEC_RE = /(from\s+|import\s+|import\s*\(\s*)(["'])([^"']+)\2/g;
77
+
78
+ /** Point aliased import specifiers in compiled code at their files. */
79
+ export function rewriteAliases(
80
+ code: string,
81
+ aliases: Record<string, string>,
82
+ ): string {
83
+ const prefixes = Object.keys(aliases);
84
+ if (prefixes.length === 0) return code;
85
+ return code.replace(
86
+ SPEC_RE,
87
+ (match, keyword: string, quote: string, specifier: string) => {
88
+ const prefix = prefixes.find(
89
+ (p) => specifier === p || specifier.startsWith(`${p}/`),
90
+ );
91
+ if (!prefix) return match;
92
+ const file = resolveFile(
93
+ join(aliases[prefix]!, specifier.slice(prefix.length)),
94
+ );
95
+ return file ? `${keyword}${quote}${file}${quote}` : match;
96
+ },
97
+ );
98
+ }
@@ -1,3 +1,4 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { join } from "node:path";
2
3
  import type { GrimoireConfig, GrimoirePlugin, WorkerMode } from "../types";
3
4
  import { createServer } from "./index";
@@ -35,11 +36,11 @@ if (process.env.GRIMOIRE_INTERNAL_SECRET) {
35
36
  const port = Number(process.env.GRIMOIRE_WORKER_PORT ?? 3001);
36
37
  const cwd = process.cwd();
37
38
 
38
- let config: GrimoireConfig = {};
39
- try {
40
- const mod = await import(join(cwd, "sigil.config.ts"));
41
- config = mod.default ?? {};
42
- } catch {}
39
+ // a config that fails to load must fail the worker, not run on defaults
40
+ const configFile = join(cwd, "sigil.config.ts");
41
+ const config: GrimoireConfig = existsSync(configFile)
42
+ ? ((await import(configFile)).default ?? {})
43
+ : {};
43
44
 
44
45
  let finalConfig: GrimoireConfig = { ...config, port, host: "127.0.0.1" };
45
46
  const plugins = finalConfig.plugins ?? [];
@@ -7,6 +7,8 @@ export interface TypegenConfig {
7
7
  projectRoot: string;
8
8
  routesDir: string;
9
9
  outDir: string; // absolute path to .grimoire/types
10
+ /** Import prefix → absolute directory ($lib, GrimoireConfig.alias), for editor `paths`. */
11
+ aliases?: Record<string, string>;
10
12
  }
11
13
 
12
14
  export interface RouteGroup {
@@ -166,9 +168,9 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
166
168
  ` secure?: boolean;`,
167
169
  ` sameSite?: "strict" | "lax" | "none";`,
168
170
  ` }): void;`,
169
- ` delete(name: string): void;`,
171
+ ` delete(name: string, options?: { path?: string; domain?: string }): void;`,
170
172
  `};`,
171
- `type _ActionKeys = Exclude<keyof _PS, "load" | "default">;`,
173
+ `type _ActionKeys = Exclude<keyof _PS, "load" | "default" | "canMatch" | "csrf" | "loading">;`,
172
174
  `export type Actions = {`,
173
175
  ` [K in _ActionKeys]: (ctx: {`,
174
176
  ` params: Params;`,
@@ -336,13 +338,24 @@ function generateAmbient(): string {
336
338
  ].join("\n");
337
339
  }
338
340
 
339
- function generateTsConfig(): string {
341
+ function generateTsConfig(
342
+ aliases: Record<string, string>,
343
+ grimoireDir: string,
344
+ ): string {
345
+ // paths without a baseUrl resolve against this file's directory
346
+ const paths: Record<string, string[]> = {};
347
+ for (const [prefix, dir] of Object.entries(aliases)) {
348
+ const rel = relative(grimoireDir, dir).replace(/\\/g, "/");
349
+ paths[prefix] = [rel];
350
+ paths[`${prefix}/*`] = [`${rel}/*`];
351
+ }
340
352
  return JSON.stringify(
341
353
  {
342
354
  compilerOptions: {
343
355
  // Merges ".." (project root) and "./types" (.grimoire/types) into one
344
356
  // virtual root so `import from './$types'` resolves without path aliases.
345
357
  rootDirs: ["..", "./types"],
358
+ ...(Object.keys(paths).length > 0 ? { paths } : {}),
346
359
  },
347
360
  include: ["types/**/*.d.ts"],
348
361
  },
@@ -383,7 +396,7 @@ export async function generateTypes(
383
396
  const grimoireDir = dirname(outDir);
384
397
  writeFileSync(
385
398
  join(grimoireDir, "tsconfig.generated.json"),
386
- generateTsConfig(),
399
+ generateTsConfig(config.aliases ?? {}, grimoireDir),
387
400
  "utf-8",
388
401
  );
389
402
  }
@@ -108,6 +108,96 @@ describe("depends", () => {
108
108
  expect(hasDep("/", "comments")).toBe(true);
109
109
  });
110
110
  });
111
+ describe("navigate — head", () => {
112
+ test("server-rendered head tags are replaced, not kept beside the new ones", async () => {
113
+ const root = document.createElement("div");
114
+ root.id = "grimoire-root";
115
+ document.body.appendChild(root);
116
+ document.head.innerHTML =
117
+ '<meta charset="UTF-8"><!--grimoire-head--><title>Old</title><meta name="description" content="old"><!--/grimoire-head-->';
118
+ const g = globalThis as { DOMParser?: unknown };
119
+ g.DOMParser ??= (window as unknown as { DOMParser: unknown }).DOMParser;
120
+ const original = globalThis.fetch;
121
+ globalThis.fetch = (async () =>
122
+ new Response(
123
+ JSON.stringify({
124
+ data: {},
125
+ layoutData: [],
126
+ params: {},
127
+ pattern: "/",
128
+ head: '<title>New</title><meta name="description" content="new">',
129
+ }),
130
+ { headers: { "content-type": "application/json" } },
131
+ )) as unknown as typeof fetch;
132
+ try {
133
+ router.initRouter({ "/": () => document.createElement("main") }, []);
134
+ await router.navigate("/");
135
+ const descriptions = [
136
+ ...document.head.querySelectorAll('meta[name="description"]'),
137
+ ].map((m) => m.getAttribute("content"));
138
+ expect(descriptions).toEqual(["new"]);
139
+ expect(document.title).toBe("New");
140
+ expect(document.head.querySelectorAll("meta[charset]").length).toBe(1);
141
+ // a second navigation replaces the tags the first one added
142
+ await router.navigate("/");
143
+ expect(
144
+ document.head.querySelectorAll('meta[name="description"]').length,
145
+ ).toBe(1);
146
+ } finally {
147
+ globalThis.fetch = original;
148
+ root.remove();
149
+ document.head.innerHTML = "";
150
+ }
151
+ });
152
+ });
153
+
154
+ describe("navigate — loading export", () => {
155
+ test("a lazy page module's loading export shows while data loads", async () => {
156
+ // other files' tests may leave a page host behind
157
+ for (const id of ["grimoire-root", "grimoire-page"])
158
+ document.getElementById(id)?.remove();
159
+ const root = document.createElement("div");
160
+ root.id = "grimoire-root";
161
+ const page = document.createElement("div");
162
+ page.id = "grimoire-page";
163
+ root.appendChild(page);
164
+ document.body.appendChild(root);
165
+ let release!: () => void;
166
+ const gate = new Promise<void>((r) => (release = r));
167
+ const original = globalThis.fetch;
168
+ globalThis.fetch = (async () => {
169
+ await gate;
170
+ return jsonResponse("/slow");
171
+ }) as unknown as typeof fetch;
172
+ try {
173
+ const Page = () => {
174
+ const el = document.createElement("p");
175
+ el.textContent = "page";
176
+ return el;
177
+ };
178
+ const loading = () => {
179
+ const el = document.createElement("p");
180
+ el.textContent = "loading";
181
+ return el;
182
+ };
183
+ router.initRouter(
184
+ { "/slow": { __lazy: async () => ({ default: Page, loading }) } },
185
+ [],
186
+ );
187
+ const done = router.navigate("/slow");
188
+ for (let i = 0; i < 20 && !root.textContent?.includes("loading"); i++)
189
+ await new Promise((r) => setTimeout(r, 5));
190
+ expect(root.textContent).toContain("loading");
191
+ release();
192
+ await done;
193
+ expect(root.textContent).toContain("page");
194
+ } finally {
195
+ globalThis.fetch = original;
196
+ root.remove();
197
+ }
198
+ });
199
+ });
200
+
111
201
  describe("navigate — view transitions", () => {
112
202
  test("falls back to direct swap when startViewTransition is missing", async () => {
113
203
  const root = document.createElement("div");
@@ -305,6 +395,104 @@ describe("enhance — named action URLs", () => {
305
395
  });
306
396
  });
307
397
 
398
+ describe("enhance — outcomes", () => {
399
+ async function submit(
400
+ reply: Response,
401
+ options: Record<string, unknown> = {},
402
+ submitter?: HTMLButtonElement,
403
+ ) {
404
+ window.history.pushState(null, "", "/books");
405
+ const { enhance } = await import("../src/client/enhance.ts");
406
+ const sent: { headers: Headers; body: FormData }[] = [];
407
+ const navigations: [string, boolean | undefined][] = [];
408
+ const g = globalThis as Record<string, unknown>;
409
+ const originalFetch = globalThis.fetch;
410
+ const originalNavigate = g.__grimoire_navigate__;
411
+ globalThis.fetch = (async (_input: string, init: RequestInit) => {
412
+ sent.push({
413
+ headers: new Headers(init.headers),
414
+ body: init.body as FormData,
415
+ });
416
+ return reply;
417
+ }) as unknown as typeof fetch;
418
+ g.__grimoire_navigate__ = (path: string, replace?: boolean) =>
419
+ navigations.push([path, replace]);
420
+
421
+ const form = document.createElement("form");
422
+ form.setAttribute("action", "?/toggle");
423
+ const input = document.createElement("input");
424
+ input.setAttribute("name", "id");
425
+ input.setAttribute("value", "7");
426
+ form.appendChild(input);
427
+ if (submitter) form.appendChild(submitter);
428
+ document.body.appendChild(form);
429
+ const cleanup = enhance(form, options);
430
+ try {
431
+ const event = new Event("submit", { bubbles: true, cancelable: true });
432
+ if (submitter)
433
+ Object.defineProperty(event, "submitter", { value: submitter });
434
+ form.dispatchEvent(event);
435
+ await new Promise((r) => setTimeout(r, 0));
436
+ return { sent, navigations };
437
+ } finally {
438
+ cleanup();
439
+ form.remove();
440
+ globalThis.fetch = originalFetch;
441
+ g.__grimoire_navigate__ = originalNavigate;
442
+ }
443
+ }
444
+
445
+ test("success on the same page re-runs its loads in place", async () => {
446
+ const seen: unknown[] = [];
447
+ const { sent, navigations } = await submit(
448
+ Response.json({
449
+ type: "success",
450
+ location: "http://localhost/books",
451
+ data: { ok: 1 },
452
+ }),
453
+ { onSuccess: (r: unknown) => seen.push(r) },
454
+ );
455
+ expect(sent[0]!.headers.get("x-grimoire-form")).toBe("1");
456
+ expect(seen).toEqual([
457
+ { redirect: "http://localhost/books", data: { ok: 1 } },
458
+ ]);
459
+ // replace: no new history entry for the same page
460
+ expect(navigations).toEqual([["/books", true]]);
461
+ });
462
+
463
+ test("a redirect elsewhere pushes a new entry", async () => {
464
+ const { navigations } = await submit(
465
+ Response.json({ type: "redirect", status: 303, location: "/books/7" }),
466
+ );
467
+ expect(navigations).toEqual([["/books/7", false]]);
468
+ });
469
+
470
+ test("fail() data goes to onFail, and nothing navigates", async () => {
471
+ const failed: unknown[] = [];
472
+ const { navigations } = await submit(
473
+ Response.json(
474
+ { fail: true, status: 400, data: { problem: "x" } },
475
+ { status: 400 },
476
+ ),
477
+ { onFail: (d: unknown) => failed.push(d) },
478
+ );
479
+ expect(failed).toEqual([{ problem: "x" }]);
480
+ expect(navigations).toEqual([]);
481
+ });
482
+
483
+ test("the submitting button's name=value is sent", async () => {
484
+ const button = document.createElement("button");
485
+ button.name = "read";
486
+ button.value = "1";
487
+ const { sent } = await submit(
488
+ Response.json({ type: "success", location: "/books", data: null }),
489
+ {},
490
+ button,
491
+ );
492
+ expect(sent[0]!.body.get("read")).toBe("1");
493
+ });
494
+ });
495
+
308
496
  describe("Page.load — parent()", () => {
309
497
  test("parent() merges layoutData entries outermost-first", async () => {
310
498
  let seenParent: Record<string, unknown> | undefined;
@@ -0,0 +1,85 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { startCoordinator } from "../src/server/coordinator.ts";
6
+
7
+ // A real coordinator with one worker process, in front of a project that has
8
+ // an HTTP route and a WebSocket route.
9
+ describe("coordinator", () => {
10
+ const port = 3960;
11
+ const root = join(tmpdir(), `grimoire-loom-${Date.now()}`);
12
+ const cwd = process.cwd();
13
+ let loom: Awaited<ReturnType<typeof startCoordinator>>;
14
+
15
+ beforeAll(async () => {
16
+ await mkdir(join(root, "src/routes/echo"), { recursive: true });
17
+ await writeFile(
18
+ join(root, "src/routes/echo/+server.ts"),
19
+ [
20
+ "export const websocket = {",
21
+ ' open(ws) { ws.send("hello"); },',
22
+ ' message(ws, data) { ws.send("echo:" + data); },',
23
+ "};",
24
+ "export function GET({ request }) {",
25
+ ' return new Response(request.headers.get("cookie") ?? "no cookie");',
26
+ "}",
27
+ ].join("\n"),
28
+ );
29
+ process.chdir(root);
30
+ loom = await startCoordinator({
31
+ config: { port, host: "127.0.0.1", routes: join(root, "src/routes") },
32
+ plugins: [],
33
+ scale: { full: 1 },
34
+ noBuild: true,
35
+ });
36
+ });
37
+
38
+ afterAll(async () => {
39
+ await loom?.stop();
40
+ process.chdir(cwd);
41
+ await rm(root, { recursive: true, force: true });
42
+ });
43
+
44
+ test("forwards requests with their cookies", async () => {
45
+ const res = await fetch(`http://127.0.0.1:${port}/echo`, {
46
+ headers: { Cookie: "a=1" },
47
+ });
48
+ expect(await res.text()).toBe("a=1");
49
+ });
50
+
51
+ test("a client's own x-grimoire-* headers don't break forwarding", async () => {
52
+ const res = await fetch(`http://127.0.0.1:${port}/echo`, {
53
+ headers: { "X-Grimoire-Internal": "guess", "X-Grimoire-Locals": "x" },
54
+ });
55
+ expect(res.status).toBe(200);
56
+ });
57
+
58
+ test("relays WebSockets, including a message sent right on open", async () => {
59
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/echo`);
60
+ const got: string[] = [];
61
+ ws.onopen = () => ws.send("first");
62
+ ws.onmessage = (e) => got.push(String(e.data));
63
+ for (let i = 0; i < 40 && got.length < 2; i++) await Bun.sleep(50);
64
+ ws.close();
65
+ expect(got).toEqual(["hello", "echo:first"]);
66
+ // and the coordinator is still up
67
+ const res = await fetch(`http://127.0.0.1:${port}/echo`);
68
+ expect(res.status).toBe(200);
69
+ });
70
+
71
+ test("a worker that dies is started again", async () => {
72
+ const worker = loom.workers[0]!;
73
+ const before = worker.pid;
74
+ process.kill(before, "SIGKILL");
75
+ let status = 0;
76
+ for (let i = 0; i < 60 && status !== 200; i++) {
77
+ await Bun.sleep(100);
78
+ status = await fetch(`http://127.0.0.1:${port}/echo`)
79
+ .then((r) => r.status)
80
+ .catch(() => 0);
81
+ }
82
+ expect(status).toBe(200);
83
+ expect(worker.pid).not.toBe(before);
84
+ });
85
+ });
@@ -0,0 +1,30 @@
1
+ import { afterAll, expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { DevGraph } from "../src/dev/graph";
6
+ import { makeDevLoader } from "../src/dev/loader";
7
+
8
+ const root = mkdtempSync(join(tmpdir(), "grimoire-dev-loader-"));
9
+ afterAll(() => rmSync(root, { recursive: true, force: true }));
10
+
11
+ test("a component with a scoped <style> block renders server-side", async () => {
12
+ const file = join(root, "Card.tsx");
13
+ // the tag is split so this test file's own preload doesn't strip it
14
+ const tag = (name: string) => `<${name}>`;
15
+ writeFileSync(
16
+ file,
17
+ `export const Card = ({ title }) => <div class="card">{title}</div>;
18
+
19
+ ${tag("style")}
20
+ .card { padding: 1rem; }
21
+ .card .title { text-decoration: line-through; color: #888; }
22
+ ${tag("/style")}
23
+ `,
24
+ );
25
+ const load = makeDevLoader(new DevGraph(), root);
26
+ const mod = await load(file);
27
+ const html = String(mod.Card({ title: "hi" }));
28
+ expect(html).toContain(">hi<");
29
+ expect(html).toMatch(/class="card s-?[a-z0-9]+"|class="card [a-z0-9-]+"/);
30
+ });
package/test/env.test.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  // packages/grimoire/src/env/env.test.ts
2
2
  import { afterEach, beforeEach, describe, expect, test } from "bun:test";
3
+ import { mkdir, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { envModuleSource } from "../src/env/modules.ts";
7
+ import { resolverPlugin, rewriteAliases } from "../src/server/resolver.ts";
3
8
 
4
9
  describe("$env/dynamic/public", () => {
5
10
  let orig: Record<string, string | undefined> = {};
@@ -88,3 +93,76 @@ describe("$env/dynamic/private", () => {
88
93
  expect(env.PUBLIC_APP_NAME).toBe("grimoire");
89
94
  });
90
95
  });
96
+
97
+ describe("$env modules in builds", () => {
98
+ test("static modules export each variable by name, and env", () => {
99
+ process.env.PUBLIC_SITE = "docs";
100
+ const src: string = envModuleSource("$env/static/public", "browser");
101
+ expect(src).toContain('export const PUBLIC_SITE = env["PUBLIC_SITE"];');
102
+ expect(src).not.toContain("SECRET");
103
+ delete process.env.PUBLIC_SITE;
104
+ });
105
+
106
+ test("private modules can't be built for the browser", () => {
107
+ for (const kind of ["static", "dynamic"]) {
108
+ expect(() => envModuleSource(`$env/${kind}/private`, "browser")).toThrow(
109
+ /server secrets/,
110
+ );
111
+ }
112
+ });
113
+
114
+ test("a browser build resolves $env and $lib, and inlines no secrets", async () => {
115
+ const dir = join(tmpdir(), `grimoire-env-build-${Date.now()}`);
116
+ await mkdir(join(dir, "src/lib"), { recursive: true });
117
+ await writeFile(
118
+ join(dir, "src/lib/greet.ts"),
119
+ 'export const greet = (s: string) => "hi " + s;',
120
+ );
121
+ await writeFile(
122
+ join(dir, "entry.ts"),
123
+ [
124
+ 'import { PUBLIC_WHO } from "$env/static/public";',
125
+ 'import { env } from "$env/dynamic/public";',
126
+ 'import { greet } from "$lib/greet";',
127
+ "console.log(greet(PUBLIC_WHO), env.PUBLIC_WHO);",
128
+ ].join("\n"),
129
+ );
130
+ process.env.PUBLIC_WHO = "world";
131
+ process.env.SECRET_WHO = "hunter2";
132
+ const cwd = process.cwd();
133
+ process.chdir(dir);
134
+ try {
135
+ const result = await Bun.build({
136
+ entrypoints: [join(dir, "entry.ts")],
137
+ plugins: [resolverPlugin({}, "browser")],
138
+ throw: false,
139
+ });
140
+ expect(result.success).toBe(true);
141
+ const code = await result.outputs[0]!.text();
142
+ expect(code).toContain('"world"');
143
+ expect(code).toContain('"hi "');
144
+ expect(code).not.toContain("hunter2");
145
+ } finally {
146
+ process.chdir(cwd);
147
+ delete process.env.PUBLIC_WHO;
148
+ delete process.env.SECRET_WHO;
149
+ await rm(dir, { recursive: true, force: true });
150
+ }
151
+ });
152
+
153
+ test("server modules get aliased imports rewritten to files", async () => {
154
+ const dir = join(tmpdir(), `grimoire-alias-${Date.now()}`);
155
+ await mkdir(join(dir, "lib"), { recursive: true });
156
+ await writeFile(join(dir, "lib/db.ts"), "export const db = 1;");
157
+ try {
158
+ const out = rewriteAliases(
159
+ 'import { db } from "$lib/db";\nimport x from "other";',
160
+ { $lib: join(dir, "lib") },
161
+ );
162
+ expect(out).toContain(`from "${join(dir, "lib/db.ts")}"`);
163
+ expect(out).toContain('from "other"');
164
+ } finally {
165
+ await rm(dir, { recursive: true, force: true });
166
+ }
167
+ });
168
+ });
@@ -205,6 +205,26 @@ describe("Cookies", () => {
205
205
  });
206
206
  });
207
207
 
208
+ describe("Cookies round-trip", () => {
209
+ test("values set with special characters read back decoded", () => {
210
+ const c = createCookies("prefs=%7B%22a%22%3A1%7D; bad=%E0%A4%A");
211
+ expect(c.get("prefs")).toBe('{"a":1}');
212
+ expect(c.get("bad")).toBe("%E0%A4%A"); // malformed stays raw
213
+ });
214
+
215
+ test("set and delete default to Path=/", () => {
216
+ const c = createCookies("");
217
+ c.set("session", "abc");
218
+ c.delete("old");
219
+ c.set("scoped", "x", { path: "/admin" });
220
+ const [set, del, scoped] = c.toHeaders();
221
+ expect(set).toContain("Path=/");
222
+ expect(del).toContain("Path=/");
223
+ expect(del).toContain("Max-Age=0");
224
+ expect(scoped).toContain("Path=/admin");
225
+ });
226
+ });
227
+
208
228
  describe("createHooks()", () => {
209
229
  test("returns handle and init", async () => {
210
230
  const handle: Handle = async ({ resolve, event }) => resolve(event);
@@ -679,6 +679,52 @@ describe("load context — await parent()", () => {
679
679
  });
680
680
  });
681
681
 
682
+ describe("a +layout.server.ts without a +layout.tsx", () => {
683
+ let dir: string;
684
+
685
+ beforeAll(async () => {
686
+ dir = join(osTmpDir(), `grimoire-guard-${Date.now()}`);
687
+ await mkdir(join(dir, "account"), { recursive: true });
688
+ await writeFile(
689
+ join(dir, "account", "+layout.server.ts"),
690
+ [
691
+ "export async function load({ request }) {",
692
+ ' if (!request.headers.get("x-user")) throw { __redirect: true, status: 303, location: "/login" };',
693
+ ' return { user: request.headers.get("x-user") };',
694
+ "}",
695
+ ].join("\n"),
696
+ );
697
+ await writeFile(
698
+ join(dir, "account", "+page.server.ts"),
699
+ `export async function load({ parent }) { return { who: (await parent()).user }; }`,
700
+ );
701
+ await writeFile(
702
+ join(dir, "account", "+page.tsx"),
703
+ `export default function P({ data }) { return <p>{"who:" + data.who}</p>; }`,
704
+ );
705
+ });
706
+
707
+ afterAll(() => rm(dir, { recursive: true }));
708
+
709
+ test("still runs: its redirect guards the folder", async () => {
710
+ const tree = await scanRoutes(dir);
711
+ const url = new URL("http://localhost/account");
712
+ const res = await renderRoute(matchRoute(tree, url)!, new Request(url));
713
+ expect(res.status).toBe(303);
714
+ expect(res.headers.get("location")).toBe("/login");
715
+ });
716
+
717
+ test("and its data reaches the page's parent()", async () => {
718
+ const tree = await scanRoutes(dir);
719
+ const url = new URL("http://localhost/account");
720
+ const res = await renderRoute(
721
+ matchRoute(tree, url)!,
722
+ new Request(url, { headers: { "x-user": "ada" } }),
723
+ );
724
+ expect(await readStream(res)).toContain("who:ada");
725
+ });
726
+ });
727
+
682
728
  describe("server-side depends()", () => {
683
729
  let depsDir: string;
684
730