@sigil-dev/grimoire 0.9.21 → 0.9.23

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 (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +22 -10
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +871 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -105
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -749
  28. package/src/rendering/preload.ts +102 -101
  29. package/src/rendering/ssrPlugin.ts +1 -1
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -206
  35. package/src/server/asset-cache.ts +57 -57
  36. package/src/server/build.ts +262 -262
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -44
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +211 -80
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -27
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -132
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -101
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +1 -1
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +799 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +381 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +808 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +1 -1
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -1,619 +1,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("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 POST() {",
323
- ' return { redirect: "/done" };',
324
- "}",
325
- "export function GET() {",
326
- ' return { redirect: "/ran-get" };',
327
- "}",
328
- ].join("\n"),
329
- );
330
-
331
- // a page with a scoped style block (tag split: this file's own
332
- // preload strips literal style blocks from sources it loads)
333
- const tag = (name: string) => `<${name}>`;
334
- await mkdir(join(tmpDir, "styled"), { recursive: true });
335
- await writeFile(
336
- join(tmpDir, "styled", "+page.tsx"),
337
- `export default () => <h1 class="t">styled</h1>;\n${tag("style")}\n.t { color: red; }\n.u { color: blue; }\n${tag("/style")}\n`,
338
- );
339
- await mkdir(join(tmpDir, "forms"), { recursive: true });
340
- await writeFile(
341
- join(tmpDir, "forms", "+page.tsx"),
342
- `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>';`,
343
- );
344
- // a streaming page: the loading shell goes out before the page renders
345
- await mkdir(join(tmpDir, "slow"), { recursive: true });
346
- await writeFile(
347
- join(tmpDir, "slow", "+page.tsx"),
348
- [
349
- `export const loading = () => '<form method="post" id="shell"></form>';`,
350
- `export default () => '<form method="post" id="page"></form>';`,
351
- ].join("\n"),
352
- );
353
-
354
- server = await createServer({
355
- port: 3006,
356
- routes: tmpDir,
357
- _skipBuild: true,
358
- });
359
- // SSR render sets the _csrf cookie
360
- const res = await fetch(`${base}/form`);
361
- const setCookie = res.headers.get("set-cookie") ?? "";
362
- csrfToken = /_csrf=([a-f0-9]+)/.exec(setCookie)?.[1] ?? "";
363
- });
364
-
365
- afterAll(() => server.stop());
366
-
367
- test("POST ?/create invokes the named export with cookies", async () => {
368
- const res = await fetch(`${base}/form?/create`, {
369
- method: "POST",
370
- headers: {
371
- "Content-Type": "application/x-www-form-urlencoded",
372
- Cookie: `_csrf=${csrfToken}`,
373
- "X-Grimoire-Form": "1",
374
- },
375
- body: `x=1&_csrf=${csrfToken}`,
376
- });
377
- expect(res.status).toBe(400);
378
- // shape asserted below — typed to satisfy strict unknown-returning json()
379
- const json = (await res.json()) as {
380
- fail: boolean;
381
- data: { hasCookies: boolean; method: string };
382
- };
383
- expect(json.fail).toBe(true);
384
- expect(json.data.hasCookies).toBe(true);
385
- expect(json.data.method).toBe("POST");
386
- });
387
-
388
- test("a plain POST that fails re-renders the page with a form prop", 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
- },
395
- body: `x=1&_csrf=${csrfToken}`,
396
- });
397
- expect(res.status).toBe(400);
398
- expect(res.headers.get("content-type")).toContain("text/html");
399
- const html = await res.text();
400
- expect(html).toContain("<h1>form</h1>");
401
- expect(html).toContain("form-says:POST");
402
- // hydration gets the same prop
403
- expect(html).toMatch(/"form":\{"ok":false[^}]*"method":"POST"/);
404
- });
405
-
406
- test("unknown named action returns 404", async () => {
407
- const res = await fetch(`${base}/form?/nope`, {
408
- method: "POST",
409
- headers: {
410
- "Content-Type": "application/x-www-form-urlencoded",
411
- Cookie: `_csrf=${csrfToken}`,
412
- },
413
- body: `x=1&_csrf=${csrfToken}`,
414
- });
415
- expect(res.status).toBe(404);
416
- });
417
-
418
- test("GET never runs a named action; it renders the page", async () => {
419
- const res = await fetch(`${base}/form?/create`);
420
- expect(res.status).toBe(200);
421
- expect(res.headers.get("content-type")).toContain("text/html");
422
- expect(await res.text()).toContain("form");
423
- });
424
-
425
- test("a page's scoped CSS is in the server-rendered <head>", async () => {
426
- const html = await (await fetch(`${base}/styled`)).text();
427
- const head = html.slice(0, html.indexOf("</head>"));
428
- const hash = /<h1 class="t (s[0-9a-f]{8})">/.exec(html)?.[1];
429
- expect(hash).toBeDefined();
430
- expect(head).toContain(`<style id="sigil-${hash}">`);
431
- expect(head).toContain(`.t.${hash} { color: red; }`);
432
- expect(head).toContain(`.u.${hash} { color: blue; }`);
433
- });
434
-
435
- test("every POST form gets a CSRF input, GET forms never do", async () => {
436
- const html = await (await fetch(`${base}/forms`)).text();
437
- const token = (id: string) =>
438
- new RegExp(
439
- `<form[^>]*id="${id}"[^>]*><input type="hidden" name="_csrf"`,
440
- ).test(html);
441
- expect(token("a")).toBe(true); // no action attribute
442
- expect(token("b")).toBe(true);
443
- expect(token("c")).toBe(false); // GET: the token would land in the URL
444
- expect(token("d")).toBe(false);
445
- });
446
-
447
- test("a GET export in +page.server.ts is not run for page views", async () => {
448
- const res = await fetch(`${base}/form`, { redirect: "manual" });
449
- expect(res.status).toBe(200);
450
- expect(await res.text()).toContain("<h1>form</h1>");
451
- const head = await fetch(`${base}/form`, { method: "HEAD" });
452
- expect(head.status).toBe(200);
453
- });
454
-
455
- test("streaming pages get CSRF tokens and the cookie too", async () => {
456
- const res = await fetch(`${base}/slow`);
457
- const token = /_csrf=([a-f0-9]+)/.exec(
458
- res.headers.get("set-cookie") ?? "",
459
- )?.[1];
460
- expect(token).toBeDefined();
461
- const html = await res.text();
462
- for (const id of ["shell", "page"]) {
463
- expect(html).toContain(
464
- `<form method="post" id="${id}"><input type="hidden" name="_csrf" value="${token}"`,
465
- );
466
- }
467
- });
468
-
469
- test("an existing CSRF cookie is kept, so other tabs' forms still work", async () => {
470
- const res = await fetch(`${base}/forms`, {
471
- headers: { Cookie: `_csrf=${csrfToken}` },
472
- });
473
- expect(res.headers.get("set-cookie")).toContain(`_csrf=${csrfToken}`);
474
- expect(await res.text()).toContain(`value="${csrfToken}"`);
475
- // a malformed cookie is replaced
476
- const bad = await fetch(`${base}/forms`, {
477
- headers: { Cookie: "_csrf=nope" },
478
- });
479
- expect(bad.headers.get("set-cookie")).toMatch(/_csrf=[0-9a-f]{64}/);
480
- });
481
-
482
- test("load and the other module hooks are not actions", async () => {
483
- for (const name of ["load", "canMatch", "csrf"]) {
484
- const res = await fetch(`${base}/form?/${name}`, {
485
- method: "POST",
486
- headers: {
487
- "Content-Type": "application/x-www-form-urlencoded",
488
- Cookie: `_csrf=${csrfToken}`,
489
- },
490
- body: `x=1&_csrf=${csrfToken}`,
491
- });
492
- expect(res.status).toBe(404);
493
- }
494
- });
495
-
496
- test("POST named action without CSRF token is forbidden", async () => {
497
- const res = await fetch(`${base}/form?/create`, {
498
- method: "POST",
499
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
500
- body: "x=1",
501
- });
502
- expect(res.status).toBe(403);
503
- });
504
-
505
- test("an enhanced submission gets its outcome as JSON, not a 303", async () => {
506
- const res = await fetch(`${base}/form`, {
507
- method: "POST",
508
- headers: {
509
- "Content-Type": "application/x-www-form-urlencoded",
510
- Cookie: `_csrf=${csrfToken}`,
511
- "X-Grimoire-Form": "1",
512
- },
513
- body: `x=1&_csrf=${csrfToken}`,
514
- redirect: "manual",
515
- });
516
- expect(res.status).toBe(200);
517
- expect(await res.json()).toEqual({
518
- type: "success",
519
- location: "/done",
520
- data: { redirect: "/done" },
521
- });
522
- });
523
-
524
- test("method dispatch without query key is unchanged", async () => {
525
- const res = await fetch(`${base}/form`, {
526
- method: "POST",
527
- headers: {
528
- "Content-Type": "application/x-www-form-urlencoded",
529
- Cookie: `_csrf=${csrfToken}`,
530
- },
531
- body: `x=1&_csrf=${csrfToken}`,
532
- redirect: "manual",
533
- });
534
- expect(res.status).toBe(303);
535
- expect(res.headers.get("location")).toBe("/done");
536
- });
537
- });
538
-
539
- describe("Server — error pages", () => {
540
- let dir: string;
541
- let server: Awaited<ReturnType<typeof createServer>>;
542
- const base = "http://localhost:3012";
543
-
544
- beforeAll(async () => {
545
- dir = join(tmpdir(), `grimoire-errors-${Date.now()}`);
546
- await mkdir(join(dir, "boom"), { recursive: true });
547
- await writeFile(
548
- join(dir, "+error.tsx"),
549
- "export default ({ status, message }) => `<h1>oops ${status}: ${message}</h1>`;",
550
- );
551
- await writeFile(
552
- join(dir, "boom", "+page.server.ts"),
553
- 'export function load() { throw new Error("db password is hunter2"); }',
554
- );
555
- await writeFile(
556
- join(dir, "boom", "+page.tsx"),
557
- "export default () => 'never';",
558
- );
559
- // a root layout with its own server data, a nested error page, and
560
- // one in a [param] folder
561
- await writeFile(
562
- join(dir, "+layout.tsx"),
563
- 'export default ({ data, children }) => `<main data-site="${data.site}">${children}</main>`;',
564
- );
565
- await writeFile(
566
- join(dir, "+layout.server.ts"),
567
- 'export function load() { return { site: "meow" }; }',
568
- );
569
- await mkdir(join(dir, "shop"), { recursive: true });
570
- await writeFile(
571
- join(dir, "shop", "+error.tsx"),
572
- "export default ({ status }) => `<h1>shop ${status}</h1>`;",
573
- );
574
- await mkdir(join(dir, "items", "[id]"), { recursive: true });
575
- await writeFile(
576
- join(dir, "items", "[id]", "+error.tsx"),
577
- "export default ({ status }) => `<h1>item ${status}</h1>`;",
578
- );
579
- server = await createServer({ port: 3012, routes: dir, _skipBuild: true });
580
- });
581
-
582
- afterAll(() => server.stop());
583
-
584
- test("an unknown URL renders +error.tsx as a whole document", async () => {
585
- const res = await fetch(`${base}/nowhere`);
586
- expect(res.status).toBe(404);
587
- const html = await res.text();
588
- expect(html).toContain("<!DOCTYPE html>");
589
- expect(html).toContain("oops 404: Not Found");
590
- });
591
-
592
- test("an unknown URL's error page sits in the layouts, with their data", async () => {
593
- const html = await (await fetch(`${base}/nowhere/at/all`)).text();
594
- expect(html).toContain('<main data-site="meow">');
595
- expect(html).toContain("oops 404: Not Found");
596
- });
597
-
598
- test("an unknown URL gets the closest +error.tsx", async () => {
599
- const res = await fetch(`${base}/shop/no-such-thing`);
600
- expect(res.status).toBe(404);
601
- expect(await res.text()).toContain("shop 404");
602
- });
603
-
604
- test("a +error.tsx in a [param] folder covers the addresses under it", async () => {
605
- expect(await (await fetch(`${base}/items/42/missing`)).text()).toContain(
606
- "item 404",
607
- );
608
- // /items itself is above the [id] folder
609
- expect(await (await fetch(`${base}/items`)).text()).toContain("oops 404");
610
- });
611
-
612
- test("an unexpected error renders +error.tsx with a generic message", async () => {
613
- const res = await fetch(`${base}/boom`);
614
- expect(res.status).toBe(500);
615
- const html = await res.text();
616
- expect(html).toContain("oops 500: Internal Server Error");
617
- expect(html).not.toContain("hunter2");
618
- });
619
- });
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
+ });