@sigil-dev/grimoire 0.9.10 → 0.9.12

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,17 +36,29 @@ 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
 
45
+ // Forced, not defaulted. The worker re-reads sigil.config.ts from disk
46
+ // rather than trusting what the CLI passed, so a `dev: true` left in the
47
+ // config reaches the request handler — which gates the HMR socket, the
48
+ // dependency-source endpoints, and /__grimoire__/open, that spawns an
49
+ // editor on the host from a query string. Overriding here as well as in
50
+ // the CLI is deliberate: the CLI's copy is not the one that binds.
51
+ //
52
+ // The worker is only ever spawned by `sigil start` or `sigil preview`.
53
+ // `sigil dev` runs in-process and never gets here, which is why forcing
54
+ // this cannot disable HMR for anyone.
44
55
  let finalConfig: GrimoireConfig = { ...config, port, host: "127.0.0.1" };
45
56
  const plugins = finalConfig.plugins ?? [];
46
57
  for (const plugin of plugins) {
47
- finalConfig = plugin.config?.(finalConfig) ?? finalConfig;
58
+ finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
48
59
  }
60
+ // Last, so a plugin config hook cannot turn it back on either.
61
+ finalConfig = { ...finalConfig, dev: false };
49
62
 
50
63
  await startWorker({
51
64
  config: finalConfig,
@@ -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
  }
package/src/types.ts CHANGED
@@ -2,6 +2,22 @@ import type { Server, ServerWebSocket } from "bun";
2
2
  import type { ScopedLogger } from "./logger";
3
3
  import type { RouteFile, RouteTree } from "./routing/scanner";
4
4
 
5
+ /**
6
+ * Structural subset of commander's Command that plugins need to register
7
+ * subcommands. Declared here rather than importing Command so that
8
+ * @sigil-dev/grimoire does not take a dependency on commander — the CLI is
9
+ * one consumer of plugins, not the only one.
10
+ */
11
+ export interface CliCommand {
12
+ name(): string;
13
+ command(nameAndArgs: string, opts?: { hidden?: boolean }): CliCommand;
14
+ description(text: string): CliCommand;
15
+ alias(alias: string): CliCommand;
16
+ option(flags: string, description?: string, defaultValue?: unknown): CliCommand;
17
+ argument(name: string, description?: string): CliCommand;
18
+ action(fn: (...args: never[]) => unknown): CliCommand;
19
+ }
20
+
5
21
  /// <reference types="bun-types">
6
22
  declare global {
7
23
  namespace App {
@@ -108,7 +124,34 @@ export interface GrimoirePlugin {
108
124
  onBuildEnd?(result: BuildResult): void | Promise<void>;
109
125
 
110
126
  // config
111
- config?: (config: GrimoireConfig) => GrimoireConfig | undefined;
127
+ /**
128
+ * Transform the project config at load time.
129
+ *
130
+ * May be async. Plugins need this to open a database connection or run
131
+ * migrations before the server starts, and a sync-only signature makes
132
+ * that impossible without blocking module scope. Every call site awaits
133
+ * the result, so a returned Promise is never mistaken for a config.
134
+ */
135
+ config?: (config: GrimoireConfig) =>
136
+ | GrimoireConfig
137
+ | undefined
138
+ | Promise<GrimoireConfig | undefined>;
139
+
140
+ /**
141
+ * Register CLI subcommands for this plugin.
142
+ *
143
+ * Called by the `sigil` CLI after it has loaded the project's sigil.config.ts,
144
+ * before command parsing, so a plugin can add `sigil jobs work` or similar.
145
+ * The project config is passed through as-is (after this plugin's own
146
+ * `config` transform, so it reflects the same values the server sees).
147
+ *
148
+ * Plugins without this hook are simply skipped. A plugin that throws here
149
+ * aborts the CLI with that error rather than failing obscurely later.
150
+ */
151
+ cli?: (
152
+ program: CliCommand,
153
+ context: GrimoireConfig,
154
+ ) => void | Promise<void>;
112
155
 
113
156
  // process lifecycle
114
157
 
@@ -0,0 +1,113 @@
1
+ import { beforeEach, describe, expect, test } from "bun:test";
2
+ import {
3
+ _resetAfterResponseForTest,
4
+ afterResponse,
5
+ drainAfterResponse,
6
+ withAfterResponse,
7
+ } from "../src/server/after-response.ts";
8
+
9
+ const req = () => new Request("http://localhost/");
10
+
11
+ beforeEach(() => {
12
+ _resetAfterResponseForTest();
13
+ });
14
+
15
+ describe("afterResponse", () => {
16
+ test("does not run before the body is consumed", async () => {
17
+ let ran = false;
18
+ const res = await withAfterResponse(req(), async () => {
19
+ afterResponse(() => {
20
+ ran = true;
21
+ });
22
+ return new Response("hello");
23
+ });
24
+ expect(ran).toBe(false);
25
+ await res.text();
26
+ await Bun.sleep(10);
27
+ expect(ran).toBe(true);
28
+ });
29
+
30
+ test("runs for a response with no body", async () => {
31
+ let ran = false;
32
+ await withAfterResponse(req(), async () => {
33
+ afterResponse(() => {
34
+ ran = true;
35
+ });
36
+ return new Response(null, { status: 204 });
37
+ });
38
+ await Bun.sleep(10);
39
+ expect(ran).toBe(true);
40
+ });
41
+
42
+ test("a throwing task does not corrupt the response", async () => {
43
+ const res = await withAfterResponse(req(), async () => {
44
+ afterResponse(() => {
45
+ throw new Error("boom");
46
+ });
47
+ return new Response("still fine");
48
+ });
49
+ expect(await res.text()).toBe("still fine");
50
+ await Bun.sleep(10);
51
+ });
52
+
53
+ test("tasks are isolated per request under concurrency", async () => {
54
+ const order: string[] = [];
55
+ const make = (tag: string) =>
56
+ withAfterResponse(req(), async () => {
57
+ afterResponse(() => order.push(tag));
58
+ return new Response(tag);
59
+ });
60
+
61
+ const [a, b] = await Promise.all([make("A"), make("B")]);
62
+ await Promise.all([a.text(), b.text()]);
63
+ await Bun.sleep(20);
64
+
65
+ expect(order.sort()).toEqual(["A", "B"]);
66
+ });
67
+
68
+ test("preserves status, statusText and headers through the rewrap", async () => {
69
+ const res = await withAfterResponse(
70
+ req(),
71
+ async () =>
72
+ new Response("x", {
73
+ status: 404,
74
+ statusText: "Nope",
75
+ headers: { "x-test": "1" },
76
+ }),
77
+ );
78
+ expect(res.status).toBe(404);
79
+ expect(res.headers.get("x-test")).toBe("1");
80
+ expect(await res.text()).toBe("x");
81
+ });
82
+
83
+ test("drain waits for a task that is still running", async () => {
84
+ let done = false;
85
+ const res = await withAfterResponse(req(), async () => {
86
+ afterResponse(async () => {
87
+ await Bun.sleep(50);
88
+ done = true;
89
+ });
90
+ return new Response("y");
91
+ });
92
+ await res.text();
93
+ await drainAfterResponse(1000);
94
+ expect(done).toBe(true);
95
+ });
96
+
97
+ test("drain returns promptly when nothing is pending", async () => {
98
+ const t = Date.now();
99
+ await drainAfterResponse(500);
100
+ expect(Date.now() - t).toBeLessThan(200);
101
+ });
102
+
103
+ test("drain gives up rather than hanging on a stuck task", async () => {
104
+ const res = await withAfterResponse(req(), async () => {
105
+ afterResponse(() => Bun.sleep(60_000));
106
+ return new Response("z");
107
+ });
108
+ await res.text();
109
+ const t = Date.now();
110
+ await drainAfterResponse(200);
111
+ expect(Date.now() - t).toBeLessThan(1500);
112
+ });
113
+ });
@@ -0,0 +1,83 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ CACHE_CONTROL,
4
+ cacheControlFor,
5
+ isContentAddressed,
6
+ } from "../src/server/asset-cache.ts";
7
+
8
+ /**
9
+ * The policy, tested directly rather than through a booted server.
10
+ *
11
+ * This is where the bug lived — a caching decision, not a routing one — so
12
+ * it is the decision worth pinning. Importing the real function rather than
13
+ * restating it here: a test that keeps its own copy passes no matter what
14
+ * the server does, which is worse than no test at all.
15
+ */
16
+ describe("isContentAddressed", () => {
17
+ test("a hash in the filename counts", () => {
18
+ expect(isContentAddressed("/style.a1b2c3d4.css", "")).toBe(true);
19
+ expect(isContentAddressed("/glyphs/ok.9f8e7d6c.svg", "")).toBe(true);
20
+ });
21
+
22
+ test("a longer hash still counts", () => {
23
+ expect(isContentAddressed("/style.deadbeef0123456789.css", "")).toBe(true);
24
+ });
25
+
26
+ test("a bare filename does not count", () => {
27
+ // The bug this policy exists to prevent: a year-long cache at a URL
28
+ // that never changes, so an edited stylesheet is never seen.
29
+ expect(isContentAddressed("/style.css", "")).toBe(false);
30
+ expect(isContentAddressed("/mark.svg", "")).toBe(false);
31
+ });
32
+
33
+ test("a version query counts", () => {
34
+ expect(isContentAddressed("/style.css", "?v=1")).toBe(true);
35
+ expect(isContentAddressed("/style.css", "?v=abc123")).toBe(true);
36
+ expect(isContentAddressed("/style.css", "?a=1&v=2")).toBe(true);
37
+ });
38
+
39
+ test("an empty version value does not count", () => {
40
+ // /style.css? and /style.css are the same resource, so treating it
41
+ // as addressed would cache it forever without it ever changing.
42
+ expect(isContentAddressed("/style.css", "?v=")).toBe(false);
43
+ expect(isContentAddressed("/style.css", "?")).toBe(false);
44
+ });
45
+
46
+ test("an unrelated query does not count", () => {
47
+ expect(isContentAddressed("/style.css", "?theme=dark")).toBe(false);
48
+ expect(isContentAddressed("/style.css", "?cachebust=1")).toBe(false);
49
+ });
50
+
51
+ test("a non-hash dotted name is not treated as addressed", () => {
52
+ // theme.min.css is common and 3 hex chars is not a hash.
53
+ expect(isContentAddressed("/app.min.css", "")).toBe(false);
54
+ expect(isContentAddressed("/style.abc.css", "")).toBe(false);
55
+ });
56
+ });
57
+
58
+ describe("cacheControlFor", () => {
59
+ test("the document is never cached", () => {
60
+ expect(cacheControlFor("/", "")).toBe("no-cache");
61
+ expect(cacheControlFor("/index.html", "")).toBe("no-cache");
62
+ });
63
+
64
+ test("a content-addressed asset is immutable", () => {
65
+ expect(cacheControlFor("/style.a1b2c3d4.css", "")).toBe("immutable");
66
+ expect(cacheControlFor("/style.css", "?v=2")).toBe("immutable");
67
+ });
68
+
69
+ test("everything else revalidates", () => {
70
+ expect(cacheControlFor("/style.css", "")).toBe("revalidate");
71
+ expect(cacheControlFor("/mark.svg", "")).toBe("revalidate");
72
+ });
73
+
74
+ test("every policy has a header", () => {
75
+ expect(CACHE_CONTROL[cacheControlFor("/", "")]).toBe("no-cache");
76
+ expect(CACHE_CONTROL[cacheControlFor("/a.12345678.css", "")]).toContain(
77
+ "immutable",
78
+ );
79
+ expect(CACHE_CONTROL[cacheControlFor("/a.css", "")]).toContain(
80
+ "must-revalidate",
81
+ );
82
+ });
83
+ });
@@ -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;