@sigil-dev/grimoire 0.9.29 → 0.9.31

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 (105) hide show
  1. package/bin/sigil.ts +4 -0
  2. package/index.ts +16 -10
  3. package/package.json +14 -6
  4. package/server.ts +2 -2
  5. package/src/adapters/bun.ts +17 -17
  6. package/src/adapters/static.ts +41 -41
  7. package/src/adapters/types.ts +36 -36
  8. package/src/base.ts +4 -1
  9. package/src/client/csrf.ts +47 -47
  10. package/src/client/deferred.ts +1 -4
  11. package/src/client/enhance.ts +160 -160
  12. package/src/client/router.ts +927 -926
  13. package/src/config-file.ts +84 -0
  14. package/src/dev/compile-module.ts +199 -193
  15. package/src/dev/hmr-client.ts +229 -229
  16. package/src/dev/hmr-server.ts +274 -266
  17. package/src/dev/loader.ts +144 -144
  18. package/src/dev/runtime-bundle.ts +5 -3
  19. package/src/duration.ts +46 -0
  20. package/src/env/modules.ts +62 -62
  21. package/src/env/required.ts +42 -42
  22. package/src/env/typegen.ts +61 -61
  23. package/src/headers.ts +105 -105
  24. package/src/logger/transports.ts +117 -117
  25. package/src/plugin-order.ts +88 -0
  26. package/src/rendering/head.ts +49 -49
  27. package/src/rendering/hydrate.ts +162 -162
  28. package/src/rendering/images.ts +43 -43
  29. package/src/rendering/preload.ts +22 -8
  30. package/src/rendering/ssrPlugin.ts +107 -107
  31. package/src/rendering/timing.ts +40 -40
  32. package/src/routing/route-ids.ts +65 -0
  33. package/src/routing/route.ts +65 -0
  34. package/src/routing/router.ts +84 -32
  35. package/src/routing/scanner.ts +18 -5
  36. package/src/routing/transform-routes.ts +102 -102
  37. package/src/server/after-response.ts +206 -206
  38. package/src/server/asset-cache.ts +57 -57
  39. package/src/server/build.ts +304 -295
  40. package/src/server/cached.ts +114 -114
  41. package/src/server/client-address.ts +82 -82
  42. package/src/server/client-dir.ts +63 -63
  43. package/src/server/client-entry.ts +44 -44
  44. package/src/server/context.ts +18 -10
  45. package/src/server/cookie-utils.ts +80 -80
  46. package/src/server/coordinator.ts +479 -476
  47. package/src/server/hooks.ts +122 -122
  48. package/src/server/index.ts +1181 -1171
  49. package/src/server/plugins.ts +172 -172
  50. package/src/server/prerender.ts +473 -473
  51. package/src/server/reserved.ts +17 -17
  52. package/src/server/resolver.ts +149 -123
  53. package/src/server/rewrite.ts +28 -28
  54. package/src/server/warm.ts +9 -3
  55. package/src/server/with-headers.ts +27 -27
  56. package/src/server/worker.ts +2 -6
  57. package/src/server-only.ts +78 -0
  58. package/src/testing/dom.ts +73 -73
  59. package/src/testing/index.ts +169 -169
  60. package/src/testing/server.ts +1 -0
  61. package/src/typegen/index.ts +97 -2
  62. package/src/types.ts +642 -508
  63. package/test/after-response.test.ts +132 -132
  64. package/test/asset-cache-policy.test.ts +6 -2
  65. package/test/base.test.ts +20 -6
  66. package/test/cached.test.ts +126 -126
  67. package/test/client-address.test.ts +78 -78
  68. package/test/client-csrf.test.ts +61 -61
  69. package/test/client-dir.test.ts +101 -101
  70. package/test/client-router.test.ts +37 -5
  71. package/test/config-file.test.ts +84 -0
  72. package/test/coordinator.test.ts +9 -2
  73. package/test/deferred.test.ts +4 -2
  74. package/test/dev-loader.test.ts +30 -30
  75. package/test/env.test.ts +171 -171
  76. package/test/force-production.test.ts +7 -2
  77. package/test/images.test.ts +20 -8
  78. package/test/locals-header.test.ts +61 -61
  79. package/test/middleware.test.ts +243 -243
  80. package/test/parser-plugins.test.ts +98 -92
  81. package/test/plugin-handle.test.ts +62 -62
  82. package/test/plugin-order.test.ts +98 -0
  83. package/test/plugin-routes.test.ts +47 -42
  84. package/test/plugin-services-context.test.ts +7 -2
  85. package/test/preload.test.ts +4 -1
  86. package/test/prerender.test.ts +3 -1
  87. package/test/rendering.test.ts +3 -2
  88. package/test/required-env.test.ts +32 -32
  89. package/test/resolver-windows.test.ts +22 -23
  90. package/test/rewrite-html.test.ts +90 -90
  91. package/test/route-group-layouts.test.ts +38 -36
  92. package/test/route.test.ts +103 -0
  93. package/test/routing.test.ts +225 -197
  94. package/test/scanning.test.ts +53 -33
  95. package/test/server-context.test.ts +22 -0
  96. package/test/server-only.test.ts +110 -0
  97. package/test/server.test.ts +659 -640
  98. package/test/services.test.ts +3 -3
  99. package/test/streaming.test.ts +11 -6
  100. package/test/testing-helpers.test.ts +166 -166
  101. package/test/typegen.test.ts +209 -112
  102. package/test/warm.test.ts +96 -96
  103. package/test/worker-context.test.ts +59 -59
  104. package/test/workspace-files.test.ts +26 -10
  105. package/test/workspace-versions.test.ts +146 -131
@@ -1,640 +1,659 @@
1
- import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
- import { mkdir, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { createServer } from "../src/server";
6
-
7
- // ── Sandbox note ─────────────────────────────────────────────────────────────
8
- // The Babel plugin unconditionally inserts `import ... from "@sigil-dev/runtime"`
9
- // for all non-SSR route files. When createServer() calls Bun.build to bundle hydrate.js,
10
- // those compiled page files pull in @sigil-dev/runtime → Bun's test sandbox blocks the
11
- // read of packages/runtime/index.ts.
12
- //
13
- // Consequence: createServer() integration tests can only use +server.ts API routes
14
- // (which are never bundled by Bun.build). Form action behavior at the HTTP level cannot
15
- // be tested here — it is covered at unit level by fail.test.ts and redirect-error.test.ts,
16
- // and at the renderer level by rendering.test.ts.
17
- // ─────────────────────────────────────────────────────────────────────────────
18
-
19
- let tmpDir: string;
20
-
21
- beforeAll(async () => {
22
- tmpDir = join(tmpdir(), `grimoire-server-${Date.now()}`);
23
- await mkdir(join(tmpDir, "api", "hello"), { recursive: true });
24
- await mkdir(join(tmpDir, "api", "items"), { recursive: true });
25
- await mkdir(join(tmpDir, "api", "away"), { recursive: true });
26
-
27
- await writeFile(
28
- join(tmpDir, "api", "hello", "+server.ts"),
29
- `export async function GET() { return Response.json({ message: "hello" }); }`,
30
- );
31
-
32
- await writeFile(
33
- join(tmpDir, "api", "items", "+server.ts"),
34
- `export async function GET() {
35
- return Response.json([{ id: 1, name: "sword" }]);
36
- }
37
- export async function POST({ request }) {
38
- const body = await request.json();
39
- return Response.json({ id: 2, ...body }, { status: 201 });
40
- }`,
41
- );
42
-
43
- // what redirect(303, "/login") throws
44
- await writeFile(
45
- join(tmpDir, "api", "away", "+server.ts"),
46
- `export async function POST() {
47
- throw { __redirect: true, status: 303, location: "/login" };
48
- }`,
49
- );
50
- });
51
-
52
- describe("Server — API routes (+server.ts)", () => {
53
- test("GET returns JSON", async () => {
54
- const server = await createServer({
55
- port: 3004,
56
- routes: tmpDir,
57
- _skipBuild: true,
58
- });
59
- const res = await fetch("http://localhost:3004/api/hello");
60
- const data = await res.json();
61
- expect(data.message).toBe("hello");
62
- server.stop();
63
- });
64
-
65
- test("GET on multi-method route returns correct JSON", async () => {
66
- const server = await createServer({
67
- port: 3004,
68
- routes: tmpDir,
69
- _skipBuild: true,
70
- });
71
- const res = await fetch("http://localhost:3004/api/items");
72
- expect(res.status).toBe(200);
73
- const items = await res.json();
74
- expect(items[0].name).toBe("sword");
75
- server.stop();
76
- });
77
-
78
- test("POST returns 201 with created resource", async () => {
79
- const server = await createServer({
80
- port: 3004,
81
- routes: tmpDir,
82
- _skipBuild: true,
83
- });
84
- const res = await fetch("http://localhost:3004/api/items", {
85
- method: "POST",
86
- headers: { "Content-Type": "application/json" },
87
- body: JSON.stringify({ name: "shield" }),
88
- });
89
- expect(res.status).toBe(201);
90
- const item = await res.json();
91
- expect(item.name).toBe("shield");
92
- server.stop();
93
- });
94
-
95
- test("a thrown redirect becomes a redirect response", async () => {
96
- const server = await createServer({
97
- port: 3004,
98
- routes: tmpDir,
99
- _skipBuild: true,
100
- });
101
- const res = await fetch("http://localhost:3004/api/away", {
102
- method: "POST",
103
- redirect: "manual",
104
- });
105
- expect(res.status).toBe(303);
106
- expect(res.headers.get("Location")).toBe("/login");
107
- server.stop();
108
- });
109
-
110
- test("unsupported method returns 405", async () => {
111
- const server = await createServer({
112
- port: 3004,
113
- routes: tmpDir,
114
- _skipBuild: true,
115
- });
116
- const res = await fetch("http://localhost:3004/api/items", {
117
- method: "DELETE",
118
- });
119
- expect(res.status).toBe(405);
120
- server.stop();
121
- });
122
- });
123
-
124
- describe("Server — WebSocket routes", () => {
125
- let wsDir: string;
126
- let server: Awaited<ReturnType<typeof createServer>>;
127
-
128
- beforeAll(async () => {
129
- wsDir = join(tmpdir(), `grimoire-ws-${Date.now()}`);
130
- await mkdir(join(wsDir, "echo"), { recursive: true });
131
- await mkdir(join(wsDir, "params", "[docId]"), { recursive: true });
132
- await mkdir(join(wsDir, "reject"), { recursive: true });
133
- await mkdir(join(wsDir, "mixed"), { recursive: true });
134
-
135
- // echo: upgrade() merges extra data, message handler echoes back
136
- await writeFile(
137
- join(wsDir, "echo", "+server.ts"),
138
- `export function upgrade({ params }) {
139
- return { sessionId: "abc123" };
140
- }
141
- export const websocket = {
142
- message(ws, data) { ws.send("echo:" + data); },
143
- };`,
144
- );
145
-
146
- // params: no upgrade(), ws.data.params still available
147
- await writeFile(
148
- join(wsDir, "params", "[docId]", "+server.ts"),
149
- `export const websocket = {
150
- open(ws) { ws.send("docId:" + ws.data.params.docId); },
151
- };`,
152
- );
153
-
154
- // reject: upgrade() throws → 426
155
- await writeFile(
156
- join(wsDir, "reject", "+server.ts"),
157
- `export function upgrade() {
158
- throw new Error("Unauthorized");
159
- }
160
- export const websocket = {
161
- message(ws, data) { ws.send(data); },
162
- };`,
163
- );
164
-
165
- // mixed: HTTP GET and WebSocket both exported
166
- await writeFile(
167
- join(wsDir, "mixed", "+server.ts"),
168
- `export function GET() {
169
- return Response.json({ kind: "http" });
170
- }
171
- export function upgrade({ params }) { return {}; }
172
- export const websocket = {
173
- message(ws, data) { ws.send(data); },
174
- };`,
175
- );
176
-
177
- // a page beside a WebSocket-only +server.ts
178
- await mkdir(join(wsDir, "room"), { recursive: true });
179
- await writeFile(
180
- join(wsDir, "room", "+server.ts"),
181
- `export const websocket = { message(ws, data) { ws.send(data); } };`,
182
- );
183
- await writeFile(
184
- join(wsDir, "room", "+page.tsx"),
185
- `export default () => "<h1>room page</h1>";`,
186
- );
187
-
188
- server = await createServer({
189
- port: 3005,
190
- routes: wsDir,
191
- _skipBuild: true,
192
- });
193
- });
194
-
195
- afterAll(() => {
196
- server.stop();
197
- });
198
- test("a method the endpoint doesn't handle renders the page", async () => {
199
- const res = await fetch("http://localhost:3005/room");
200
- expect(res.status).toBe(200);
201
- expect(await res.text()).toContain("room page");
202
- });
203
-
204
- test("with no page, it's still 405", async () => {
205
- const res = await fetch("http://localhost:3005/echo");
206
- expect(res.status).toBe(405);
207
- });
208
-
209
- function wsConnect(path: string): Promise<WebSocket> {
210
- return new Promise((resolve, reject) => {
211
- const ws = new WebSocket(`ws://localhost:3005${path}`);
212
- ws.onopen = () => resolve(ws);
213
- ws.onerror = () =>
214
- reject(new Error(`WebSocket connection failed: ${path}`));
215
- });
216
- }
217
-
218
- function nextMessage(ws: WebSocket): Promise<string> {
219
- return new Promise((resolve, reject) => {
220
- const timer = setTimeout(
221
- () => reject(new Error("timeout waiting for message")),
222
- 2000,
223
- );
224
- ws.onmessage = (ev) => {
225
- clearTimeout(timer);
226
- resolve(String(ev.data));
227
- };
228
- ws.onerror = () => {
229
- clearTimeout(timer);
230
- reject(new Error("ws error"));
231
- };
232
- });
233
- }
234
-
235
- test("message is echoed back", async () => {
236
- const ws = await wsConnect("/echo");
237
- const pending = nextMessage(ws);
238
- ws.send("hello");
239
- expect(await pending).toBe("echo:hello");
240
- ws.close();
241
- });
242
-
243
- test("upgrade() return value merges into ws.data", async () => {
244
- // sessionId set in upgrade() — echo route sends it back via a second message
245
- const ws = new WebSocket("ws://localhost:3005/echo");
246
- // just verify connection opens cleanly (sessionId is in ws.data server-side)
247
- await new Promise<void>((resolve, reject) => {
248
- const t = setTimeout(() => reject(new Error("timeout")), 2000);
249
- ws.onopen = () => {
250
- clearTimeout(t);
251
- resolve();
252
- };
253
- ws.onerror = () => {
254
- clearTimeout(t);
255
- reject(new Error("connect failed"));
256
- };
257
- });
258
- ws.close();
259
- });
260
-
261
- test("ws.data.params available when no upgrade() export", async () => {
262
- const ws = await wsConnect("/params/42");
263
- expect(await nextMessage(ws)).toBe("docId:42");
264
- ws.close();
265
- });
266
-
267
- test("upgrade() throwing rejects the connection", async () => {
268
- await new Promise<void>((resolve, reject) => {
269
- const ws = new WebSocket("ws://localhost:3005/reject");
270
- const t = setTimeout(() => reject(new Error("timeout")), 2000);
271
- ws.onopen = () => {
272
- clearTimeout(t);
273
- ws.close();
274
- reject(new Error("should not have opened"));
275
- };
276
- ws.onerror = () => {
277
- clearTimeout(t);
278
- resolve();
279
- };
280
- ws.onclose = (ev) => {
281
- clearTimeout(t);
282
- if (ev.code !== 1006) resolve();
283
- else resolve();
284
- };
285
- });
286
- });
287
-
288
- test("plain HTTP GET on mixed route still works (no Upgrade header)", async () => {
289
- const res = await fetch("http://localhost:3005/mixed");
290
- expect(res.status).toBe(200);
291
- const body = await res.json();
292
- expect(body.kind).toBe("http");
293
- });
294
- });
295
-
296
- describe("Server — named form actions (?/name)", () => {
297
- let server: { stop: () => void };
298
- let csrfToken = "";
299
- const base = "http://localhost:3006";
300
-
301
- beforeAll(async () => {
302
- await mkdir(join(tmpDir, "form"), { recursive: true });
303
- await writeFile(
304
- join(tmpDir, "form", "+page.tsx"),
305
- 'export default ({ form }) => "<h1>form</h1>" + (form ? "form-says:" + form.method : "");',
306
- );
307
- await writeFile(
308
- join(tmpDir, "form", "+page.server.ts"),
309
- [
310
- "export async function create(action) {",
311
- " return {",
312
- " __fail: true,",
313
- " status: 400,",
314
- " data: {",
315
- " ok: false,",
316
- ' hasCookies: typeof action.cookies?.get === "function",',
317
- " method: action.request.method,",
318
- " },",
319
- " };",
320
- "}",
321
- "export function load() { return {}; }",
322
- "export async function teapot() { throw new Response('short and stout', { status: 418 }); }",
323
- "export async function raw() { return new Response('raw reply', { status: 202 }); }",
324
- "export async function POST() {",
325
- ' return { redirect: "/done" };',
326
- "}",
327
- "export function GET() {",
328
- ' return { redirect: "/ran-get" };',
329
- "}",
330
- ].join("\n"),
331
- );
332
-
333
- // a page with a scoped style block (tag split: this file's own
334
- // preload strips literal style blocks from sources it loads)
335
- const tag = (name: string) => `<${name}>`;
336
- await mkdir(join(tmpDir, "styled"), { recursive: true });
337
- await writeFile(
338
- join(tmpDir, "styled", "+page.tsx"),
339
- `export default () => <h1 class="t">styled</h1>;\n${tag("style")}\n.t { color: red; }\n.u { color: blue; }\n${tag("/style")}\n`,
340
- );
341
- await mkdir(join(tmpDir, "forms"), { recursive: true });
342
- await writeFile(
343
- join(tmpDir, "forms", "+page.tsx"),
344
- `export default () => '<form method="post" id="a"></form><form method="POST" action="?/x" id="b"></form><form action="/search" id="c"></form><form id="d"></form>';`,
345
- );
346
- // a streaming page: the loading shell goes out before the page renders
347
- await mkdir(join(tmpDir, "slow"), { recursive: true });
348
- await writeFile(
349
- join(tmpDir, "slow", "+page.tsx"),
350
- [
351
- `export const loading = () => '<form method="post" id="shell"></form>';`,
352
- `export default () => '<form method="post" id="page"></form>';`,
353
- ].join("\n"),
354
- );
355
-
356
- server = await createServer({
357
- port: 3006,
358
- routes: tmpDir,
359
- _skipBuild: true,
360
- });
361
- // SSR render sets the _csrf cookie
362
- const res = await fetch(`${base}/form`);
363
- const setCookie = res.headers.get("set-cookie") ?? "";
364
- csrfToken = /_csrf=([a-f0-9]+)/.exec(setCookie)?.[1] ?? "";
365
- });
366
-
367
- afterAll(() => server.stop());
368
-
369
- test("POST ?/create invokes the named export with cookies", async () => {
370
- const res = await fetch(`${base}/form?/create`, {
371
- method: "POST",
372
- headers: {
373
- "Content-Type": "application/x-www-form-urlencoded",
374
- Cookie: `_csrf=${csrfToken}`,
375
- "X-Grimoire-Form": "1",
376
- },
377
- body: `x=1&_csrf=${csrfToken}`,
378
- });
379
- expect(res.status).toBe(400);
380
- // shape asserted below — typed to satisfy strict unknown-returning json()
381
- const json = (await res.json()) as {
382
- fail: boolean;
383
- data: { hasCookies: boolean; method: string };
384
- };
385
- expect(json.fail).toBe(true);
386
- expect(json.data.hasCookies).toBe(true);
387
- expect(json.data.method).toBe("POST");
388
- });
389
-
390
- test("a plain POST that fails re-renders the page with a form prop", async () => {
391
- const res = await fetch(`${base}/form?/create`, {
392
- method: "POST",
393
- headers: {
394
- "Content-Type": "application/x-www-form-urlencoded",
395
- Cookie: `_csrf=${csrfToken}`,
396
- },
397
- body: `x=1&_csrf=${csrfToken}`,
398
- });
399
- expect(res.status).toBe(400);
400
- expect(res.headers.get("content-type")).toContain("text/html");
401
- const html = await res.text();
402
- expect(html).toContain("<h1>form</h1>");
403
- expect(html).toContain("form-says:POST");
404
- // hydration gets the same prop
405
- expect(html).toMatch(/"form":\{"ok":false[^}]*"method":"POST"/);
406
- });
407
-
408
- test("unknown named action returns 404", async () => {
409
- const res = await fetch(`${base}/form?/nope`, {
410
- method: "POST",
411
- headers: {
412
- "Content-Type": "application/x-www-form-urlencoded",
413
- Cookie: `_csrf=${csrfToken}`,
414
- },
415
- body: `x=1&_csrf=${csrfToken}`,
416
- });
417
- expect(res.status).toBe(404);
418
- });
419
-
420
- test("GET never runs a named action; it renders the page", async () => {
421
- const res = await fetch(`${base}/form?/create`);
422
- expect(res.status).toBe(200);
423
- expect(res.headers.get("content-type")).toContain("text/html");
424
- expect(await res.text()).toContain("form");
425
- });
426
-
427
- test("a page's scoped CSS is in the server-rendered <head>", async () => {
428
- const html = await (await fetch(`${base}/styled`)).text();
429
- const head = html.slice(0, html.indexOf("</head>"));
430
- const hash = /<h1 class="t (s[0-9a-f]{8})">/.exec(html)?.[1];
431
- expect(hash).toBeDefined();
432
- expect(head).toContain(`<style id="sigil-${hash}">`);
433
- expect(head).toContain(`.t.${hash} { color: red; }`);
434
- expect(head).toContain(`.u.${hash} { color: blue; }`);
435
- });
436
-
437
- test("every POST form gets a CSRF input, GET forms never do", async () => {
438
- const html = await (await fetch(`${base}/forms`)).text();
439
- const token = (id: string) =>
440
- new RegExp(
441
- `<form[^>]*id="${id}"[^>]*><input type="hidden" name="_csrf"`,
442
- ).test(html);
443
- expect(token("a")).toBe(true); // no action attribute
444
- expect(token("b")).toBe(true);
445
- expect(token("c")).toBe(false); // GET: the token would land in the URL
446
- expect(token("d")).toBe(false);
447
- });
448
-
449
- test("a GET export in +page.server.ts is not run for page views", async () => {
450
- const res = await fetch(`${base}/form`, { redirect: "manual" });
451
- expect(res.status).toBe(200);
452
- expect(await res.text()).toContain("<h1>form</h1>");
453
- const head = await fetch(`${base}/form`, { method: "HEAD" });
454
- expect(head.status).toBe(200);
455
- });
456
-
457
- test("streaming pages get CSRF tokens and the cookie too", async () => {
458
- const res = await fetch(`${base}/slow`);
459
- const token = /_csrf=([a-f0-9]+)/.exec(
460
- res.headers.get("set-cookie") ?? "",
461
- )?.[1];
462
- expect(token).toBeDefined();
463
- const html = await res.text();
464
- for (const id of ["shell", "page"]) {
465
- expect(html).toContain(
466
- `<form method="post" id="${id}"><input type="hidden" name="_csrf" value="${token}"`,
467
- );
468
- }
469
- });
470
-
471
- test("an existing CSRF cookie is kept, so other tabs' forms still work", async () => {
472
- const res = await fetch(`${base}/forms`, {
473
- headers: { Cookie: `_csrf=${csrfToken}` },
474
- });
475
- expect(res.headers.get("set-cookie")).toContain(`_csrf=${csrfToken}`);
476
- expect(await res.text()).toContain(`value="${csrfToken}"`);
477
- // a malformed cookie is replaced
478
- const bad = await fetch(`${base}/forms`, {
479
- headers: { Cookie: "_csrf=nope" },
480
- });
481
- expect(bad.headers.get("set-cookie")).toMatch(/_csrf=[0-9a-f]{64}/);
482
- });
483
-
484
- test("load and the other module hooks are not actions", async () => {
485
- for (const name of ["load", "canMatch", "csrf"]) {
486
- const res = await fetch(`${base}/form?/${name}`, {
487
- method: "POST",
488
- headers: {
489
- "Content-Type": "application/x-www-form-urlencoded",
490
- Cookie: `_csrf=${csrfToken}`,
491
- },
492
- body: `x=1&_csrf=${csrfToken}`,
493
- });
494
- expect(res.status).toBe(404);
495
- }
496
- });
497
-
498
- test("an action can throw or return a Response and it is the reply", async () => {
499
- const post = (name: string) =>
500
- fetch(`${base}/form?/${name}`, {
501
- method: "POST",
502
- headers: {
503
- "Content-Type": "application/x-www-form-urlencoded",
504
- Cookie: `_csrf=${csrfToken}`,
505
- },
506
- body: `x=1&_csrf=${csrfToken}`,
507
- redirect: "manual",
508
- });
509
- const thrown = await post("teapot");
510
- expect(thrown.status).toBe(418);
511
- expect(await thrown.text()).toBe("short and stout");
512
- const returned = await post("raw");
513
- expect(returned.status).toBe(202);
514
- expect(await returned.text()).toBe("raw reply");
515
- });
516
-
517
- test("POST named action without CSRF token is forbidden", async () => {
518
- const res = await fetch(`${base}/form?/create`, {
519
- method: "POST",
520
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
521
- body: "x=1",
522
- });
523
- expect(res.status).toBe(403);
524
- });
525
-
526
- test("an enhanced submission gets its outcome as JSON, not a 303", async () => {
527
- const res = await fetch(`${base}/form`, {
528
- method: "POST",
529
- headers: {
530
- "Content-Type": "application/x-www-form-urlencoded",
531
- Cookie: `_csrf=${csrfToken}`,
532
- "X-Grimoire-Form": "1",
533
- },
534
- body: `x=1&_csrf=${csrfToken}`,
535
- redirect: "manual",
536
- });
537
- expect(res.status).toBe(200);
538
- expect(await res.json()).toEqual({
539
- type: "success",
540
- location: "/done",
541
- data: { redirect: "/done" },
542
- });
543
- });
544
-
545
- test("method dispatch without query key is unchanged", async () => {
546
- const res = await fetch(`${base}/form`, {
547
- method: "POST",
548
- headers: {
549
- "Content-Type": "application/x-www-form-urlencoded",
550
- Cookie: `_csrf=${csrfToken}`,
551
- },
552
- body: `x=1&_csrf=${csrfToken}`,
553
- redirect: "manual",
554
- });
555
- expect(res.status).toBe(303);
556
- expect(res.headers.get("location")).toBe("/done");
557
- });
558
- });
559
-
560
- describe("Server — error pages", () => {
561
- let dir: string;
562
- let server: Awaited<ReturnType<typeof createServer>>;
563
- const base = "http://localhost:3012";
564
-
565
- beforeAll(async () => {
566
- dir = join(tmpdir(), `grimoire-errors-${Date.now()}`);
567
- await mkdir(join(dir, "boom"), { recursive: true });
568
- await writeFile(
569
- join(dir, "+error.tsx"),
570
- "export default ({ status, message }) => `<h1>oops ${status}: ${message}</h1>`;",
571
- );
572
- await writeFile(
573
- join(dir, "boom", "+page.server.ts"),
574
- 'export function load() { throw new Error("db password is hunter2"); }',
575
- );
576
- await writeFile(
577
- join(dir, "boom", "+page.tsx"),
578
- "export default () => 'never';",
579
- );
580
- // a root layout with its own server data, a nested error page, and
581
- // one in a [param] folder
582
- await writeFile(
583
- join(dir, "+layout.tsx"),
584
- 'export default ({ data, children }) => `<main data-site="${data.site}">${children}</main>`;',
585
- );
586
- await writeFile(
587
- join(dir, "+layout.server.ts"),
588
- 'export function load() { return { site: "meow" }; }',
589
- );
590
- await mkdir(join(dir, "shop"), { recursive: true });
591
- await writeFile(
592
- join(dir, "shop", "+error.tsx"),
593
- "export default ({ status }) => `<h1>shop ${status}</h1>`;",
594
- );
595
- await mkdir(join(dir, "items", "[id]"), { recursive: true });
596
- await writeFile(
597
- join(dir, "items", "[id]", "+error.tsx"),
598
- "export default ({ status }) => `<h1>item ${status}</h1>`;",
599
- );
600
- server = await createServer({ port: 3012, routes: dir, _skipBuild: true });
601
- });
602
-
603
- afterAll(() => server.stop());
604
-
605
- test("an unknown URL renders +error.tsx as a whole document", async () => {
606
- const res = await fetch(`${base}/nowhere`);
607
- expect(res.status).toBe(404);
608
- const html = await res.text();
609
- expect(html).toContain("<!DOCTYPE html>");
610
- expect(html).toContain("oops 404: Not Found");
611
- });
612
-
613
- test("an unknown URL's error page sits in the layouts, with their data", async () => {
614
- const html = await (await fetch(`${base}/nowhere/at/all`)).text();
615
- expect(html).toContain('<main data-site="meow">');
616
- expect(html).toContain("oops 404: Not Found");
617
- });
618
-
619
- test("an unknown URL gets the closest +error.tsx", async () => {
620
- const res = await fetch(`${base}/shop/no-such-thing`);
621
- expect(res.status).toBe(404);
622
- expect(await res.text()).toContain("shop 404");
623
- });
624
-
625
- test("a +error.tsx in a [param] folder covers the addresses under it", async () => {
626
- expect(await (await fetch(`${base}/items/42/missing`)).text()).toContain(
627
- "item 404",
628
- );
629
- // /items itself is above the [id] folder
630
- expect(await (await fetch(`${base}/items`)).text()).toContain("oops 404");
631
- });
632
-
633
- test("an unexpected error renders +error.tsx with a generic message", async () => {
634
- const res = await fetch(`${base}/boom`);
635
- expect(res.status).toBe(500);
636
- const html = await res.text();
637
- expect(html).toContain("oops 500: Internal Server Error");
638
- expect(html).not.toContain("hunter2");
639
- });
640
- });
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createServer } from "../src/server";
6
+
7
+ // ── Sandbox note ─────────────────────────────────────────────────────────────
8
+ // The Babel plugin unconditionally inserts `import ... from "@sigil-dev/runtime"`
9
+ // for all non-SSR route files. When createServer() calls Bun.build to bundle hydrate.js,
10
+ // those compiled page files pull in @sigil-dev/runtime → Bun's test sandbox blocks the
11
+ // read of packages/runtime/index.ts.
12
+ //
13
+ // Consequence: createServer() integration tests can only use +server.ts API routes
14
+ // (which are never bundled by Bun.build). Form action behavior at the HTTP level cannot
15
+ // be tested here — it is covered at unit level by fail.test.ts and redirect-error.test.ts,
16
+ // and at the renderer level by rendering.test.ts.
17
+ // ─────────────────────────────────────────────────────────────────────────────
18
+
19
+ let tmpDir: string;
20
+
21
+ beforeAll(async () => {
22
+ tmpDir = join(tmpdir(), `grimoire-server-${Date.now()}`);
23
+ await mkdir(join(tmpDir, "api", "hello"), { recursive: true });
24
+ await mkdir(join(tmpDir, "api", "items"), { recursive: true });
25
+ await mkdir(join(tmpDir, "api", "away"), { recursive: true });
26
+
27
+ await writeFile(
28
+ join(tmpDir, "api", "hello", "+server.ts"),
29
+ `export async function GET() { return Response.json({ message: "hello" }); }`,
30
+ );
31
+
32
+ await writeFile(
33
+ join(tmpDir, "api", "items", "+server.ts"),
34
+ `export async function GET() {
35
+ return Response.json([{ id: 1, name: "sword" }]);
36
+ }
37
+ export async function POST({ request }) {
38
+ const body = await request.json();
39
+ return Response.json({ id: 2, ...body }, { status: 201 });
40
+ }`,
41
+ );
42
+
43
+ // what redirect(303, "/login") throws
44
+ await writeFile(
45
+ join(tmpDir, "api", "away", "+server.ts"),
46
+ `export async function POST() {
47
+ throw { __redirect: true, status: 303, location: "/login" };
48
+ }`,
49
+ );
50
+ });
51
+
52
+ describe("Server — API routes (+server.ts)", () => {
53
+ test("GET returns JSON", async () => {
54
+ const server = await createServer({
55
+ port: 3004,
56
+ routes: tmpDir,
57
+ _skipBuild: true,
58
+ });
59
+ const res = await fetch("http://localhost:3004/api/hello");
60
+ const data = await res.json();
61
+ expect(data.message).toBe("hello");
62
+ server.stop();
63
+ });
64
+
65
+ test("GET on multi-method route returns correct JSON", async () => {
66
+ const server = await createServer({
67
+ port: 3004,
68
+ routes: tmpDir,
69
+ _skipBuild: true,
70
+ });
71
+ const res = await fetch("http://localhost:3004/api/items");
72
+ expect(res.status).toBe(200);
73
+ const items = await res.json();
74
+ expect(items[0].name).toBe("sword");
75
+ server.stop();
76
+ });
77
+
78
+ test("POST returns 201 with created resource", async () => {
79
+ const server = await createServer({
80
+ port: 3004,
81
+ routes: tmpDir,
82
+ _skipBuild: true,
83
+ });
84
+ const res = await fetch("http://localhost:3004/api/items", {
85
+ method: "POST",
86
+ headers: { "Content-Type": "application/json" },
87
+ body: JSON.stringify({ name: "shield" }),
88
+ });
89
+ expect(res.status).toBe(201);
90
+ const item = await res.json();
91
+ expect(item.name).toBe("shield");
92
+ server.stop();
93
+ });
94
+
95
+ test("a thrown redirect becomes a redirect response", async () => {
96
+ const server = await createServer({
97
+ port: 3004,
98
+ routes: tmpDir,
99
+ _skipBuild: true,
100
+ });
101
+ const res = await fetch("http://localhost:3004/api/away", {
102
+ method: "POST",
103
+ redirect: "manual",
104
+ });
105
+ expect(res.status).toBe(303);
106
+ expect(res.headers.get("Location")).toBe("/login");
107
+ server.stop();
108
+ });
109
+
110
+ test("maxRequestBodySize caps request bodies", async () => {
111
+ const server = await createServer({
112
+ port: 3004,
113
+ routes: tmpDir,
114
+ _skipBuild: true,
115
+ maxRequestBodySize: 1024,
116
+ });
117
+ const post = (size: number) =>
118
+ fetch("http://localhost:3004/api/items", {
119
+ method: "POST",
120
+ headers: { "Content-Type": "application/json" },
121
+ body: JSON.stringify({ name: "x".repeat(size) }),
122
+ }).catch(() => null);
123
+ expect((await post(100))?.status).toBe(201);
124
+ // Bun answers 413 or drops the connection, depending on how far it got
125
+ expect((await post(64 * 1024))?.status ?? 413).toBe(413);
126
+ server.stop();
127
+ });
128
+
129
+ test("unsupported method returns 405", async () => {
130
+ const server = await createServer({
131
+ port: 3004,
132
+ routes: tmpDir,
133
+ _skipBuild: true,
134
+ });
135
+ const res = await fetch("http://localhost:3004/api/items", {
136
+ method: "DELETE",
137
+ });
138
+ expect(res.status).toBe(405);
139
+ server.stop();
140
+ });
141
+ });
142
+
143
+ describe("Server — WebSocket routes", () => {
144
+ let wsDir: string;
145
+ let server: Awaited<ReturnType<typeof createServer>>;
146
+
147
+ beforeAll(async () => {
148
+ wsDir = join(tmpdir(), `grimoire-ws-${Date.now()}`);
149
+ await mkdir(join(wsDir, "echo"), { recursive: true });
150
+ await mkdir(join(wsDir, "params", "[docId]"), { recursive: true });
151
+ await mkdir(join(wsDir, "reject"), { recursive: true });
152
+ await mkdir(join(wsDir, "mixed"), { recursive: true });
153
+
154
+ // echo: upgrade() merges extra data, message handler echoes back
155
+ await writeFile(
156
+ join(wsDir, "echo", "+server.ts"),
157
+ `export function upgrade({ params }) {
158
+ return { sessionId: "abc123" };
159
+ }
160
+ export const websocket = {
161
+ message(ws, data) { ws.send("echo:" + data); },
162
+ };`,
163
+ );
164
+
165
+ // params: no upgrade(), ws.data.params still available
166
+ await writeFile(
167
+ join(wsDir, "params", "[docId]", "+server.ts"),
168
+ `export const websocket = {
169
+ open(ws) { ws.send("docId:" + ws.data.params.docId); },
170
+ };`,
171
+ );
172
+
173
+ // reject: upgrade() throws → 426
174
+ await writeFile(
175
+ join(wsDir, "reject", "+server.ts"),
176
+ `export function upgrade() {
177
+ throw new Error("Unauthorized");
178
+ }
179
+ export const websocket = {
180
+ message(ws, data) { ws.send(data); },
181
+ };`,
182
+ );
183
+
184
+ // mixed: HTTP GET and WebSocket both exported
185
+ await writeFile(
186
+ join(wsDir, "mixed", "+server.ts"),
187
+ `export function GET() {
188
+ return Response.json({ kind: "http" });
189
+ }
190
+ export function upgrade({ params }) { return {}; }
191
+ export const websocket = {
192
+ message(ws, data) { ws.send(data); },
193
+ };`,
194
+ );
195
+
196
+ // a page beside a WebSocket-only +server.ts
197
+ await mkdir(join(wsDir, "room"), { recursive: true });
198
+ await writeFile(
199
+ join(wsDir, "room", "+server.ts"),
200
+ `export const websocket = { message(ws, data) { ws.send(data); } };`,
201
+ );
202
+ await writeFile(
203
+ join(wsDir, "room", "+page.tsx"),
204
+ `export default () => "<h1>room page</h1>";`,
205
+ );
206
+
207
+ server = await createServer({
208
+ port: 3005,
209
+ routes: wsDir,
210
+ _skipBuild: true,
211
+ });
212
+ });
213
+
214
+ afterAll(() => {
215
+ server.stop();
216
+ });
217
+ test("a method the endpoint doesn't handle renders the page", async () => {
218
+ const res = await fetch("http://localhost:3005/room");
219
+ expect(res.status).toBe(200);
220
+ expect(await res.text()).toContain("room page");
221
+ });
222
+
223
+ test("with no page, it's still 405", async () => {
224
+ const res = await fetch("http://localhost:3005/echo");
225
+ expect(res.status).toBe(405);
226
+ });
227
+
228
+ function wsConnect(path: string): Promise<WebSocket> {
229
+ return new Promise((resolve, reject) => {
230
+ const ws = new WebSocket(`ws://localhost:3005${path}`);
231
+ ws.onopen = () => resolve(ws);
232
+ ws.onerror = () =>
233
+ reject(new Error(`WebSocket connection failed: ${path}`));
234
+ });
235
+ }
236
+
237
+ function nextMessage(ws: WebSocket): Promise<string> {
238
+ return new Promise((resolve, reject) => {
239
+ const timer = setTimeout(
240
+ () => reject(new Error("timeout waiting for message")),
241
+ 2000,
242
+ );
243
+ ws.onmessage = (ev) => {
244
+ clearTimeout(timer);
245
+ resolve(String(ev.data));
246
+ };
247
+ ws.onerror = () => {
248
+ clearTimeout(timer);
249
+ reject(new Error("ws error"));
250
+ };
251
+ });
252
+ }
253
+
254
+ test("message is echoed back", async () => {
255
+ const ws = await wsConnect("/echo");
256
+ const pending = nextMessage(ws);
257
+ ws.send("hello");
258
+ expect(await pending).toBe("echo:hello");
259
+ ws.close();
260
+ });
261
+
262
+ test("upgrade() return value merges into ws.data", async () => {
263
+ // sessionId set in upgrade() — echo route sends it back via a second message
264
+ const ws = new WebSocket("ws://localhost:3005/echo");
265
+ // just verify connection opens cleanly (sessionId is in ws.data server-side)
266
+ await new Promise<void>((resolve, reject) => {
267
+ const t = setTimeout(() => reject(new Error("timeout")), 2000);
268
+ ws.onopen = () => {
269
+ clearTimeout(t);
270
+ resolve();
271
+ };
272
+ ws.onerror = () => {
273
+ clearTimeout(t);
274
+ reject(new Error("connect failed"));
275
+ };
276
+ });
277
+ ws.close();
278
+ });
279
+
280
+ test("ws.data.params available when no upgrade() export", async () => {
281
+ const ws = await wsConnect("/params/42");
282
+ expect(await nextMessage(ws)).toBe("docId:42");
283
+ ws.close();
284
+ });
285
+
286
+ test("upgrade() throwing rejects the connection", async () => {
287
+ await new Promise<void>((resolve, reject) => {
288
+ const ws = new WebSocket("ws://localhost:3005/reject");
289
+ const t = setTimeout(() => reject(new Error("timeout")), 2000);
290
+ ws.onopen = () => {
291
+ clearTimeout(t);
292
+ ws.close();
293
+ reject(new Error("should not have opened"));
294
+ };
295
+ ws.onerror = () => {
296
+ clearTimeout(t);
297
+ resolve();
298
+ };
299
+ ws.onclose = (ev) => {
300
+ clearTimeout(t);
301
+ if (ev.code !== 1006) resolve();
302
+ else resolve();
303
+ };
304
+ });
305
+ });
306
+
307
+ test("plain HTTP GET on mixed route still works (no Upgrade header)", async () => {
308
+ const res = await fetch("http://localhost:3005/mixed");
309
+ expect(res.status).toBe(200);
310
+ const body = await res.json();
311
+ expect(body.kind).toBe("http");
312
+ });
313
+ });
314
+
315
+ describe("Server — named form actions (?/name)", () => {
316
+ let server: { stop: () => void };
317
+ let csrfToken = "";
318
+ const base = "http://localhost:3006";
319
+
320
+ beforeAll(async () => {
321
+ await mkdir(join(tmpDir, "form"), { recursive: true });
322
+ await writeFile(
323
+ join(tmpDir, "form", "+page.tsx"),
324
+ 'export default ({ form }) => "<h1>form</h1>" + (form ? "form-says:" + form.method : "");',
325
+ );
326
+ await writeFile(
327
+ join(tmpDir, "form", "+page.server.ts"),
328
+ [
329
+ "export async function create(action) {",
330
+ " return {",
331
+ " __fail: true,",
332
+ " status: 400,",
333
+ " data: {",
334
+ " ok: false,",
335
+ ' hasCookies: typeof action.cookies?.get === "function",',
336
+ " method: action.request.method,",
337
+ " },",
338
+ " };",
339
+ "}",
340
+ "export function load() { return {}; }",
341
+ "export async function teapot() { throw new Response('short and stout', { status: 418 }); }",
342
+ "export async function raw() { return new Response('raw reply', { status: 202 }); }",
343
+ "export async function POST() {",
344
+ ' return { redirect: "/done" };',
345
+ "}",
346
+ "export function GET() {",
347
+ ' return { redirect: "/ran-get" };',
348
+ "}",
349
+ ].join("\n"),
350
+ );
351
+
352
+ // a page with a scoped style block (tag split: this file's own
353
+ // preload strips literal style blocks from sources it loads)
354
+ const tag = (name: string) => `<${name}>`;
355
+ await mkdir(join(tmpDir, "styled"), { recursive: true });
356
+ await writeFile(
357
+ join(tmpDir, "styled", "+page.tsx"),
358
+ `export default () => <h1 class="t">styled</h1>;\n${tag("style")}\n.t { color: red; }\n.u { color: blue; }\n${tag("/style")}\n`,
359
+ );
360
+ await mkdir(join(tmpDir, "forms"), { recursive: true });
361
+ await writeFile(
362
+ join(tmpDir, "forms", "+page.tsx"),
363
+ `export default () => '<form method="post" id="a"></form><form method="POST" action="?/x" id="b"></form><form action="/search" id="c"></form><form id="d"></form>';`,
364
+ );
365
+ // a streaming page: the loading shell goes out before the page renders
366
+ await mkdir(join(tmpDir, "slow"), { recursive: true });
367
+ await writeFile(
368
+ join(tmpDir, "slow", "+page.tsx"),
369
+ [
370
+ `export const loading = () => '<form method="post" id="shell"></form>';`,
371
+ `export default () => '<form method="post" id="page"></form>';`,
372
+ ].join("\n"),
373
+ );
374
+
375
+ server = await createServer({
376
+ port: 3006,
377
+ routes: tmpDir,
378
+ _skipBuild: true,
379
+ });
380
+ // SSR render sets the _csrf cookie
381
+ const res = await fetch(`${base}/form`);
382
+ const setCookie = res.headers.get("set-cookie") ?? "";
383
+ csrfToken = /_csrf=([a-f0-9]+)/.exec(setCookie)?.[1] ?? "";
384
+ });
385
+
386
+ afterAll(() => server.stop());
387
+
388
+ test("POST ?/create invokes the named export with cookies", async () => {
389
+ const res = await fetch(`${base}/form?/create`, {
390
+ method: "POST",
391
+ headers: {
392
+ "Content-Type": "application/x-www-form-urlencoded",
393
+ Cookie: `_csrf=${csrfToken}`,
394
+ "X-Grimoire-Form": "1",
395
+ },
396
+ body: `x=1&_csrf=${csrfToken}`,
397
+ });
398
+ expect(res.status).toBe(400);
399
+ // shape asserted below — typed to satisfy strict unknown-returning json()
400
+ const json = (await res.json()) as {
401
+ fail: boolean;
402
+ data: { hasCookies: boolean; method: string };
403
+ };
404
+ expect(json.fail).toBe(true);
405
+ expect(json.data.hasCookies).toBe(true);
406
+ expect(json.data.method).toBe("POST");
407
+ });
408
+
409
+ test("a plain POST that fails re-renders the page with a form prop", async () => {
410
+ const res = await fetch(`${base}/form?/create`, {
411
+ method: "POST",
412
+ headers: {
413
+ "Content-Type": "application/x-www-form-urlencoded",
414
+ Cookie: `_csrf=${csrfToken}`,
415
+ },
416
+ body: `x=1&_csrf=${csrfToken}`,
417
+ });
418
+ expect(res.status).toBe(400);
419
+ expect(res.headers.get("content-type")).toContain("text/html");
420
+ const html = await res.text();
421
+ expect(html).toContain("<h1>form</h1>");
422
+ expect(html).toContain("form-says:POST");
423
+ // hydration gets the same prop
424
+ expect(html).toMatch(/"form":\{"ok":false[^}]*"method":"POST"/);
425
+ });
426
+
427
+ test("unknown named action returns 404", async () => {
428
+ const res = await fetch(`${base}/form?/nope`, {
429
+ method: "POST",
430
+ headers: {
431
+ "Content-Type": "application/x-www-form-urlencoded",
432
+ Cookie: `_csrf=${csrfToken}`,
433
+ },
434
+ body: `x=1&_csrf=${csrfToken}`,
435
+ });
436
+ expect(res.status).toBe(404);
437
+ });
438
+
439
+ test("GET never runs a named action; it renders the page", async () => {
440
+ const res = await fetch(`${base}/form?/create`);
441
+ expect(res.status).toBe(200);
442
+ expect(res.headers.get("content-type")).toContain("text/html");
443
+ expect(await res.text()).toContain("form");
444
+ });
445
+
446
+ test("a page's scoped CSS is in the server-rendered <head>", async () => {
447
+ const html = await (await fetch(`${base}/styled`)).text();
448
+ const head = html.slice(0, html.indexOf("</head>"));
449
+ const hash = /<h1 class="t (s[0-9a-f]{8})">/.exec(html)?.[1];
450
+ expect(hash).toBeDefined();
451
+ expect(head).toContain(`<style id="sigil-${hash}">`);
452
+ expect(head).toContain(`.t.${hash} { color: red; }`);
453
+ expect(head).toContain(`.u.${hash} { color: blue; }`);
454
+ });
455
+
456
+ test("every POST form gets a CSRF input, GET forms never do", async () => {
457
+ const html = await (await fetch(`${base}/forms`)).text();
458
+ const token = (id: string) =>
459
+ new RegExp(
460
+ `<form[^>]*id="${id}"[^>]*><input type="hidden" name="_csrf"`,
461
+ ).test(html);
462
+ expect(token("a")).toBe(true); // no action attribute
463
+ expect(token("b")).toBe(true);
464
+ expect(token("c")).toBe(false); // GET: the token would land in the URL
465
+ expect(token("d")).toBe(false);
466
+ });
467
+
468
+ test("a GET export in +page.server.ts is not run for page views", async () => {
469
+ const res = await fetch(`${base}/form`, { redirect: "manual" });
470
+ expect(res.status).toBe(200);
471
+ expect(await res.text()).toContain("<h1>form</h1>");
472
+ const head = await fetch(`${base}/form`, { method: "HEAD" });
473
+ expect(head.status).toBe(200);
474
+ });
475
+
476
+ test("streaming pages get CSRF tokens and the cookie too", async () => {
477
+ const res = await fetch(`${base}/slow`);
478
+ const token = /_csrf=([a-f0-9]+)/.exec(
479
+ res.headers.get("set-cookie") ?? "",
480
+ )?.[1];
481
+ expect(token).toBeDefined();
482
+ const html = await res.text();
483
+ for (const id of ["shell", "page"]) {
484
+ expect(html).toContain(
485
+ `<form method="post" id="${id}"><input type="hidden" name="_csrf" value="${token}"`,
486
+ );
487
+ }
488
+ });
489
+
490
+ test("an existing CSRF cookie is kept, so other tabs' forms still work", async () => {
491
+ const res = await fetch(`${base}/forms`, {
492
+ headers: { Cookie: `_csrf=${csrfToken}` },
493
+ });
494
+ expect(res.headers.get("set-cookie")).toContain(`_csrf=${csrfToken}`);
495
+ expect(await res.text()).toContain(`value="${csrfToken}"`);
496
+ // a malformed cookie is replaced
497
+ const bad = await fetch(`${base}/forms`, {
498
+ headers: { Cookie: "_csrf=nope" },
499
+ });
500
+ expect(bad.headers.get("set-cookie")).toMatch(/_csrf=[0-9a-f]{64}/);
501
+ });
502
+
503
+ test("load and the other module hooks are not actions", async () => {
504
+ for (const name of ["load", "canMatch", "csrf"]) {
505
+ const res = await fetch(`${base}/form?/${name}`, {
506
+ method: "POST",
507
+ headers: {
508
+ "Content-Type": "application/x-www-form-urlencoded",
509
+ Cookie: `_csrf=${csrfToken}`,
510
+ },
511
+ body: `x=1&_csrf=${csrfToken}`,
512
+ });
513
+ expect(res.status).toBe(404);
514
+ }
515
+ });
516
+
517
+ test("an action can throw or return a Response and it is the reply", async () => {
518
+ const post = (name: string) =>
519
+ fetch(`${base}/form?/${name}`, {
520
+ method: "POST",
521
+ headers: {
522
+ "Content-Type": "application/x-www-form-urlencoded",
523
+ Cookie: `_csrf=${csrfToken}`,
524
+ },
525
+ body: `x=1&_csrf=${csrfToken}`,
526
+ redirect: "manual",
527
+ });
528
+ const thrown = await post("teapot");
529
+ expect(thrown.status).toBe(418);
530
+ expect(await thrown.text()).toBe("short and stout");
531
+ const returned = await post("raw");
532
+ expect(returned.status).toBe(202);
533
+ expect(await returned.text()).toBe("raw reply");
534
+ });
535
+
536
+ test("POST named action without CSRF token is forbidden", async () => {
537
+ const res = await fetch(`${base}/form?/create`, {
538
+ method: "POST",
539
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
540
+ body: "x=1",
541
+ });
542
+ expect(res.status).toBe(403);
543
+ });
544
+
545
+ test("an enhanced submission gets its outcome as JSON, not a 303", async () => {
546
+ const res = await fetch(`${base}/form`, {
547
+ method: "POST",
548
+ headers: {
549
+ "Content-Type": "application/x-www-form-urlencoded",
550
+ Cookie: `_csrf=${csrfToken}`,
551
+ "X-Grimoire-Form": "1",
552
+ },
553
+ body: `x=1&_csrf=${csrfToken}`,
554
+ redirect: "manual",
555
+ });
556
+ expect(res.status).toBe(200);
557
+ expect(await res.json()).toEqual({
558
+ type: "success",
559
+ location: "/done",
560
+ data: { redirect: "/done" },
561
+ });
562
+ });
563
+
564
+ test("method dispatch without query key is unchanged", async () => {
565
+ const res = await fetch(`${base}/form`, {
566
+ method: "POST",
567
+ headers: {
568
+ "Content-Type": "application/x-www-form-urlencoded",
569
+ Cookie: `_csrf=${csrfToken}`,
570
+ },
571
+ body: `x=1&_csrf=${csrfToken}`,
572
+ redirect: "manual",
573
+ });
574
+ expect(res.status).toBe(303);
575
+ expect(res.headers.get("location")).toBe("/done");
576
+ });
577
+ });
578
+
579
+ describe("Server — error pages", () => {
580
+ let dir: string;
581
+ let server: Awaited<ReturnType<typeof createServer>>;
582
+ const base = "http://localhost:3012";
583
+
584
+ beforeAll(async () => {
585
+ dir = join(tmpdir(), `grimoire-errors-${Date.now()}`);
586
+ await mkdir(join(dir, "boom"), { recursive: true });
587
+ await writeFile(
588
+ join(dir, "+error.tsx"),
589
+ "export default ({ status, message }) => `<h1>oops ${status}: ${message}</h1>`;",
590
+ );
591
+ await writeFile(
592
+ join(dir, "boom", "+page.server.ts"),
593
+ 'export function load() { throw new Error("db password is hunter2"); }',
594
+ );
595
+ await writeFile(
596
+ join(dir, "boom", "+page.tsx"),
597
+ "export default () => 'never';",
598
+ );
599
+ // a root layout with its own server data, a nested error page, and
600
+ // one in a [param] folder
601
+ await writeFile(
602
+ join(dir, "+layout.tsx"),
603
+ 'export default ({ data, children }) => `<main data-site="${data.site}">${children}</main>`;',
604
+ );
605
+ await writeFile(
606
+ join(dir, "+layout.server.ts"),
607
+ 'export function load() { return { site: "meow" }; }',
608
+ );
609
+ await mkdir(join(dir, "shop"), { recursive: true });
610
+ await writeFile(
611
+ join(dir, "shop", "+error.tsx"),
612
+ "export default ({ status }) => `<h1>shop ${status}</h1>`;",
613
+ );
614
+ await mkdir(join(dir, "items", "[id]"), { recursive: true });
615
+ await writeFile(
616
+ join(dir, "items", "[id]", "+error.tsx"),
617
+ "export default ({ status }) => `<h1>item ${status}</h1>`;",
618
+ );
619
+ server = await createServer({ port: 3012, routes: dir, _skipBuild: true });
620
+ });
621
+
622
+ afterAll(() => server.stop());
623
+
624
+ test("an unknown URL renders +error.tsx as a whole document", async () => {
625
+ const res = await fetch(`${base}/nowhere`);
626
+ expect(res.status).toBe(404);
627
+ const html = await res.text();
628
+ expect(html).toContain("<!DOCTYPE html>");
629
+ expect(html).toContain("oops 404: Not Found");
630
+ });
631
+
632
+ test("an unknown URL's error page sits in the layouts, with their data", async () => {
633
+ const html = await (await fetch(`${base}/nowhere/at/all`)).text();
634
+ expect(html).toContain('<main data-site="meow">');
635
+ expect(html).toContain("oops 404: Not Found");
636
+ });
637
+
638
+ test("an unknown URL gets the closest +error.tsx", async () => {
639
+ const res = await fetch(`${base}/shop/no-such-thing`);
640
+ expect(res.status).toBe(404);
641
+ expect(await res.text()).toContain("shop 404");
642
+ });
643
+
644
+ test("a +error.tsx in a [param] folder covers the addresses under it", async () => {
645
+ expect(await (await fetch(`${base}/items/42/missing`)).text()).toContain(
646
+ "item 404",
647
+ );
648
+ // /items itself is above the [id] folder
649
+ expect(await (await fetch(`${base}/items`)).text()).toContain("oops 404");
650
+ });
651
+
652
+ test("an unexpected error renders +error.tsx with a generic message", async () => {
653
+ const res = await fetch(`${base}/boom`);
654
+ expect(res.status).toBe(500);
655
+ const html = await res.text();
656
+ expect(html).toContain("oops 500: Internal Server Error");
657
+ expect(html).not.toContain("hunter2");
658
+ });
659
+ });