@sigil-dev/grimoire 0.9.11 → 0.9.13

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