@sigil-dev/grimoire 0.9.11 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,8 @@ import { crawlFrom } from "../dev/scan.ts";
11
11
  import { startWatcher } from "../dev/watcher.ts";
12
12
  import { envModuleSource } from "../env/modules";
13
13
  import { log } from "../logger/instance.ts";
14
+ import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
15
+ import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
14
16
  import { renderErrorPage, renderRoute } from "../rendering";
15
17
  import { registerSSRPlugin } from "../rendering/ssrPlugin";
16
18
  import { matchRoute } from "../routing/router";
@@ -58,6 +60,70 @@ function watchRoots(projectRoot: string, routesDir: string): string[] {
58
60
  roots.push(routesDir);
59
61
  return roots;
60
62
  }
63
+
64
+ /**
65
+ * Serve a file from public/, or return null when the path is not one.
66
+ *
67
+ * `immutable` is sent only for a URL that changes with its content, and
68
+ * `must-revalidate` with an ETag for everything else. That distinction is
69
+ * the whole point: telling a browser to cache a stylesheet for a year at a
70
+ * URL that never changes means a deploy which edits the CSS is invisible to
71
+ * anyone already holding it — the new HTML loads, and the old stylesheet
72
+ * stays. Unconditional `immutable` was the bug here, and it was worse than
73
+ * no caching at all, because it looked like it was working.
74
+ *
75
+ * Callers must not put user input in the pathname: this joins it onto
76
+ * public/ directly.
77
+ */
78
+ async function servePublicAsset(
79
+ pathname: string,
80
+ search: string,
81
+ ifNoneMatch: string | null,
82
+ ): Promise<Response | null> {
83
+ // Reject traversal before touching the filesystem.
84
+ if (pathname.includes("..") || pathname.includes("\0")) return null;
85
+ const file = Bun.file(join(process.cwd(), "public", pathname));
86
+ if (!(await file.exists())) return null;
87
+
88
+ const headers: Record<string, string> = {};
89
+ // Bun sets Content-Type from the extension, but be explicit for the
90
+ // cases where a wrong guess is expensive: a stylesheet served as
91
+ // text/plain is refused outright by the browser.
92
+ const type = file.type;
93
+ if (type) headers["Content-Type"] = type;
94
+
95
+ const policy = cacheControlFor(pathname, search);
96
+ headers["Cache-Control"] = CACHE_CONTROL[policy];
97
+ if (policy === "revalidate") {
98
+ // The hash of the content, so a revalidation can be answered with
99
+ // 304 instead of the whole file.
100
+ const hasher = new Bun.CryptoHasher("sha256");
101
+ hasher.update(await file.arrayBuffer());
102
+ const etag = `"${hasher.digest("hex").slice(0, 16)}"`;
103
+ headers["ETag"] = etag;
104
+
105
+ // Compared here rather than left to Bun: a Bun.file body does not
106
+ // honour If-None-Match on its own, so without this the conditional
107
+ // request would get a 200 and re-download the whole file, and
108
+ // max-age=0 would cost a full transfer on every single page load.
109
+ //
110
+ // Weak comparison, and a match on `*`: both are what the HTTP spec
111
+ // asks for here. `W/` is stripped because these are strong ETags and
112
+ // a client may legitimately send the weak form of one.
113
+ const current = ifNoneMatch
114
+ ?.split(",")
115
+ .map((v) => v.trim())
116
+ .some((v) => v === "*" || v.replace(/^W\//, "") === etag);
117
+ if (current) {
118
+ return new Response(null, { status: 304, headers });
119
+ }
120
+ }
121
+ // Content-Length and Last-Modified come from the File; let Bun set them.
122
+ if (file.lastModified) {
123
+ headers["Last-Modified"] = new Date(file.lastModified).toUTCString();
124
+ }
125
+ return new Response(file, { headers });
126
+ }
61
127
  /**
62
128
  * Try to load hooks.server.ts from the project root.
63
129
  */
@@ -100,7 +166,7 @@ export async function createServer(config: GrimoireConfig = {}) {
100
166
  let finalConfig = config;
101
167
  const earlyPlugins = config.plugins ?? [];
102
168
  for (const plugin of earlyPlugins) {
103
- finalConfig = plugin.config?.(finalConfig) ?? finalConfig;
169
+ finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
104
170
  }
105
171
 
106
172
  const {
@@ -248,536 +314,558 @@ export async function createServer(config: GrimoireConfig = {}) {
248
314
  // Run init hook if present
249
315
  await hooksInit?.();
250
316
 
251
- const server = Bun.serve({
252
- port,
253
- hostname: host,
254
- fetch: async (req) => {
255
- const rawLocals = req.headers.get("X-Grimoire-Locals");
256
- const locals: App.Locals = rawLocals
257
- ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
258
- : {};
259
- const url = new URL(req.url);
260
-
261
- if (dev && url.pathname === "/__grimoire__/hmr") {
262
- //@ts-expect-error holy shut up
263
- if (server.upgrade(req, { data: { __hmrClient: true } })) {
264
- return undefined as unknown as Response;
265
- }
266
- return new Response("Upgrade Required", { status: 426 });
267
- }
268
- if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
269
- return new Response(HMR_CLIENT_SOURCE, {
270
- headers: { "Content-Type": "application/javascript" },
271
- });
317
+ // onRouteRender forces the whole response to be buffered into a string,
318
+ // which silently disables streaming for every route a plugin touches. That
319
+ // is a real cost and an invisible one, so say it once at boot rather than
320
+ // letting someone discover it as "streaming stopped working".
321
+ for (const p of plugins) {
322
+ if (p.onRouteRender) {
323
+ logger.warn(
324
+ `plugin "${p.name}" implements onRouteRender, which buffers the full HTML response and disables streaming (including the \`loading\` shell) on every route it touches. If you only need to change headers, use onRequest instead.`,
325
+ );
326
+ }
327
+ }
328
+
329
+ async function handleRequest(req: Request) {
330
+ const rawLocals = req.headers.get("X-Grimoire-Locals");
331
+ const locals: App.Locals = rawLocals
332
+ ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
333
+ : {};
334
+ const url = new URL(req.url);
335
+
336
+ if (dev && url.pathname === "/__grimoire__/hmr") {
337
+ //@ts-expect-error holy shut up
338
+ if (server.upgrade(req, { data: { __hmrClient: true } })) {
339
+ return undefined as unknown as Response;
272
340
  }
273
- if (dev && url.pathname === "/__grimoire__/open") {
274
- const file = url.searchParams.get("file") ?? "";
275
- const line = url.searchParams.get("line") ?? "1";
276
- const col = url.searchParams.get("col") ?? "1";
277
- const editor = finalConfig.devEditor ?? "code";
278
- //@ts-expect-error Bun spawn has werird types just shut up
279
- Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
280
- return new Response(null, { status: 204 });
341
+ return new Response("Upgrade Required", { status: 426 });
342
+ }
343
+ if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
344
+ return new Response(HMR_CLIENT_SOURCE, {
345
+ headers: { "Content-Type": "application/javascript" },
346
+ });
347
+ }
348
+ if (dev && url.pathname === "/__grimoire__/open") {
349
+ const file = url.searchParams.get("file") ?? "";
350
+ const line = url.searchParams.get("line") ?? "1";
351
+ const col = url.searchParams.get("col") ?? "1";
352
+ const editor = finalConfig.devEditor ?? "code";
353
+ //@ts-expect-error Bun spawn has werird types just shut up
354
+ Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
355
+ return new Response(null, { status: 204 });
356
+ }
357
+ if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
358
+ const depName = decodeURIComponent(
359
+ url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
360
+ );
361
+
362
+ // grimoire shim
363
+ if (depName.includes("@sigil-dev__grimoire")) {
364
+ return Response.redirect("/__grimoire__/grimoire-client.js", 302);
281
365
  }
282
- if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
283
- const depName = decodeURIComponent(
284
- url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
285
- );
286
366
 
287
- // grimoire shim
288
- if (depName.includes("@sigil-dev__grimoire")) {
289
- return Response.redirect("/__grimoire__/grimoire-client.js", 302);
290
- }
367
+ // convert URL-safe name back to package name
368
+ // @codex__shared → @codex/shared
369
+ const pkgName = depName.startsWith("@")
370
+ ? depName.replace("__", "/")
371
+ : depName;
291
372
 
292
- // convert URL-safe name back to package name
293
- // @codex__shared → @codex/shared
294
- const pkgName = depName.startsWith("@")
295
- ? depName.replace("__", "/")
296
- : depName;
297
-
298
- const depsDir = join(process.cwd(), ".grimoire/deps");
299
- mkdirSync(depsDir, { recursive: true });
300
- const outFile = join(depsDir, `${depName}.js`);
301
-
302
- if (!(await Bun.file(outFile).exists())) {
303
- logger.debug("bundling dep:", pkgName);
304
- try {
305
- const entry = Bun.resolveSync(pkgName, process.cwd());
306
- const result = await Bun.build({
307
- entrypoints: [entry],
308
- outdir: depsDir,
309
- naming: `${depName}.js`,
310
- target: "browser",
311
- format: "esm",
312
- minify: false,
313
- external: ["@sigil-dev/runtime"],
314
- });
315
- if (!result.success) {
316
- logger.error("dep bundle failed:", pkgName, result.logs);
317
- return new Response(
318
- `throw new Error("failed to bundle dep: ${pkgName}")`,
319
- { headers: { "Content-Type": "application/javascript" } },
320
- );
321
- }
322
- logger.debug("bundled dep:", pkgName);
323
- } catch (e: any) {
373
+ const depsDir = join(process.cwd(), ".grimoire/deps");
374
+ mkdirSync(depsDir, { recursive: true });
375
+ const outFile = join(depsDir, `${depName}.js`);
376
+
377
+ if (!(await Bun.file(outFile).exists())) {
378
+ logger.debug("bundling dep:", pkgName);
379
+ try {
380
+ const entry = Bun.resolveSync(pkgName, process.cwd());
381
+ const result = await Bun.build({
382
+ entrypoints: [entry],
383
+ outdir: depsDir,
384
+ naming: `${depName}.js`,
385
+ target: "browser",
386
+ format: "esm",
387
+ minify: false,
388
+ external: ["@sigil-dev/runtime"],
389
+ });
390
+ if (!result.success) {
391
+ logger.error("dep bundle failed:", pkgName, result.logs);
324
392
  return new Response(
325
- `throw new Error("dep not found: ${pkgName}: ${e.message}")`,
393
+ `throw new Error("failed to bundle dep: ${pkgName}")`,
326
394
  { headers: { "Content-Type": "application/javascript" } },
327
395
  );
328
396
  }
397
+ logger.debug("bundled dep:", pkgName);
398
+ } catch (e: any) {
399
+ return new Response(
400
+ `throw new Error("dep not found: ${pkgName}: ${e.message}")`,
401
+ { headers: { "Content-Type": "application/javascript" } },
402
+ );
329
403
  }
404
+ }
330
405
 
331
- return new Response(Bun.file(outFile), {
332
- headers: {
333
- "Content-Type": "application/javascript",
334
- "Cache-Control": "no-store",
335
- },
336
- });
406
+ return new Response(Bun.file(outFile), {
407
+ headers: {
408
+ "Content-Type": "application/javascript",
409
+ "Cache-Control": "no-store",
410
+ },
411
+ });
412
+ }
413
+
414
+ if (dev && url.pathname.startsWith("/__grimoire__/env/")) {
415
+ const specifier = `$env/${url.pathname.slice("/__grimoire__/env/".length).replace(/\.js$/, "")}`;
416
+ let js: string;
417
+ try {
418
+ js = envModuleSource(specifier, "browser");
419
+ } catch (e: unknown) {
420
+ const message = e instanceof Error ? e.message : String(e);
421
+ js = `throw new Error(${JSON.stringify(message)})`;
337
422
  }
423
+ return new Response(js, {
424
+ headers: {
425
+ "Content-Type": "application/javascript",
426
+ "Cache-Control": "no-store",
427
+ },
428
+ });
429
+ }
338
430
 
339
- if (dev && url.pathname.startsWith("/__grimoire__/env/")) {
340
- const specifier = `$env/${url.pathname.slice("/__grimoire__/env/".length).replace(/\.js$/, "")}`;
341
- let js: string;
342
- try {
343
- js = envModuleSource(specifier, "browser");
344
- } catch (e: unknown) {
345
- const message = e instanceof Error ? e.message : String(e);
346
- js = `throw new Error(${JSON.stringify(message)})`;
347
- }
431
+ if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
432
+ const clientPath = decodeURIComponent(
433
+ url.pathname.slice("/__grimoire__/m/".length),
434
+ );
435
+ const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
436
+ try {
437
+ // compiled at the module's current graph version, which is what
438
+ // the `?v=` in the URL was derived from
439
+ const { js } = await getDevModule(absPath, {
440
+ projectRoot: process.cwd(),
441
+ aliases,
442
+ graph,
443
+ });
348
444
  return new Response(js, {
349
445
  headers: {
350
446
  "Content-Type": "application/javascript",
351
447
  "Cache-Control": "no-store",
352
448
  },
353
449
  });
450
+ } catch (e: unknown) {
451
+ const message = e instanceof Error ? e.message : String(e);
452
+ return new Response(`throw new Error(${JSON.stringify(message)})`, {
453
+ headers: { "Content-Type": "application/javascript" },
454
+ });
354
455
  }
456
+ }
355
457
 
356
- if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
357
- const clientPath = decodeURIComponent(
358
- url.pathname.slice("/__grimoire__/m/".length),
359
- );
360
- const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
361
- try {
362
- // compiled at the module's current graph version, which is what
363
- // the `?v=` in the URL was derived from
364
- const { js } = await getDevModule(absPath, {
365
- projectRoot: process.cwd(),
366
- aliases,
367
- graph,
368
- });
369
- return new Response(js, {
370
- headers: {
371
- "Content-Type": "application/javascript",
372
- "Cache-Control": "no-store",
373
- },
374
- });
375
- } catch (e: unknown) {
376
- const message = e instanceof Error ? e.message : String(e);
377
- return new Response(`throw new Error(${JSON.stringify(message)})`, {
378
- headers: { "Content-Type": "application/javascript" },
379
- });
380
- }
458
+ // Static files are served BEFORE the plugin pipeline. A CSS file or
459
+ // an image has nothing to do with a plugin's onRequest hook, and
460
+ // running them through it costs a hook round-trip plus a stat on
461
+ // every asset request.
462
+ //
463
+ // Caching rule, decided per asset by servePublicAsset: the document
464
+ // is never cached, a content-addressed URL is immutable, and
465
+ // anything else revalidates against an ETag.
466
+ const staticAsset = await servePublicAsset(
467
+ url.pathname,
468
+ url.search,
469
+ req.headers.get("if-none-match"),
470
+ );
471
+ if (staticAsset) return staticAsset;
472
+
473
+ return runRequestHooks(plugins, req, async () => {
474
+
475
+ const HTTP_METHODS = [
476
+ "GET",
477
+ "POST",
478
+ "PUT",
479
+ "PATCH",
480
+ "DELETE",
481
+ "HEAD",
482
+ "OPTIONS",
483
+ ] as const;
484
+
485
+ // Build event BEFORE matching — handle() runs pre-match like SvelteKit
486
+ const cookieHeader = req.headers.get("cookie") ?? "";
487
+ const cookies = createCookies(cookieHeader);
488
+ const setHeadersMap: Record<string, string> = {};
489
+
490
+ const event: RequestEvent = {
491
+ request: req,
492
+ url,
493
+ params: {},
494
+ locals,
495
+ cookies,
496
+ route: { id: "" },
497
+ fetch: globalThis.fetch,
498
+ setHeaders: (headers) => Object.assign(setHeadersMap, headers),
499
+ };
500
+
501
+ if (hooksHandleFetch) {
502
+ event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
503
+ const r = new Request(reqInfo, init);
504
+ return Promise.resolve(
505
+ hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
506
+ );
507
+ };
381
508
  }
382
-
383
- return runRequestHooks(plugins, req, async () => {
384
- const publicFile = Bun.file(`${process.cwd()}/public${url.pathname}`);
385
- if (await publicFile.exists()) {
386
- return new Response(publicFile);
509
+ const patchedFetch: typeof fetch = (input, init) => {
510
+ const resolved =
511
+ typeof input === "string" && input.startsWith("/")
512
+ ? new URL(input, url.origin).toString()
513
+ : input;
514
+ return globalThis.fetch(resolved as any, init);
515
+ };
516
+ const resolve: ResolveFunction = async (evt) => {
517
+ // matching happens here — after handle() has run
518
+ let matched = matchRoute(tree, evt.url, paramMatcherFns);
519
+ if (!matched) {
520
+ // the nearest +error.tsx, as a whole document like any other
521
+ // error page (it was a bare fragment with no <head>)
522
+ return (
523
+ (await renderErrorPage(
524
+ tree.errors,
525
+ evt.url.pathname,
526
+ 404,
527
+ "Not Found",
528
+ null,
529
+ loader,
530
+ { nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
531
+ )) ?? new Response("Not Found", { status: 404 })
532
+ );
387
533
  }
388
534
 
389
- const HTTP_METHODS = [
390
- "GET",
391
- "POST",
392
- "PUT",
393
- "PATCH",
394
- "DELETE",
395
- "HEAD",
396
- "OPTIONS",
397
- ] as const;
398
-
399
- // Build event BEFORE matching — handle() runs pre-match like SvelteKit
400
- const cookieHeader = req.headers.get("cookie") ?? "";
401
- const cookies = createCookies(cookieHeader);
402
- const setHeadersMap: Record<string, string> = {};
403
-
404
- const event: RequestEvent = {
405
- request: req,
406
- url,
407
- params: {},
408
- locals,
409
- cookies,
410
- route: { id: "" },
411
- fetch: globalThis.fetch,
412
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
413
- };
535
+ // patch event with match results so handle() epilogue can read them
536
+ evt.params = matched.params;
537
+ evt.route = { id: matched.route.path };
414
538
 
415
- if (hooksHandleFetch) {
416
- event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
417
- const r = new Request(reqInfo, init);
418
- return Promise.resolve(
419
- hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
420
- );
421
- };
422
- }
423
- const patchedFetch: typeof fetch = (input, init) => {
424
- const resolved =
425
- typeof input === "string" && input.startsWith("/")
426
- ? new URL(input, url.origin).toString()
427
- : input;
428
- return globalThis.fetch(resolved as any, init);
429
- };
430
- const resolve: ResolveFunction = async (evt) => {
431
- // matching happens here — after handle() has run
432
- let matched = matchRoute(tree, evt.url, paramMatcherFns);
433
- if (!matched) {
434
- // the nearest +error.tsx, as a whole document like any other
435
- // error page (it was a bare fragment with no <head>)
436
- return (
437
- (await renderErrorPage(
438
- tree.errors,
439
- evt.url.pathname,
440
- 404,
441
- "Not Found",
442
- null,
443
- loader,
444
- { nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
445
- )) ?? new Response("Not Found", { status: 404 })
446
- );
447
- }
539
+ // API routes (+server.ts)
540
+ if (matched.route.type === "server") {
541
+ const mod = await loader(matched.route.filePath);
448
542
 
449
- // patch event with match results so handle() epilogue can read them
450
- evt.params = matched.params;
451
- evt.route = { id: matched.route.path };
452
-
453
- // API routes (+server.ts)
454
- if (matched.route.type === "server") {
455
- const mod = await loader(matched.route.filePath);
456
-
457
- const isWsUpgrade =
458
- evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
459
- if (isWsUpgrade && mod.websocket) {
460
- let extraData: Record<string, unknown> = {};
461
- if (mod.upgrade) {
462
- try {
463
- const result = await mod.upgrade({
464
- request: evt.request,
465
- params: matched.params,
466
- url: evt.url,
467
- locals: evt.locals,
468
- });
469
- if (result && typeof result === "object") extraData = result;
470
- } catch {
471
- return new Response("Upgrade Required", { status: 426 });
472
- }
473
- }
474
- const wsData: _WsInternalData = {
475
- params: matched.params,
476
- __handler: mod.websocket,
477
- ...extraData,
478
- };
479
- //@ts-expect-error i dont know what you are talking about please
480
- if (server.upgrade(req, { data: wsData })) {
481
- return undefined as unknown as Response;
543
+ const isWsUpgrade =
544
+ evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
545
+ if (isWsUpgrade && mod.websocket) {
546
+ let extraData: Record<string, unknown> = {};
547
+ if (mod.upgrade) {
548
+ try {
549
+ const result = await mod.upgrade({
550
+ request: evt.request,
551
+ params: matched.params,
552
+ url: evt.url,
553
+ locals: evt.locals,
554
+ });
555
+ if (result && typeof result === "object") extraData = result;
556
+ } catch {
557
+ return new Response("Upgrade Required", { status: 426 });
482
558
  }
483
- return new Response("Upgrade Required", { status: 426 });
484
559
  }
560
+ const wsData: _WsInternalData = {
561
+ params: matched.params,
562
+ __handler: mod.websocket,
563
+ ...extraData,
564
+ };
565
+ //@ts-expect-error i dont know what you are talking about please
566
+ if (server.upgrade(req, { data: wsData })) {
567
+ return undefined as unknown as Response;
568
+ }
569
+ return new Response("Upgrade Required", { status: 426 });
570
+ }
571
+
572
+ const handler = mod[evt.request.method];
573
+ if (handler) {
574
+ return handler({
575
+ request: evt.request,
576
+ params: matched.params,
577
+ url: evt.url,
578
+ locals: evt.locals,
579
+ fetch: patchedFetch,
580
+ cookies,
581
+ setHeaders: (headers) => Object.assign(setHeadersMap, headers),
582
+ });
583
+ }
584
+ // no handler for this method: a page at the same URL (say a
585
+ // chat page next to its WebSocket endpoint) takes the request
586
+ const page = matchRoute(
587
+ { ...tree, servers: [] },
588
+ evt.url,
589
+ paramMatcherFns,
590
+ );
591
+ if (!page) {
592
+ return new Response("Method Not Allowed", { status: 405 });
593
+ }
594
+ matched = page;
595
+ evt.params = page.params;
596
+ evt.route = { id: page.route.path };
597
+ }
598
+
599
+ // form actions (+page.server.ts)
600
+ if (
601
+ matched.pageServer &&
602
+ HTTP_METHODS.includes(evt.request.method as any)
603
+ ) {
604
+ const mod = await loader(matched.pageServer.filePath);
605
+
606
+ // named actions: ?/create dispatches export `create`. Only for
607
+ // non-GET requests: a GET must never run an action, or any link
608
+ // or <img> on another site could trigger one with the visitor's
609
+ // cookies and no CSRF check (GET skips it)
610
+ const isRead =
611
+ evt.request.method === "GET" || evt.request.method === "HEAD";
612
+ const actionName = isRead
613
+ ? undefined
614
+ : [...evt.url.searchParams.keys()]
615
+ .find((k) => k.startsWith("/"))
616
+ ?.slice(1);
617
+ // every other function export is callable by name, but the
618
+ // module's own hooks are not actions
619
+ const reserved =
620
+ actionName !== undefined && RESERVED_EXPORTS.has(actionName);
621
+ // reads render the page; an exported GET is not an action either
622
+ const handler =
623
+ reserved || isRead
624
+ ? undefined
625
+ : actionName
626
+ ? mod[actionName]
627
+ : mod[evt.request.method];
628
+ if (actionName && typeof handler !== "function") {
629
+ return new Response("Not Found", { status: 404 });
630
+ }
485
631
 
486
- const handler = mod[evt.request.method];
487
- if (handler) {
488
- return handler({
632
+ if (mod.csrf !== false && !isRead) {
633
+ const cookieToken = cookies.get("_csrf");
634
+ const formData = await evt.request
635
+ .clone()
636
+ .formData()
637
+ .catch(() => null);
638
+ const bodyToken = formData?.get("_csrf");
639
+ if (!cookieToken || cookieToken !== String(bodyToken)) {
640
+ return new Response("Forbidden", { status: 403 });
641
+ }
642
+ }
643
+ // enhance() submits with fetch, which follows a 303 on its own
644
+ // and can't read where it went; it asks for the outcome as JSON
645
+ // instead and navigates itself
646
+ const enhanced = evt.request.headers.get("x-grimoire-form") === "1";
647
+ if (handler) {
648
+ let result: any;
649
+ try {
650
+ result = await handler({
489
651
  request: evt.request,
490
652
  params: matched.params,
491
653
  url: evt.url,
492
654
  locals: evt.locals,
493
655
  fetch: patchedFetch,
494
656
  cookies,
495
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
496
657
  });
497
- }
498
- // no handler for this method: a page at the same URL (say a
499
- // chat page next to its WebSocket endpoint) takes the request
500
- const page = matchRoute(
501
- { ...tree, servers: [] },
502
- evt.url,
503
- paramMatcherFns,
504
- );
505
- if (!page) {
506
- return new Response("Method Not Allowed", { status: 405 });
507
- }
508
- matched = page;
509
- evt.params = page.params;
510
- evt.route = { id: page.route.path };
511
- }
512
-
513
- // form actions (+page.server.ts)
514
- if (
515
- matched.pageServer &&
516
- HTTP_METHODS.includes(evt.request.method as any)
517
- ) {
518
- const mod = await loader(matched.pageServer.filePath);
519
-
520
- // named actions: ?/create dispatches export `create`. Only for
521
- // non-GET requests: a GET must never run an action, or any link
522
- // or <img> on another site could trigger one with the visitor's
523
- // cookies and no CSRF check (GET skips it)
524
- const isRead =
525
- evt.request.method === "GET" || evt.request.method === "HEAD";
526
- const actionName = isRead
527
- ? undefined
528
- : [...evt.url.searchParams.keys()]
529
- .find((k) => k.startsWith("/"))
530
- ?.slice(1);
531
- // every other function export is callable by name, but the
532
- // module's own hooks are not actions
533
- const reserved =
534
- actionName !== undefined && RESERVED_EXPORTS.has(actionName);
535
- // reads render the page; an exported GET is not an action either
536
- const handler =
537
- reserved || isRead
538
- ? undefined
539
- : actionName
540
- ? mod[actionName]
541
- : mod[evt.request.method];
542
- if (actionName && typeof handler !== "function") {
543
- return new Response("Not Found", { status: 404 });
544
- }
545
-
546
- if (mod.csrf !== false && !isRead) {
547
- const cookieToken = cookies.get("_csrf");
548
- const formData = await evt.request
549
- .clone()
550
- .formData()
551
- .catch(() => null);
552
- const bodyToken = formData?.get("_csrf");
553
- if (!cookieToken || cookieToken !== String(bodyToken)) {
554
- return new Response("Forbidden", { status: 403 });
555
- }
556
- }
557
- // enhance() submits with fetch, which follows a 303 on its own
558
- // and can't read where it went; it asks for the outcome as JSON
559
- // instead and navigates itself
560
- const enhanced = evt.request.headers.get("x-grimoire-form") === "1";
561
- if (handler) {
562
- let result: any;
563
- try {
564
- result = await handler({
565
- request: evt.request,
566
- params: matched.params,
567
- url: evt.url,
568
- locals: evt.locals,
569
- fetch: patchedFetch,
570
- cookies,
571
- });
572
- } catch (e) {
573
- if (isRedirectResult(e)) {
574
- if (enhanced) {
575
- return Response.json({
576
- type: "redirect",
577
- status: e.status,
578
- location: e.location,
579
- });
580
- }
581
- return new Response(null, {
658
+ } catch (e) {
659
+ if (isRedirectResult(e)) {
660
+ if (enhanced) {
661
+ return Response.json({
662
+ type: "redirect",
582
663
  status: e.status,
583
- headers: { Location: e.location },
664
+ location: e.location,
584
665
  });
585
666
  }
586
- if (isErrorResult(e)) {
587
- const isApi =
588
- enhanced ||
589
- evt.request.headers
590
- .get("accept")
591
- ?.includes("application/json");
592
- if (isApi) {
593
- return Response.json(
594
- { error: true, status: e.status, message: e.message },
595
- { status: e.status },
596
- );
597
- }
598
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
599
- // no layoutPairs here: layout data comes from the load
600
- // pipeline in renderRoute, which a form action bypasses —
601
- // wrapping layouts without their data would crash them
602
- return (
603
- (await renderErrorPage(
604
- tree.errors,
605
- evt.url.pathname,
606
- e.status,
607
- e.message,
608
- e,
609
- loader,
610
- { params: matched.params, nonceAttr, dev },
611
- )) ?? new Response(e.message, { status: e.status })
612
- );
613
- }
614
- throw e;
667
+ return new Response(null, {
668
+ status: e.status,
669
+ headers: { Location: e.location },
670
+ });
615
671
  }
616
-
617
- if (isFailResult(result)) {
618
- if (enhanced) {
672
+ if (isErrorResult(e)) {
673
+ const isApi =
674
+ enhanced ||
675
+ evt.request.headers
676
+ .get("accept")
677
+ ?.includes("application/json");
678
+ if (isApi) {
619
679
  return Response.json(
620
- { fail: true, status: result.status, data: result.data },
621
- { status: result.status },
680
+ { error: true, status: e.status, message: e.message },
681
+ { status: e.status },
622
682
  );
623
683
  }
624
- // a plain form post (no JavaScript): show the page again,
625
- // with the failure as its `form` prop
626
- return renderRoute(
627
- matched,
628
- evt.request,
629
- tree.errors,
630
- loader,
631
- evt.locals,
632
- plugins,
633
- cspNonce,
634
- dev,
635
- patchedFetch,
636
- { status: result.status, data: result.data },
684
+ const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
685
+ // no layoutPairs here: layout data comes from the load
686
+ // pipeline in renderRoute, which a form action bypasses —
687
+ // wrapping layouts without their data would crash them
688
+ return (
689
+ (await renderErrorPage(
690
+ tree.errors,
691
+ evt.url.pathname,
692
+ e.status,
693
+ e.message,
694
+ e,
695
+ loader,
696
+ { params: matched.params, nonceAttr, dev },
697
+ )) ?? new Response(e.message, { status: e.status })
637
698
  );
638
699
  }
700
+ throw e;
701
+ }
639
702
 
640
- const redirectTo =
641
- result?.redirect ?? evt.request.headers.get("referer") ?? "/";
703
+ if (isFailResult(result)) {
642
704
  if (enhanced) {
643
- return Response.json({
644
- type: "success",
645
- location: redirectTo,
646
- data: result ?? null,
647
- });
705
+ return Response.json(
706
+ { fail: true, status: result.status, data: result.data },
707
+ { status: result.status },
708
+ );
648
709
  }
649
- return new Response(null, {
650
- status: 303,
651
- headers: { Location: redirectTo },
652
- });
653
- }
654
- if (!actionName && !isRead) {
655
- return new Response("Method Not Allowed", { status: 405 });
710
+ // a plain form post (no JavaScript): show the page again,
711
+ // with the failure as its `form` prop
712
+ return renderRoute(
713
+ matched,
714
+ evt.request,
715
+ tree.errors,
716
+ loader,
717
+ evt.locals,
718
+ plugins,
719
+ cspNonce,
720
+ dev,
721
+ patchedFetch,
722
+ { status: result.status, data: result.data },
723
+ );
656
724
  }
657
- }
658
725
 
659
- // page routes
660
- const response = await renderRoute(
661
- matched,
662
- evt.request,
663
- tree.errors,
664
- loader,
665
- evt.locals,
666
- plugins,
667
- cspNonce,
668
- dev,
669
- patchedFetch,
670
- );
671
-
672
- if (evt.request.headers.get("x-grimoire-navigate") === "1") {
673
- return response;
674
- }
675
-
676
- const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
677
- if (hasRenderPlugins) {
678
- let html = await response.text();
679
- for (const plugin of plugins) {
680
- html =
681
- (await plugin.onRouteRender?.(html, {
682
- route: matched.route,
683
- request: evt.request,
684
- params: matched.params,
685
- data: undefined,
686
- })) ?? html;
726
+ const redirectTo =
727
+ result?.redirect ?? evt.request.headers.get("referer") ?? "/";
728
+ if (enhanced) {
729
+ return Response.json({
730
+ type: "success",
731
+ location: redirectTo,
732
+ data: result ?? null,
733
+ });
687
734
  }
688
- // Carry the original headers over. Rebuilding with a fixed set
689
- // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
690
- // plugin silently broke form actions and cache correctness.
691
- const headers = new Headers(response.headers);
692
- headers.set("Content-Type", "text/html");
693
- return new Response(html, {
694
- status: response.status,
695
- statusText: response.statusText,
696
- headers,
735
+ return new Response(null, {
736
+ status: 303,
737
+ headers: { Location: redirectTo },
697
738
  });
698
739
  }
740
+ if (!actionName && !isRead) {
741
+ return new Response("Method Not Allowed", { status: 405 });
742
+ }
743
+ }
744
+
745
+ // page routes
746
+ const response = await renderRoute(
747
+ matched,
748
+ evt.request,
749
+ tree.errors,
750
+ loader,
751
+ evt.locals,
752
+ plugins,
753
+ cspNonce,
754
+ dev,
755
+ patchedFetch,
756
+ );
699
757
 
758
+ if (evt.request.headers.get("x-grimoire-navigate") === "1") {
700
759
  return response;
701
- };
760
+ }
702
761
 
703
- let response: Response;
704
- try {
705
- if (!hooksHandle) {
706
- response = await resolve(event);
707
- } else {
708
- response = await hooksHandle({ event, resolve });
762
+ const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
763
+ if (hasRenderPlugins) {
764
+ let html = await response.text();
765
+ for (const plugin of plugins) {
766
+ html =
767
+ (await plugin.onRouteRender?.(html, {
768
+ route: matched.route,
769
+ request: evt.request,
770
+ params: matched.params,
771
+ data: undefined,
772
+ })) ?? html;
709
773
  }
710
- } catch (err) {
711
- logger.error(
712
- `${event.request.method} ${event.url.pathname} failed:`,
713
- err,
714
- );
715
- await hooksHandleError?.({
716
- error: err,
717
- event,
718
- status: 500,
719
- message: "Internal Server Error",
774
+ // Carry the original headers over. Rebuilding with a fixed set
775
+ // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
776
+ // plugin silently broke form actions and cache correctness.
777
+ const headers = new Headers(response.headers);
778
+ headers.set("Content-Type", "text/html");
779
+ return new Response(html, {
780
+ status: response.status,
781
+ statusText: response.statusText,
782
+ headers,
720
783
  });
721
- // an unexpected error gets the nearest +error.tsx too, with a
722
- // generic message: details stay in the log
723
- try {
724
- const page = await renderErrorPage(
725
- tree.errors,
726
- event.url.pathname,
727
- 500,
728
- "Internal Server Error",
729
- process.env.NODE_ENV === "production" ? null : err,
730
- loader,
731
- { nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
732
- );
733
- if (page) return page;
734
- } catch (pageErr) {
735
- logger.error(
736
- "+error.tsx failed while rendering an error:",
737
- pageErr,
738
- );
739
- }
740
- const errorHtmlPath = `${process.cwd()}/error.html`;
741
- try {
742
- const errorFile = Bun.file(errorHtmlPath);
743
- if (await errorFile.exists()) {
744
- return new Response(errorFile, {
745
- status: 500,
746
- headers: { "Content-Type": "text/html" },
747
- });
748
- }
749
- } catch {}
750
- const message =
751
- process.env.NODE_ENV === "production"
752
- ? "Internal Server Error"
753
- : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
754
- return new Response(message, { status: 500 });
755
784
  }
756
785
 
757
- const setCookieHeaders = cookies.toHeaders();
758
- if (
759
- !response ||
760
- (setCookieHeaders.length === 0 &&
761
- Object.keys(setHeadersMap).length === 0)
762
- ) {
763
- return response;
764
- }
765
- const headers = new Headers(response.headers);
766
- for (const [k, v] of Object.entries(setHeadersMap)) {
767
- headers.set(k, v);
768
- }
769
- for (const sc of setCookieHeaders) {
770
- headers.append("Set-Cookie", sc);
786
+ return response;
787
+ };
788
+
789
+ let response: Response;
790
+ try {
791
+ if (!hooksHandle) {
792
+ response = await resolve(event);
793
+ } else {
794
+ response = await hooksHandle({ event, resolve });
771
795
  }
772
- response = new Response(response.body, {
773
- status: response.status,
774
- statusText: response.statusText,
775
- headers,
796
+ } catch (err) {
797
+ logger.error(
798
+ `${event.request.method} ${event.url.pathname} failed:`,
799
+ err,
800
+ );
801
+ await hooksHandleError?.({
802
+ error: err,
803
+ event,
804
+ status: 500,
805
+ message: "Internal Server Error",
776
806
  });
807
+ // an unexpected error gets the nearest +error.tsx too, with a
808
+ // generic message: details stay in the log
809
+ try {
810
+ const page = await renderErrorPage(
811
+ tree.errors,
812
+ event.url.pathname,
813
+ 500,
814
+ "Internal Server Error",
815
+ process.env.NODE_ENV === "production" ? null : err,
816
+ loader,
817
+ { nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
818
+ );
819
+ if (page) return page;
820
+ } catch (pageErr) {
821
+ logger.error(
822
+ "+error.tsx failed while rendering an error:",
823
+ pageErr,
824
+ );
825
+ }
826
+ const errorHtmlPath = `${process.cwd()}/error.html`;
827
+ try {
828
+ const errorFile = Bun.file(errorHtmlPath);
829
+ if (await errorFile.exists()) {
830
+ return new Response(errorFile, {
831
+ status: 500,
832
+ headers: { "Content-Type": "text/html" },
833
+ });
834
+ }
835
+ } catch {}
836
+ const message =
837
+ process.env.NODE_ENV === "production"
838
+ ? "Internal Server Error"
839
+ : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
840
+ return new Response(message, { status: 500 });
841
+ }
777
842
 
843
+ const setCookieHeaders = cookies.toHeaders();
844
+ if (
845
+ !response ||
846
+ (setCookieHeaders.length === 0 &&
847
+ Object.keys(setHeadersMap).length === 0)
848
+ ) {
778
849
  return response;
850
+ }
851
+ const headers = new Headers(response.headers);
852
+ for (const [k, v] of Object.entries(setHeadersMap)) {
853
+ headers.set(k, v);
854
+ }
855
+ for (const sc of setCookieHeaders) {
856
+ headers.append("Set-Cookie", sc);
857
+ }
858
+ response = new Response(response.body, {
859
+ status: response.status,
860
+ statusText: response.statusText,
861
+ headers,
779
862
  });
780
- },
863
+
864
+ return response;
865
+ });
866
+ }
867
+
868
+ const wsConfig = {
781
869
  websocket: {
782
870
  open(ws: ServerWebSocket<any>) {
783
871
  if (ws.data.__hmrClient) {
@@ -802,6 +890,19 @@ export async function createServer(config: GrimoireConfig = {}) {
802
890
  (ws.data as _WsInternalData).__handler?.drain?.(ws);
803
891
  },
804
892
  },
893
+ };
894
+
895
+ // Bun.serve is called here rather than alongside the websocket config
896
+ // because handleRequest is referenced before its declaration; function
897
+ // hoisting makes that safe, and this keeps the two blocks readable.
898
+ const server = Bun.serve({
899
+ port,
900
+ hostname: host,
901
+ // Wrapping is what makes afterResponse() mean "after the response",
902
+ // including for streaming responses: the tasks fire when the body
903
+ // finishes, not when the handler returns.
904
+ fetch: (req) => withAfterResponse(req, handleRequest),
905
+ ...wsConfig,
805
906
  });
806
907
 
807
908
  let stopping = false;
@@ -809,6 +910,10 @@ export async function createServer(config: GrimoireConfig = {}) {
809
910
  if (stopping) return;
810
911
  stopping = true;
811
912
  await runHook(plugins, "onStop", "shutdown");
913
+ // Drain before stopping, so a task already registered for a response
914
+ // that has been sent gets to finish rather than being killed with the
915
+ // process. Bounded: a hung task must not block a deploy forever.
916
+ await drainAfterResponse();
812
917
  // stop(true), not stop(): the graceful form waits for open connections,
813
918
  // and a dev HMR websocket never closes on its own, so shutdown hangs.
814
919
  server.stop(true);