@sigil-dev/grimoire 0.9.10 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,10 +9,13 @@ import { makeDevLoader } from "../dev/loader.ts";
9
9
  import { normalizePath } from "../dev/paths.ts";
10
10
  import { crawlFrom } from "../dev/scan.ts";
11
11
  import { startWatcher } from "../dev/watcher.ts";
12
+ import { envModuleSource } from "../env/modules";
12
13
  import { log } from "../logger/instance.ts";
14
+ import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
15
+ import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
13
16
  import { renderErrorPage, renderRoute } from "../rendering";
14
17
  import { registerSSRPlugin } from "../rendering/ssrPlugin";
15
- import { findClosestError, matchRoute } from "../routing/router";
18
+ import { matchRoute } from "../routing/router";
16
19
  import { isErrorResult } from "../sentinels/error.ts";
17
20
  import { isFailResult } from "../sentinels/fail.ts";
18
21
  import { isRedirectResult } from "../sentinels/redirect.ts";
@@ -28,9 +31,19 @@ import type {
28
31
  ResolveFunction,
29
32
  } from "./hooks";
30
33
  import { runDeserializeLocals, runHook, runRequestHooks } from "./plugins";
34
+ import { projectAliases, resolverPlugin } from "./resolver";
31
35
 
32
36
  const logger = log.scope("server");
33
37
 
38
+ /** +page.server.ts exports that are never dispatched as named actions. */
39
+ const RESERVED_EXPORTS = new Set([
40
+ "load",
41
+ "canMatch",
42
+ "csrf",
43
+ "loading",
44
+ "default",
45
+ ]);
46
+
34
47
  /**
35
48
  * Directories to watch in dev. `src` covers components and libs that pages
36
49
  * import; the routes directory is added separately when it lives outside it.
@@ -47,6 +60,70 @@ function watchRoots(projectRoot: string, routesDir: string): string[] {
47
60
  roots.push(routesDir);
48
61
  return roots;
49
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
+ }
50
127
  /**
51
128
  * Try to load hooks.server.ts from the project root.
52
129
  */
@@ -57,18 +134,23 @@ async function loadHooks(projectRoot: string): Promise<{
57
134
  handleFetch?: HandleFetch;
58
135
  }> {
59
136
  const hooksPath = `${projectRoot}/hooks.server.ts`;
60
- try {
61
- const mod = await import(hooksPath);
62
- return {
63
- handle: mod.handle,
64
- init: mod.init,
65
- handleError: mod.handleError,
66
- handleFetch: mod.handleFetch,
67
- };
68
- } catch {
69
- // no hooks file — that's fine
70
- return {};
71
- }
137
+ // no hooks file is fine; a hooks file that fails to load is not, and
138
+ // swallowing that silently switched off auth and every other handle
139
+ if (!existsSync(hooksPath)) return {};
140
+ const mod = await import(hooksPath);
141
+ return {
142
+ handle: mod.handle,
143
+ init: mod.init,
144
+ handleError: mod.handleError,
145
+ handleFetch: mod.handleFetch,
146
+ };
147
+ }
148
+
149
+ let resolverRegistered = false;
150
+ function registerServerResolver(config: GrimoireConfig): void {
151
+ if (resolverRegistered) return;
152
+ resolverRegistered = true;
153
+ bunPlugin(resolverPlugin(config, "server"));
72
154
  }
73
155
 
74
156
  interface _WsInternalData {
@@ -84,7 +166,7 @@ export async function createServer(config: GrimoireConfig = {}) {
84
166
  let finalConfig = config;
85
167
  const earlyPlugins = config.plugins ?? [];
86
168
  for (const plugin of earlyPlugins) {
87
- finalConfig = plugin.config?.(finalConfig) ?? finalConfig;
169
+ finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
88
170
  }
89
171
 
90
172
  const {
@@ -113,7 +195,9 @@ export async function createServer(config: GrimoireConfig = {}) {
113
195
 
114
196
  // SSR plugin should NOT INTNERCEPT FILES BUNDLEDFOR CLIENT
115
197
  // WHAT ARE WE DOINGGGGGGGGG
116
- registerSSRPlugin(plugins);
198
+ // $lib and config.alias in every server module, and the $env/* modules
199
+ registerSSRPlugin(plugins, projectAliases(finalConfig));
200
+ registerServerResolver(finalConfig);
117
201
 
118
202
  const graph = new DevGraph();
119
203
  const hmr = dev ? new HmrServer() : null;
@@ -230,242 +314,263 @@ export async function createServer(config: GrimoireConfig = {}) {
230
314
  // Run init hook if present
231
315
  await hooksInit?.();
232
316
 
233
- // Register alias plugin so dynamically-imported +server.ts routes can resolve custom aliases
234
- if (Object.keys(aliases).length > 0) {
235
- bunPlugin({
236
- name: "grimoire-alias",
237
- setup(build) {
238
- for (const [prefix, target] of Object.entries(aliases)) {
239
- const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
240
- build.onResolve(
241
- { filter: new RegExp(`^${escaped}(/|$)`) },
242
- (args) => ({
243
- path: args.path.replace(prefix, join(process.cwd(), target)),
244
- }),
245
- );
246
- }
247
- },
248
- });
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
+ }
249
327
  }
250
- const server = Bun.serve({
251
- port,
252
- hostname: host,
253
- fetch: async (req) => {
254
- const rawLocals = req.headers.get("X-Grimoire-Locals");
255
- const locals: App.Locals = rawLocals
256
- ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
257
- : {};
258
- const url = new URL(req.url);
259
-
260
- if (dev && url.pathname === "/__grimoire__/hmr") {
261
- //@ts-expect-error holy shut up
262
- if (server.upgrade(req, { data: { __hmrClient: true } })) {
263
- return undefined as unknown as Response;
264
- }
265
- return new Response("Upgrade Required", { status: 426 });
266
- }
267
- if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
268
- return new Response(HMR_CLIENT_SOURCE, {
269
- headers: { "Content-Type": "application/javascript" },
270
- });
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;
271
340
  }
272
- if (dev && url.pathname === "/__grimoire__/open") {
273
- const file = url.searchParams.get("file") ?? "";
274
- const line = url.searchParams.get("line") ?? "1";
275
- const col = url.searchParams.get("col") ?? "1";
276
- const editor = finalConfig.devEditor ?? "code";
277
- //@ts-expect-error Bun spawn has werird types just shut up
278
- Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
279
- 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);
280
365
  }
281
- if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
282
- const depName = decodeURIComponent(
283
- url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
284
- );
285
366
 
286
- // grimoire shim
287
- if (depName.includes("@sigil-dev__grimoire")) {
288
- return Response.redirect("/__grimoire__/grimoire-client.js", 302);
289
- }
367
+ // convert URL-safe name back to package name
368
+ // @codex__shared → @codex/shared
369
+ const pkgName = depName.startsWith("@")
370
+ ? depName.replace("__", "/")
371
+ : depName;
290
372
 
291
- // convert URL-safe name back to package name
292
- // @codex__shared → @codex/shared
293
- const pkgName = depName.startsWith("@")
294
- ? depName.replace("__", "/")
295
- : depName;
296
-
297
- const depsDir = join(process.cwd(), ".grimoire/deps");
298
- mkdirSync(depsDir, { recursive: true });
299
- const outFile = join(depsDir, `${depName}.js`);
300
-
301
- if (!(await Bun.file(outFile).exists())) {
302
- logger.debug("bundling dep:", pkgName);
303
- try {
304
- const entry = Bun.resolveSync(pkgName, process.cwd());
305
- const result = await Bun.build({
306
- entrypoints: [entry],
307
- outdir: depsDir,
308
- naming: `${depName}.js`,
309
- target: "browser",
310
- format: "esm",
311
- minify: false,
312
- external: ["@sigil-dev/runtime"],
313
- });
314
- if (!result.success) {
315
- logger.error("dep bundle failed:", pkgName, result.logs);
316
- return new Response(
317
- `throw new Error("failed to bundle dep: ${pkgName}")`,
318
- { headers: { "Content-Type": "application/javascript" } },
319
- );
320
- }
321
- logger.debug("bundled dep:", pkgName);
322
- } 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);
323
392
  return new Response(
324
- `throw new Error("dep not found: ${pkgName}: ${e.message}")`,
393
+ `throw new Error("failed to bundle dep: ${pkgName}")`,
325
394
  { headers: { "Content-Type": "application/javascript" } },
326
395
  );
327
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
+ );
328
403
  }
404
+ }
405
+
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)})`;
422
+ }
423
+ return new Response(js, {
424
+ headers: {
425
+ "Content-Type": "application/javascript",
426
+ "Cache-Control": "no-store",
427
+ },
428
+ });
429
+ }
329
430
 
330
- return new Response(Bun.file(outFile), {
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
+ });
444
+ return new Response(js, {
331
445
  headers: {
332
446
  "Content-Type": "application/javascript",
333
447
  "Cache-Control": "no-store",
334
448
  },
335
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
+ });
336
455
  }
456
+ }
337
457
 
338
- if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
339
- const clientPath = decodeURIComponent(
340
- url.pathname.slice("/__grimoire__/m/".length),
341
- );
342
- const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
343
- try {
344
- // compiled at the module's current graph version, which is what
345
- // the `?v=` in the URL was derived from
346
- const { js } = await getDevModule(absPath, {
347
- projectRoot: process.cwd(),
348
- aliases,
349
- graph,
350
- });
351
- return new Response(js, {
352
- headers: {
353
- "Content-Type": "application/javascript",
354
- "Cache-Control": "no-store",
355
- },
356
- });
357
- } catch (e: unknown) {
358
- const message = e instanceof Error ? e.message : String(e);
359
- return new Response(`throw new Error(${JSON.stringify(message)})`, {
360
- headers: { "Content-Type": "application/javascript" },
361
- });
362
- }
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
+ };
363
508
  }
364
-
365
- return runRequestHooks(plugins, req, async () => {
366
- const publicFile = Bun.file(`${process.cwd()}/public${url.pathname}`);
367
- if (await publicFile.exists()) {
368
- 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
+ );
369
533
  }
370
534
 
371
- const HTTP_METHODS = [
372
- "GET",
373
- "POST",
374
- "PUT",
375
- "PATCH",
376
- "DELETE",
377
- "HEAD",
378
- "OPTIONS",
379
- ] as const;
380
-
381
- // Build event BEFORE matching — handle() runs pre-match like SvelteKit
382
- const cookieHeader = req.headers.get("cookie") ?? "";
383
- const cookies = createCookies(cookieHeader);
384
- const setHeadersMap: Record<string, string> = {};
385
-
386
- const event: RequestEvent = {
387
- request: req,
388
- url,
389
- params: {},
390
- locals,
391
- cookies,
392
- route: { id: "" },
393
- fetch: globalThis.fetch,
394
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
395
- };
535
+ // patch event with match results so handle() epilogue can read them
536
+ evt.params = matched.params;
537
+ evt.route = { id: matched.route.path };
396
538
 
397
- if (hooksHandleFetch) {
398
- event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
399
- const r = new Request(reqInfo, init);
400
- return Promise.resolve(
401
- hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
402
- );
403
- };
404
- }
405
- const patchedFetch: typeof fetch = (input, init) => {
406
- const resolved =
407
- typeof input === "string" && input.startsWith("/")
408
- ? new URL(input, url.origin).toString()
409
- : input;
410
- return globalThis.fetch(resolved as any, init);
411
- };
412
- const resolve: ResolveFunction = async (evt) => {
413
- // matching happens here — after handle() has run
414
- const matched = matchRoute(tree, evt.url, paramMatcherFns);
415
- if (!matched) {
416
- const error = findClosestError(tree.errors, evt.url.pathname);
417
- if (error) {
418
- const mod = await loader(error.filePath);
419
- const html = mod.default({ status: 404, message: "Not Found" });
420
- return new Response(html, {
421
- status: 404,
422
- headers: { "Content-Type": "text/html" },
423
- });
424
- }
425
- return new Response("Not Found", { status: 404 });
426
- }
539
+ // API routes (+server.ts)
540
+ if (matched.route.type === "server") {
541
+ const mod = await loader(matched.route.filePath);
427
542
 
428
- // patch event with match results so handle() epilogue can read them
429
- evt.params = matched.params;
430
- evt.route = { id: matched.route.path };
431
-
432
- // API routes (+server.ts)
433
- if (matched.route.type === "server") {
434
- const mod = await loader(matched.route.filePath);
435
-
436
- const isWsUpgrade =
437
- evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
438
- if (isWsUpgrade && mod.websocket) {
439
- let extraData: Record<string, unknown> = {};
440
- if (mod.upgrade) {
441
- try {
442
- const result = await mod.upgrade({
443
- request: evt.request,
444
- params: matched.params,
445
- url: evt.url,
446
- locals: evt.locals,
447
- });
448
- if (result && typeof result === "object") extraData = result;
449
- } catch {
450
- return new Response("Upgrade Required", { status: 426 });
451
- }
452
- }
453
- const wsData: _WsInternalData = {
454
- params: matched.params,
455
- __handler: mod.websocket,
456
- ...extraData,
457
- };
458
- //@ts-expect-error i dont know what you are talking about please
459
- if (server.upgrade(req, { data: wsData })) {
460
- 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 });
461
558
  }
462
- return new Response("Upgrade Required", { status: 426 });
463
559
  }
464
-
465
- const handler = mod[evt.request.method];
466
- if (!handler) {
467
- return new Response("Method Not Allowed", { status: 405 });
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;
468
568
  }
569
+ return new Response("Upgrade Required", { status: 426 });
570
+ }
571
+
572
+ const handler = mod[evt.request.method];
573
+ if (handler) {
469
574
  return handler({
470
575
  request: evt.request,
471
576
  params: matched.params,
@@ -475,210 +580,292 @@ export async function createServer(config: GrimoireConfig = {}) {
475
580
  cookies,
476
581
  setHeaders: (headers) => Object.assign(setHeadersMap, headers),
477
582
  });
478
- }
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
+ }
479
598
 
480
- // form actions (+page.server.ts)
481
- if (
482
- matched.pageServer &&
483
- HTTP_METHODS.includes(evt.request.method as any)
484
- ) {
485
- const mod = await loader(matched.pageServer.filePath);
486
-
487
- // named actions: ?/create dispatches export `create`
488
- const actionName = [...evt.url.searchParams.keys()]
489
- .find((k) => k.startsWith("/"))
490
- ?.slice(1);
491
- const handler = actionName
492
- ? mod[actionName]
493
- : mod[evt.request.method];
494
- if (actionName && !handler) {
495
- return new Response("Not Found", { status: 404 });
496
- }
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
+ }
497
631
 
498
- if (
499
- mod.csrf !== false &&
500
- evt.request.method !== "GET" &&
501
- evt.request.method !== "HEAD"
502
- ) {
503
- const cookieToken = cookies.get("_csrf");
504
- const formData = await evt.request
505
- .clone()
506
- .formData()
507
- .catch(() => null);
508
- const bodyToken = formData?.get("_csrf");
509
- if (!cookieToken || cookieToken !== String(bodyToken)) {
510
- return new Response("Forbidden", { status: 403 });
511
- }
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 });
512
641
  }
513
- if (handler) {
514
- let result: any;
515
- try {
516
- result = await handler({
517
- request: evt.request,
518
- params: matched.params,
519
- url: evt.url,
520
- locals: evt.locals,
521
- fetch: patchedFetch,
522
- cookies,
523
- });
524
- } catch (e) {
525
- if (isRedirectResult(e)) {
526
- return new Response(null, {
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({
651
+ request: evt.request,
652
+ params: matched.params,
653
+ url: evt.url,
654
+ locals: evt.locals,
655
+ fetch: patchedFetch,
656
+ cookies,
657
+ });
658
+ } catch (e) {
659
+ if (isRedirectResult(e)) {
660
+ if (enhanced) {
661
+ return Response.json({
662
+ type: "redirect",
527
663
  status: e.status,
528
- headers: { Location: e.location },
664
+ location: e.location,
529
665
  });
530
666
  }
531
- if (isErrorResult(e)) {
532
- const isApi = evt.request.headers
667
+ return new Response(null, {
668
+ status: e.status,
669
+ headers: { Location: e.location },
670
+ });
671
+ }
672
+ if (isErrorResult(e)) {
673
+ const isApi =
674
+ enhanced ||
675
+ evt.request.headers
533
676
  .get("accept")
534
677
  ?.includes("application/json");
535
- if (isApi) {
536
- return Response.json(
537
- { error: true, status: e.status, message: e.message },
538
- { status: e.status },
539
- );
540
- }
541
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
542
- // no layoutPairs here: layout data comes from the load
543
- // pipeline in renderRoute, which a form action bypasses —
544
- // wrapping layouts without their data would crash them
545
- return (
546
- (await renderErrorPage(
547
- tree.errors,
548
- evt.url.pathname,
549
- e.status,
550
- e.message,
551
- e,
552
- loader,
553
- { params: matched.params, nonceAttr, dev },
554
- )) ?? new Response(e.message, { status: e.status })
678
+ if (isApi) {
679
+ return Response.json(
680
+ { error: true, status: e.status, message: e.message },
681
+ { status: e.status },
555
682
  );
556
683
  }
557
- throw e;
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 })
698
+ );
558
699
  }
700
+ throw e;
701
+ }
559
702
 
560
- if (isFailResult(result)) {
703
+ if (isFailResult(result)) {
704
+ if (enhanced) {
561
705
  return Response.json(
562
706
  { fail: true, status: result.status, data: result.data },
563
707
  { status: result.status },
564
708
  );
565
709
  }
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
+ );
724
+ }
566
725
 
567
- const redirectTo =
568
- result?.redirect ?? evt.request.headers.get("referer") ?? "/";
569
- return new Response(null, {
570
- status: 303,
571
- headers: { Location: redirectTo },
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,
572
733
  });
573
734
  }
574
- if (!actionName && evt.request.method !== "GET") {
575
- return new Response("Method Not Allowed", { status: 405 });
576
- }
735
+ return new Response(null, {
736
+ status: 303,
737
+ headers: { Location: redirectTo },
738
+ });
577
739
  }
578
-
579
- // page routes
580
- const response = await renderRoute(
581
- matched,
582
- evt.request,
583
- tree.errors,
584
- loader,
585
- evt.locals,
586
- plugins,
587
- cspNonce,
588
- dev,
589
- patchedFetch,
590
- );
591
-
592
- if (evt.request.headers.get("x-grimoire-navigate") === "1") {
593
- return response;
740
+ if (!actionName && !isRead) {
741
+ return new Response("Method Not Allowed", { status: 405 });
594
742
  }
743
+ }
595
744
 
596
- const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
597
- if (hasRenderPlugins) {
598
- let html = await response.text();
599
- for (const plugin of plugins) {
600
- html =
601
- (await plugin.onRouteRender?.(html, {
602
- route: matched.route,
603
- request: evt.request,
604
- params: matched.params,
605
- data: undefined,
606
- })) ?? html;
607
- }
608
- // Carry the original headers over. Rebuilding with a fixed set
609
- // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
610
- // plugin silently broke form actions and cache correctness.
611
- const headers = new Headers(response.headers);
612
- headers.set("Content-Type", "text/html");
613
- return new Response(html, {
614
- status: response.status,
615
- statusText: response.statusText,
616
- headers,
617
- });
618
- }
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
+ );
619
757
 
758
+ if (evt.request.headers.get("x-grimoire-navigate") === "1") {
620
759
  return response;
621
- };
760
+ }
622
761
 
623
- let response: Response;
624
- try {
625
- if (!hooksHandle) {
626
- response = await resolve(event);
627
- } else {
628
- 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;
629
773
  }
630
- } catch (err) {
631
- logger.error(
632
- `${event.request.method} ${event.url.pathname} failed:`,
633
- err,
634
- );
635
- await hooksHandleError?.({
636
- error: err,
637
- event,
638
- status: 500,
639
- 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,
640
783
  });
641
- const errorHtmlPath = `${process.cwd()}/error.html`;
642
- try {
643
- const errorFile = Bun.file(errorHtmlPath);
644
- if (await errorFile.exists()) {
645
- return new Response(errorFile, {
646
- status: 500,
647
- headers: { "Content-Type": "text/html" },
648
- });
649
- }
650
- } catch {}
651
- const message =
652
- process.env.NODE_ENV === "production"
653
- ? "Internal Server Error"
654
- : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
655
- return new Response(message, { status: 500 });
656
784
  }
657
785
 
658
- const setCookieHeaders = cookies.toHeaders();
659
- if (
660
- !response ||
661
- (setCookieHeaders.length === 0 &&
662
- Object.keys(setHeadersMap).length === 0)
663
- ) {
664
- return response;
665
- }
666
- const headers = new Headers(response.headers);
667
- for (const [k, v] of Object.entries(setHeadersMap)) {
668
- headers.set(k, v);
669
- }
670
- for (const sc of setCookieHeaders) {
671
- 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 });
672
795
  }
673
- response = new Response(response.body, {
674
- status: response.status,
675
- statusText: response.statusText,
676
- 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",
677
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
+ }
678
842
 
843
+ const setCookieHeaders = cookies.toHeaders();
844
+ if (
845
+ !response ||
846
+ (setCookieHeaders.length === 0 &&
847
+ Object.keys(setHeadersMap).length === 0)
848
+ ) {
679
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,
680
862
  });
681
- },
863
+
864
+ return response;
865
+ });
866
+ }
867
+
868
+ const wsConfig = {
682
869
  websocket: {
683
870
  open(ws: ServerWebSocket<any>) {
684
871
  if (ws.data.__hmrClient) {
@@ -703,6 +890,19 @@ export async function createServer(config: GrimoireConfig = {}) {
703
890
  (ws.data as _WsInternalData).__handler?.drain?.(ws);
704
891
  },
705
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,
706
906
  });
707
907
 
708
908
  let stopping = false;
@@ -710,6 +910,10 @@ export async function createServer(config: GrimoireConfig = {}) {
710
910
  if (stopping) return;
711
911
  stopping = true;
712
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();
713
917
  // stop(true), not stop(): the graceful form waits for open connections,
714
918
  // and a dev HMR websocket never closes on its own, so shutdown hangs.
715
919
  server.stop(true);