@sigil-dev/grimoire 0.9.21 → 0.9.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +16 -5
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +870 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -105
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -749
  28. package/src/rendering/preload.ts +101 -101
  29. package/src/rendering/ssrPlugin.ts +108 -108
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -206
  35. package/src/server/asset-cache.ts +57 -57
  36. package/src/server/build.ts +262 -262
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -44
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +1138 -1018
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -27
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -132
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -101
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +92 -92
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +798 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +378 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +805 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +131 -131
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -1,1018 +1,1138 @@
1
- import { existsSync, mkdirSync } from "node:fs";
2
- import { isAbsolute, join } from "node:path";
3
- import { plugin as bunPlugin, type ServerWebSocket } from "bun";
4
- import { getDevModule } from "../dev/compile-module.ts";
5
- import { DevGraph } from "../dev/graph.ts";
6
- import { HMR_CLIENT_SOURCE } from "../dev/hmr-client.ts";
7
- import { type DevContext, HmrServer, handleChange } from "../dev/hmr-server.ts";
8
- import { makeDevLoader } from "../dev/loader.ts";
9
- import { normalizePath } from "../dev/paths.ts";
10
- import { crawlFrom } from "../dev/scan.ts";
11
- import { startWatcher } from "../dev/watcher.ts";
12
- import { envModuleSource } from "../env/modules";
13
- import { log } from "../logger/instance.ts";
14
- import { renderErrorPage, renderRoute } from "../rendering";
15
- import { registerSSRPlugin } from "../rendering/ssrPlugin";
16
- import { setServerTiming } from "../rendering/timing.ts";
17
- import { matchNotFound, matchRoute } from "../routing/router";
18
- import { isErrorResult } from "../sentinels/error.ts";
19
- import { isFailResult } from "../sentinels/fail.ts";
20
- import { isRedirectResult } from "../sentinels/redirect.ts";
21
- import type { GrimoireConfig, WsRouteHandler } from "../types";
22
- import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
23
- import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
24
- import { buildProject, rebuildClient } from "./build";
25
- import { clientAddressOf, trackClientAddress } from "./client-address";
26
- import { CLIENT_URL, clientDir } from "./client-dir";
27
- import { createCookies } from "./cookie-utils";
28
- import type {
29
- Handle,
30
- HandleError,
31
- HandleFetch,
32
- InitFunction,
33
- RequestEvent,
34
- ResolveFunction,
35
- } from "./hooks";
36
- import {
37
- collectServices,
38
- composeHandle,
39
- runDeserializeLocals,
40
- runHook,
41
- runRequestHooks,
42
- } from "./plugins";
43
- import { projectAliases, resolverPlugin } from "./resolver";
44
- import { preloadModules, startWarming, type Warmer } from "./warm.ts";
45
- import { withHeaders } from "./with-headers";
46
-
47
- /** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
48
- const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
49
-
50
- const logger = log.scope("server");
51
-
52
- /** +page.server.ts exports that are never dispatched as named actions. */
53
- const RESERVED_EXPORTS = new Set([
54
- "load",
55
- "canMatch",
56
- "csrf",
57
- "loading",
58
- "default",
59
- ]);
60
-
61
- /**
62
- * Directories to watch in dev. `src` covers components and libs that pages
63
- * import; the routes directory is added separately when it lives outside it.
64
- */
65
- function watchRoots(projectRoot: string, routesDir: string): string[] {
66
- const src = join(projectRoot, "src");
67
- const roots = existsSync(src) ? [src] : [];
68
- const key = normalizePath(routesDir);
69
- if (
70
- !roots.some(
71
- (r) => key === normalizePath(r) || key.startsWith(`${normalizePath(r)}/`),
72
- )
73
- )
74
- roots.push(routesDir);
75
- return roots;
76
- }
77
-
78
- /**
79
- * ETags by file, keyed on size and modification time. Hashing the content on
80
- * every request read the whole file and ran sha256 over it for each page
81
- * view; the answer only changes when the file does.
82
- */
83
- const etags = new Map<string, { stamp: string; etag: string }>();
84
-
85
- async function etagFor(file: ReturnType<typeof Bun.file>): Promise<string> {
86
- const key = file.name ?? "";
87
- const stamp = `${file.size}:${file.lastModified}`;
88
- const hit = etags.get(key);
89
- if (hit && hit.stamp === stamp) return hit.etag;
90
- const hasher = new Bun.CryptoHasher("sha256");
91
- hasher.update(await file.arrayBuffer());
92
- const etag = `"${hasher.digest("hex").slice(0, 16)}"`;
93
- etags.set(key, { stamp, etag });
94
- return etag;
95
- }
96
-
97
- /**
98
- * Serve a file from public/, or the client bundle from .grimoire/client for
99
- * a /__grimoire__/ path, or return null when the path is neither.
100
- *
101
- * `immutable` is sent only for a URL that changes with its content, and
102
- * `must-revalidate` with an ETag for everything else. That distinction is
103
- * the whole point: telling a browser to cache a stylesheet for a year at a
104
- * URL that never changes means a deploy which edits the CSS is invisible to
105
- * anyone already holding it — the new HTML loads, and the old stylesheet
106
- * stays. Unconditional `immutable` was the bug here, and it was worse than
107
- * no caching at all, because it looked like it was working.
108
- *
109
- * Callers must not put user input in the pathname: this joins it onto
110
- * public/ directly.
111
- */
112
- async function servePublicAsset(
113
- pathname: string,
114
- search: string,
115
- ifNoneMatch: string | null,
116
- ): Promise<Response | null> {
117
- // Reject traversal before touching the filesystem.
118
- if (pathname.includes("..") || pathname.includes("\0")) return null;
119
- const file = Bun.file(
120
- pathname.startsWith(CLIENT_URL)
121
- ? join(clientDir(), pathname.slice(CLIENT_URL.length))
122
- : join(process.cwd(), "public", pathname),
123
- );
124
- if (!(await file.exists())) return null;
125
-
126
- const headers: Record<string, string> = {};
127
- // Bun sets Content-Type from the extension, but be explicit for the
128
- // cases where a wrong guess is expensive: a stylesheet served as
129
- // text/plain is refused outright by the browser.
130
- const type = file.type;
131
- if (type) headers["Content-Type"] = type;
132
-
133
- const policy = cacheControlFor(pathname, search);
134
- headers["Cache-Control"] = CACHE_CONTROL[policy];
135
- if (policy === "revalidate") {
136
- // The hash of the content, so a revalidation can be answered with
137
- // 304 instead of the whole file.
138
- const etag = await etagFor(file);
139
- headers["ETag"] = etag;
140
-
141
- // Compared here rather than left to Bun: a Bun.file body does not
142
- // honour If-None-Match on its own, so without this the conditional
143
- // request would get a 200 and re-download the whole file, and
144
- // max-age=0 would cost a full transfer on every single page load.
145
- //
146
- // Weak comparison, and a match on `*`: both are what the HTTP spec
147
- // asks for here. `W/` is stripped because these are strong ETags and
148
- // a client may legitimately send the weak form of one.
149
- const current = ifNoneMatch
150
- ?.split(",")
151
- .map((v) => v.trim())
152
- .some((v) => v === "*" || v.replace(/^W\//, "") === etag);
153
- if (current) {
154
- return new Response(null, { status: 304, headers });
155
- }
156
- }
157
- // Content-Length and Last-Modified come from the File; let Bun set them.
158
- if (file.lastModified) {
159
- headers["Last-Modified"] = new Date(file.lastModified).toUTCString();
160
- }
161
- return new Response(file, { headers });
162
- }
163
- /**
164
- * Try to load hooks.server.ts from the project root.
165
- */
166
- async function loadHooks(projectRoot: string): Promise<{
167
- handle?: Handle;
168
- init?: InitFunction;
169
- handleError?: HandleError;
170
- handleFetch?: HandleFetch;
171
- }> {
172
- const hooksPath = `${projectRoot}/hooks.server.ts`;
173
- // no hooks file is fine; a hooks file that fails to load is not, and
174
- // swallowing that silently switched off auth and every other handle
175
- if (!existsSync(hooksPath)) return {};
176
- const mod = await import(hooksPath);
177
- return {
178
- handle: mod.handle,
179
- init: mod.init,
180
- handleError: mod.handleError,
181
- handleFetch: mod.handleFetch,
182
- };
183
- }
184
-
185
- let resolverRegistered = false;
186
- function registerServerResolver(config: GrimoireConfig): void {
187
- if (resolverRegistered) return;
188
- resolverRegistered = true;
189
- bunPlugin(resolverPlugin(config, "server"));
190
- }
191
-
192
- interface _WsInternalData {
193
- params: Record<string, string>;
194
- // always present at runtime — optional only to satisfy TypeScript;
195
- // upgrade block gates on mod.websocket before calling server.upgrade()
196
- __handler?: WsRouteHandler<any>;
197
- [key: string]: unknown;
198
- }
199
-
200
- export async function createServer(config: GrimoireConfig = {}) {
201
- // run config hooks
202
- let finalConfig = config;
203
- const earlyPlugins = config.plugins ?? [];
204
- for (const plugin of earlyPlugins) {
205
- finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
206
- }
207
-
208
- const {
209
- port = 3000,
210
- host = "localhost",
211
- plugins = [],
212
- dev = false,
213
- routes = "src/routes",
214
- cspNonce,
215
- //biome-ignore lint: not implemented yet
216
- devEditor = "code",
217
- _skipBuild = false,
218
- } = finalConfig;
219
-
220
- let tree: any;
221
- if (!config._skipBuild) {
222
- const { result, tree: _tree } = await buildProject(finalConfig, plugins);
223
- if (!result.success) throw new Error("Grimoire: build failed");
224
- tree = _tree;
225
- } else {
226
- // worker — build already done by loom, just scan routes
227
- const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
228
- const { scanRoutes } = await import("../routing/scanner");
229
- tree = await scanRoutes(routesDir, process.cwd());
230
- }
231
-
232
- // SSR plugin should NOT INTNERCEPT FILES BUNDLEDFOR CLIENT
233
- // WHAT ARE WE DOINGGGGGGGGG
234
- // $lib and config.alias in every server module, and the $env/* modules
235
- registerSSRPlugin(plugins, projectAliases(finalConfig));
236
- registerServerResolver(finalConfig);
237
-
238
- const graph = new DevGraph();
239
- const hmr = dev ? new HmrServer() : null;
240
-
241
- const aliases = finalConfig.alias ?? {};
242
- setServerTiming(finalConfig.serverTiming ?? dev);
243
-
244
- if (dev) {
245
- const { ensureRuntimeBundle } = await import("../dev/runtime-bundle.ts");
246
- await ensureRuntimeBundle(process.cwd());
247
-
248
- // clean dev-modules cache from previous session
249
- const { rmSync, mkdirSync } = await import("node:fs");
250
- const devModulesDir = join(process.cwd(), ".grimoire/dev-modules");
251
- try {
252
- rmSync(devModulesDir, { recursive: true, force: true });
253
- } catch {}
254
- mkdirSync(devModulesDir, { recursive: true });
255
-
256
- const scanCtx = { graph, projectRoot: process.cwd(), aliases };
257
- const entryFiles = () => {
258
- const all = [
259
- ...tree.routes,
260
- ...tree.layouts,
261
- ...tree.servers,
262
- ...tree.errors,
263
- ];
264
- for (const rf of all) {
265
- graph.getOrCreate(rf.filePath, rf.filePath);
266
- graph.markRoute(rf.filePath, rf);
267
- }
268
- return all.map((rf) => rf.filePath);
269
- };
270
-
271
- // crawl the whole import graph, not just each route's direct imports:
272
- // an edit is traced back to the routes that render it through however
273
- // many component hops lie between
274
- await crawlFrom(entryFiles(), scanCtx);
275
-
276
- const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
277
-
278
- // one rebuild at a time; saves that land during a build fold into one
279
- // follow-up pass instead of queueing a Bun.build each
280
- let rebuilding: Promise<void> | null = null;
281
- let rebuildQueued = false;
282
- const runRebuild = (): Promise<void> => {
283
- if (rebuilding) {
284
- rebuildQueued = true;
285
- return rebuilding;
286
- }
287
- rebuilding = (async () => {
288
- do {
289
- rebuildQueued = false;
290
- const { result, tree: rescanned } = await rebuildClient(
291
- finalConfig,
292
- plugins,
293
- );
294
- if (!result.success) {
295
- logger.error("client rebuild failed:", result.errors.join("\n"));
296
- break;
297
- }
298
- // adopt the rescanned tree so routes added since startup match
299
- tree = rescanned;
300
- await crawlFrom(entryFiles(), scanCtx);
301
- } while (rebuildQueued);
302
- })().finally(() => {
303
- rebuilding = null;
304
- });
305
- return rebuilding;
306
- };
307
-
308
- const devCtx: DevContext = {
309
- graph,
310
- hmr: hmr!,
311
- projectRoot: process.cwd(),
312
- aliases,
313
- entries: entryFiles,
314
- rebuild: runRebuild,
315
- scheduleRebuild: () => {
316
- runRebuild().catch((e: unknown) =>
317
- logger.error("client rebuild failed:", e),
318
- );
319
- },
320
- };
321
-
322
- startWatcher(watchRoots(process.cwd(), routesDir), (f) =>
323
- handleChange(f, devCtx),
324
- );
325
- }
326
-
327
- const loader = dev
328
- ? makeDevLoader(graph, process.cwd(), { aliases })
329
- : (p: string) => import(p);
330
-
331
- // [param=matcher] validation — load src/params/*.ts once at startup
332
- const paramMatcherFns: Record<string, (value: string) => boolean> = {};
333
- for (const pm of tree.paramMatcherFiles ?? []) {
334
- try {
335
- const mod = await loader(pm.filePath);
336
- if (typeof mod.match === "function") {
337
- paramMatcherFns[pm.name] = mod.match;
338
- }
339
- } catch (e) {
340
- logger.warn(`failed to load param matcher "${pm.name}":`, e);
341
- }
342
- }
343
- // Load hooks.server.ts
344
- const {
345
- handle: appHandle,
346
- init: hooksInit,
347
- handleError: hooksHandleError,
348
- handleFetch: hooksHandleFetch,
349
- } = await loadHooks(process.cwd());
350
-
351
- const hooksHandle = composeHandle(plugins, appHandle);
352
-
353
- // Resolved once at startup, not per request: services() may open a pool,
354
- // and the object is immutable for the process lifetime, so building it
355
- // inside handleRequest would open a connection per visitor.
356
- //
357
- // Before init(), so hooks.server.ts can use what plugins opened — a
358
- // database for a warm-up query or a migration check is the usual case,
359
- // and running init first meant it could only fail.
360
- const services = await collectServices(plugins);
361
-
362
- // Run init hook if present
363
- await hooksInit?.();
364
-
365
- // onRouteRender forces the whole response to be buffered into a string,
366
- // which silently disables streaming for every route a plugin touches. That
367
- // is a real cost and an invisible one, so say it once at boot rather than
368
- // letting someone discover it as "streaming stopped working".
369
- for (const p of plugins) {
370
- if (p.onRouteRender) {
371
- logger.warn(
372
- `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.`,
373
- );
374
- }
375
- }
376
-
377
- async function handleRequest(req: Request) {
378
- const rawLocals = req.headers.get("X-Grimoire-Locals");
379
- const locals: App.Locals = rawLocals
380
- ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
381
- : {};
382
- // Plugin services sit under the request's own locals: what the app
383
- // set (a session, a user) always wins over what a plugin declared,
384
- // so a plugin cannot clobber auth by defining a common key.
385
- for (const [key, value] of Object.entries(services)) {
386
- if (!(key in locals)) locals[key] = value;
387
- }
388
- const url = new URL(req.url);
389
-
390
- if (dev && url.pathname === "/__grimoire__/hmr") {
391
- //@ts-expect-error holy shut up
392
- if (server.upgrade(req, { data: { __hmrClient: true } })) {
393
- return undefined as unknown as Response;
394
- }
395
- return new Response("Upgrade Required", { status: 426 });
396
- }
397
- if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
398
- return new Response(HMR_CLIENT_SOURCE, {
399
- headers: { "Content-Type": "application/javascript" },
400
- });
401
- }
402
- if (dev && url.pathname === "/__grimoire__/open") {
403
- const file = url.searchParams.get("file") ?? "";
404
- const line = url.searchParams.get("line") ?? "1";
405
- const col = url.searchParams.get("col") ?? "1";
406
- const editor = finalConfig.devEditor ?? "code";
407
- //@ts-expect-error Bun spawn has werird types just shut up
408
- Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
409
- return new Response(null, { status: 204 });
410
- }
411
- if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
412
- const depName = decodeURIComponent(
413
- url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
414
- );
415
-
416
- // grimoire shim
417
- if (depName.includes("@sigil-dev__grimoire")) {
418
- return Response.redirect("/__grimoire__/grimoire-client.js", 302);
419
- }
420
-
421
- // convert URL-safe name back to package name
422
- // @codex__shared → @codex/shared
423
- const pkgName = depName.startsWith("@")
424
- ? depName.replace("__", "/")
425
- : depName;
426
-
427
- const depsDir = join(process.cwd(), ".grimoire/deps");
428
- mkdirSync(depsDir, { recursive: true });
429
- const outFile = join(depsDir, `${depName}.js`);
430
-
431
- if (!(await Bun.file(outFile).exists())) {
432
- logger.debug("bundling dep:", pkgName);
433
- try {
434
- const entry = Bun.resolveSync(pkgName, process.cwd());
435
- const result = await Bun.build({
436
- entrypoints: [entry],
437
- outdir: depsDir,
438
- naming: `${depName}.js`,
439
- target: "browser",
440
- format: "esm",
441
- minify: false,
442
- external: ["@sigil-dev/runtime"],
443
- });
444
- if (!result.success) {
445
- logger.error("dep bundle failed:", pkgName, result.logs);
446
- return new Response(
447
- `throw new Error("failed to bundle dep: ${pkgName}")`,
448
- { headers: { "Content-Type": "application/javascript" } },
449
- );
450
- }
451
- logger.debug("bundled dep:", pkgName);
452
- } catch (e: any) {
453
- return new Response(
454
- `throw new Error("dep not found: ${pkgName}: ${e.message}")`,
455
- { headers: { "Content-Type": "application/javascript" } },
456
- );
457
- }
458
- }
459
-
460
- return new Response(Bun.file(outFile), {
461
- headers: {
462
- "Content-Type": "application/javascript",
463
- "Cache-Control": "no-store",
464
- },
465
- });
466
- }
467
-
468
- if (dev && url.pathname.startsWith("/__grimoire__/env/")) {
469
- const specifier = `$env/${url.pathname.slice("/__grimoire__/env/".length).replace(/\.js$/, "")}`;
470
- let js: string;
471
- try {
472
- js = envModuleSource(specifier, "browser");
473
- } catch (e: unknown) {
474
- const message = e instanceof Error ? e.message : String(e);
475
- js = `throw new Error(${JSON.stringify(message)})`;
476
- }
477
- return new Response(js, {
478
- headers: {
479
- "Content-Type": "application/javascript",
480
- "Cache-Control": "no-store",
481
- },
482
- });
483
- }
484
-
485
- if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
486
- const clientPath = decodeURIComponent(
487
- url.pathname.slice("/__grimoire__/m/".length),
488
- );
489
- const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
490
- try {
491
- // compiled at the module's current graph version, which is what
492
- // the `?v=` in the URL was derived from
493
- const { js } = await getDevModule(absPath, {
494
- projectRoot: process.cwd(),
495
- aliases,
496
- graph,
497
- });
498
- return new Response(js, {
499
- headers: {
500
- "Content-Type": "application/javascript",
501
- "Cache-Control": "no-store",
502
- },
503
- });
504
- } catch (e: unknown) {
505
- const message = e instanceof Error ? e.message : String(e);
506
- return new Response(`throw new Error(${JSON.stringify(message)})`, {
507
- headers: { "Content-Type": "application/javascript" },
508
- });
509
- }
510
- }
511
-
512
- // Static files are served BEFORE the plugin pipeline. A CSS file or
513
- // an image has nothing to do with a plugin's onRequest hook, and
514
- // running them through it costs a hook round-trip plus a stat on
515
- // every asset request.
516
- //
517
- // Caching rule, decided per asset by servePublicAsset: the document
518
- // is never cached, a content-addressed URL is immutable, and
519
- // anything else revalidates against an ETag.
520
- const staticAsset = await servePublicAsset(
521
- url.pathname,
522
- url.search,
523
- req.headers.get("if-none-match"),
524
- );
525
- if (staticAsset) return staticAsset;
526
-
527
- return runRequestHooks(plugins, req, async () => {
528
- const HTTP_METHODS = [
529
- "GET",
530
- "POST",
531
- "PUT",
532
- "PATCH",
533
- "DELETE",
534
- "HEAD",
535
- "OPTIONS",
536
- ] as const;
537
-
538
- // Build event BEFORE matching — handle() runs pre-match like SvelteKit
539
- trackClientAddress(req, server);
540
- const cookieHeader = req.headers.get("cookie") ?? "";
541
- const cookies = createCookies(cookieHeader);
542
- const setHeadersMap: Record<string, string> = {};
543
-
544
- const event: RequestEvent = {
545
- request: req,
546
- url,
547
- params: {},
548
- locals,
549
- cookies,
550
- route: { id: "" },
551
- fetch: globalThis.fetch,
552
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
553
- getClientAddress: () => clientAddressOf(req),
554
- };
555
-
556
- if (hooksHandleFetch) {
557
- event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
558
- const r = new Request(reqInfo, init);
559
- return Promise.resolve(
560
- hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
561
- );
562
- };
563
- }
564
- const patchedFetch: typeof fetch = (input, init) => {
565
- const resolved =
566
- typeof input === "string" && input.startsWith("/")
567
- ? new URL(input, url.origin).toString()
568
- : input;
569
- return globalThis.fetch(resolved as any, init);
570
- };
571
- const resolve: ResolveFunction = async (evt) => {
572
- // matching happens here — after handle() has run
573
- let matched = matchRoute(tree, evt.url, paramMatcherFns);
574
- if (!matched) {
575
- // the nearest +error.tsx inside the layouts that cover the
576
- // address, like a page whose load throws error(404)
577
- return renderRoute(
578
- matchNotFound(tree, evt.url),
579
- evt.request,
580
- tree.errors,
581
- loader,
582
- evt.locals,
583
- plugins,
584
- cspNonce,
585
- dev,
586
- patchedFetch,
587
- );
588
- }
589
-
590
- // patch event with match results so handle() epilogue can read them
591
- evt.params = matched.params;
592
- evt.route = { id: matched.route.path };
593
-
594
- // API routes (+server.ts)
595
- if (matched.route.type === "server") {
596
- const mod = await loader(matched.route.filePath);
597
-
598
- const isWsUpgrade =
599
- evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
600
- if (isWsUpgrade && mod.websocket) {
601
- let extraData: Record<string, unknown> = {};
602
- if (mod.upgrade) {
603
- try {
604
- const result = await mod.upgrade({
605
- request: evt.request,
606
- params: matched.params,
607
- url: evt.url,
608
- locals: evt.locals,
609
- });
610
- if (result && typeof result === "object") extraData = result;
611
- } catch {
612
- return new Response("Upgrade Required", { status: 426 });
613
- }
614
- }
615
- const wsData: _WsInternalData = {
616
- params: matched.params,
617
- __handler: mod.websocket,
618
- ...extraData,
619
- };
620
- //@ts-expect-error i dont know what you are talking about please
621
- if (server.upgrade(req, { data: wsData })) {
622
- return undefined as unknown as Response;
623
- }
624
- return new Response("Upgrade Required", { status: 426 });
625
- }
626
-
627
- const handler = mod[evt.request.method];
628
- if (handler) {
629
- try {
630
- return await handler({
631
- request: evt.request,
632
- params: matched.params,
633
- url: evt.url,
634
- locals: evt.locals,
635
- fetch: patchedFetch,
636
- cookies,
637
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
638
- getClientAddress: () => clientAddressOf(evt.request),
639
- });
640
- } catch (e) {
641
- // `throw redirect(303, "/login")` works here as in an action
642
- if (isRedirectResult(e)) {
643
- return new Response(null, {
644
- status: e.status,
645
- headers: { Location: e.location },
646
- });
647
- }
648
- throw e;
649
- }
650
- }
651
- // no handler for this method: a page at the same URL (say a
652
- // chat page next to its WebSocket endpoint) takes the request
653
- const page = matchRoute(
654
- { ...tree, servers: [] },
655
- evt.url,
656
- paramMatcherFns,
657
- );
658
- if (!page) {
659
- return new Response("Method Not Allowed", { status: 405 });
660
- }
661
- matched = page;
662
- evt.params = page.params;
663
- evt.route = { id: page.route.path };
664
- }
665
-
666
- // form actions (+page.server.ts)
667
- if (
668
- matched.pageServer &&
669
- HTTP_METHODS.includes(evt.request.method as any)
670
- ) {
671
- const mod = await loader(matched.pageServer.filePath);
672
-
673
- // named actions: ?/create dispatches export `create`. Only for
674
- // non-GET requests: a GET must never run an action, or any link
675
- // or <img> on another site could trigger one with the visitor's
676
- // cookies and no CSRF check (GET skips it)
677
- const isRead =
678
- evt.request.method === "GET" || evt.request.method === "HEAD";
679
- const actionName = isRead
680
- ? undefined
681
- : [...evt.url.searchParams.keys()]
682
- .find((k) => k.startsWith("/"))
683
- ?.slice(1);
684
- // every other function export is callable by name, but the
685
- // module's own hooks are not actions
686
- const reserved =
687
- actionName !== undefined && RESERVED_EXPORTS.has(actionName);
688
- // reads render the page; an exported GET is not an action either
689
- const handler =
690
- reserved || isRead
691
- ? undefined
692
- : actionName
693
- ? mod[actionName]
694
- : mod[evt.request.method];
695
- if (actionName && typeof handler !== "function") {
696
- return new Response("Not Found", { status: 404 });
697
- }
698
-
699
- if (mod.csrf !== false && !isRead) {
700
- const cookieToken = cookies.get("_csrf");
701
- const formData = await evt.request
702
- .clone()
703
- .formData()
704
- .catch(() => null);
705
- const bodyToken = formData?.get("_csrf");
706
- if (!cookieToken || cookieToken !== String(bodyToken)) {
707
- return new Response("Forbidden", { status: 403 });
708
- }
709
- }
710
- // enhance() submits with fetch, which follows a 303 on its own
711
- // and can't read where it went; it asks for the outcome as JSON
712
- // instead and navigates itself
713
- const enhanced = evt.request.headers.get("x-grimoire-form") === "1";
714
- if (handler) {
715
- let result: any;
716
- try {
717
- result = await handler({
718
- request: evt.request,
719
- params: matched.params,
720
- url: evt.url,
721
- locals: evt.locals,
722
- fetch: patchedFetch,
723
- cookies,
724
- getClientAddress: () => clientAddressOf(evt.request),
725
- });
726
- } catch (e) {
727
- if (isRedirectResult(e)) {
728
- if (enhanced) {
729
- return Response.json({
730
- type: "redirect",
731
- status: e.status,
732
- location: e.location,
733
- });
734
- }
735
- return new Response(null, {
736
- status: e.status,
737
- headers: { Location: e.location },
738
- });
739
- }
740
- if (isErrorResult(e)) {
741
- const isApi =
742
- enhanced ||
743
- evt.request.headers
744
- .get("accept")
745
- ?.includes("application/json");
746
- if (isApi) {
747
- return Response.json(
748
- { error: true, status: e.status, message: e.message },
749
- { status: e.status },
750
- );
751
- }
752
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
753
- // no layoutPairs here: layout data comes from the load
754
- // pipeline in renderRoute, which a form action bypasses —
755
- // wrapping layouts without their data would crash them
756
- return (
757
- (await renderErrorPage(
758
- tree.errors,
759
- evt.url.pathname,
760
- e.status,
761
- e.message,
762
- e,
763
- loader,
764
- { params: matched.params, nonceAttr, dev },
765
- )) ??
766
- new Response(e.message, { status: e.status, headers: TEXT })
767
- );
768
- }
769
- throw e;
770
- }
771
-
772
- if (isFailResult(result)) {
773
- if (enhanced) {
774
- return Response.json(
775
- { fail: true, status: result.status, data: result.data },
776
- { status: result.status },
777
- );
778
- }
779
- // a plain form post (no JavaScript): show the page again,
780
- // with the failure as its `form` prop
781
- return renderRoute(
782
- matched,
783
- evt.request,
784
- tree.errors,
785
- loader,
786
- evt.locals,
787
- plugins,
788
- cspNonce,
789
- dev,
790
- patchedFetch,
791
- { status: result.status, data: result.data },
792
- );
793
- }
794
-
795
- const redirectTo =
796
- result?.redirect ?? evt.request.headers.get("referer") ?? "/";
797
- if (enhanced) {
798
- return Response.json({
799
- type: "success",
800
- location: redirectTo,
801
- data: result ?? null,
802
- });
803
- }
804
- return new Response(null, {
805
- status: 303,
806
- headers: { Location: redirectTo },
807
- });
808
- }
809
- if (!actionName && !isRead) {
810
- return new Response("Method Not Allowed", { status: 405 });
811
- }
812
- }
813
-
814
- // page routes
815
- const response = await renderRoute(
816
- matched,
817
- evt.request,
818
- tree.errors,
819
- loader,
820
- evt.locals,
821
- plugins,
822
- cspNonce,
823
- dev,
824
- patchedFetch,
825
- );
826
-
827
- if (evt.request.headers.get("x-grimoire-navigate") === "1") {
828
- return response;
829
- }
830
-
831
- const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
832
- if (hasRenderPlugins) {
833
- let html = await response.text();
834
- for (const plugin of plugins) {
835
- html =
836
- (await plugin.onRouteRender?.(html, {
837
- route: matched.route,
838
- request: evt.request,
839
- params: matched.params,
840
- data: undefined,
841
- })) ?? html;
842
- }
843
- // Carry the original headers over. Rebuilding with a fixed set
844
- // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
845
- // plugin silently broke form actions and cache correctness.
846
- const headers = new Headers(response.headers);
847
- headers.set("Content-Type", "text/html");
848
- return new Response(html, {
849
- status: response.status,
850
- statusText: response.statusText,
851
- headers,
852
- });
853
- }
854
-
855
- return response;
856
- };
857
-
858
- let response: Response;
859
- try {
860
- if (!hooksHandle) {
861
- response = await resolve(event);
862
- } else {
863
- response = await hooksHandle({ event, resolve });
864
- }
865
- } catch (err) {
866
- logger.error(
867
- `${event.request.method} ${event.url.pathname} failed:`,
868
- err,
869
- );
870
- await hooksHandleError?.({
871
- error: err,
872
- event,
873
- status: 500,
874
- message: "Internal Server Error",
875
- });
876
- // an unexpected error gets the nearest +error.tsx too, with a
877
- // generic message: details stay in the log
878
- try {
879
- const page = await renderErrorPage(
880
- tree.errors,
881
- event.url.pathname,
882
- 500,
883
- "Internal Server Error",
884
- process.env.NODE_ENV === "production" ? null : err,
885
- loader,
886
- { nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
887
- );
888
- if (page) return page;
889
- } catch (pageErr) {
890
- logger.error("+error.tsx failed while rendering an error:", pageErr);
891
- }
892
- const errorHtmlPath = `${process.cwd()}/error.html`;
893
- try {
894
- const errorFile = Bun.file(errorHtmlPath);
895
- if (await errorFile.exists()) {
896
- return new Response(errorFile, {
897
- status: 500,
898
- headers: { "Content-Type": "text/html" },
899
- });
900
- }
901
- } catch {}
902
- const message =
903
- process.env.NODE_ENV === "production"
904
- ? "Internal Server Error"
905
- : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
906
- return new Response(message, { status: 500, headers: TEXT });
907
- }
908
-
909
- const setCookieHeaders = cookies.toHeaders();
910
- if (
911
- !response ||
912
- (setCookieHeaders.length === 0 &&
913
- Object.keys(setHeadersMap).length === 0)
914
- ) {
915
- return response;
916
- }
917
- return withHeaders(
918
- response,
919
- Object.entries(setHeadersMap),
920
- setCookieHeaders.map((sc) => ["Set-Cookie", sc] as [string, string]),
921
- );
922
- });
923
- }
924
-
925
- const wsConfig = {
926
- websocket: {
927
- open(ws: ServerWebSocket<any>) {
928
- if (ws.data.__hmrClient) {
929
- hmr?.addClient(ws);
930
- return;
931
- }
932
- (ws.data as _WsInternalData).__handler?.open?.(ws);
933
- },
934
- message(ws: ServerWebSocket<any>, data: string | Buffer) {
935
- if (ws.data.__hmrClient) return;
936
- (ws.data as _WsInternalData).__handler?.message?.(ws, data);
937
- },
938
- close(ws: ServerWebSocket<any>, code: number, reason?: string) {
939
- if (ws.data.__hmrClient) {
940
- hmr?.removeClient(ws);
941
- return;
942
- }
943
- (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
944
- },
945
- drain(ws: ServerWebSocket<any>) {
946
- if (ws.data.__hmrClient) return;
947
- (ws.data as _WsInternalData).__handler?.drain?.(ws);
948
- },
949
- },
950
- };
951
-
952
- // Bun.serve is called here rather than alongside the websocket config
953
- // because handleRequest is referenced before its declaration; function
954
- // hoisting makes that safe, and this keeps the two blocks readable.
955
- // Wrapping is what makes afterResponse() mean "after the response",
956
- // including for streaming responses: the tasks fire when the body
957
- // finishes, not when the handler returns.
958
- const fetchHandler = (req: Request) => withAfterResponse(req, handleRequest);
959
-
960
- // Before the port opens, so the first visitor never pays for compiling a
961
- // route: a worker only reports ready once this has finished.
962
- const warmConfig = finalConfig.warm;
963
- if (!dev && warmConfig?.preload !== false) {
964
- const files = [
965
- ...tree.routes,
966
- ...tree.layouts,
967
- ...tree.servers,
968
- ...tree.errors,
969
- ].map((rf: { filePath: string }) => rf.filePath);
970
- const t0 = performance.now();
971
- const loaded = await preloadModules(files, loader, (msg, err) =>
972
- logger.warn(msg, err),
973
- );
974
- logger.info(
975
- `preloaded ${loaded}/${new Set(files).size} route modules in ${Math.round(performance.now() - t0)}ms`,
976
- );
977
- }
978
-
979
- const server = Bun.serve({
980
- port,
981
- hostname: host,
982
- fetch: fetchHandler,
983
- ...wsConfig,
984
- });
985
-
986
- let warmer: Warmer | null = null;
987
- if (!dev && warmConfig?.paths?.length) {
988
- warmer = startWarming({
989
- paths: warmConfig.paths,
990
- every: warmConfig.every,
991
- origin: `http://${host}:${server.port}`,
992
- headers: finalConfig._warmHeaders,
993
- handle: async (req) => fetchHandler(req),
994
- log: (msg) => logger.info(msg),
995
- });
996
- }
997
-
998
- let stopping = false;
999
- const handleShutdown = async () => {
1000
- if (stopping) return;
1001
- stopping = true;
1002
- warmer?.stop();
1003
- await runHook(plugins, "onStop", "shutdown");
1004
- // Drain before stopping, so a task already registered for a response
1005
- // that has been sent gets to finish rather than being killed with the
1006
- // process. Bounded: a hung task must not block a deploy forever.
1007
- await drainAfterResponse();
1008
- // stop(true), not stop(): the graceful form waits for open connections,
1009
- // and a dev HMR websocket never closes on its own, so shutdown hangs.
1010
- server.stop(true);
1011
- process.exit(0);
1012
- };
1013
- process.on("SIGINT", handleShutdown);
1014
- process.on("SIGTERM", handleShutdown);
1015
-
1016
- await runHook(plugins, "onStart", server);
1017
- return server;
1018
- }
1
+ import { existsSync, mkdirSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { plugin as bunPlugin, type Server, type ServerWebSocket } from "bun";
4
+ import { getDevModule } from "../dev/compile-module.ts";
5
+ import { DevGraph } from "../dev/graph.ts";
6
+ import { HMR_CLIENT_SOURCE } from "../dev/hmr-client.ts";
7
+ import { type DevContext, HmrServer, handleChange } from "../dev/hmr-server.ts";
8
+ import { makeDevLoader } from "../dev/loader.ts";
9
+ import { normalizePath } from "../dev/paths.ts";
10
+ import { crawlFrom } from "../dev/scan.ts";
11
+ import { startWatcher } from "../dev/watcher.ts";
12
+ import { envModuleSource } from "../env/modules";
13
+ import { log } from "../logger/instance.ts";
14
+ import { renderErrorPage, renderRoute } from "../rendering";
15
+ import { registerSSRPlugin } from "../rendering/ssrPlugin";
16
+ import { setServerTiming } from "../rendering/timing.ts";
17
+ import { matchNotFound, matchRoute } from "../routing/router";
18
+ import { isErrorResult } from "../sentinels/error.ts";
19
+ import { isFailResult } from "../sentinels/fail.ts";
20
+ import { isRedirectResult } from "../sentinels/redirect.ts";
21
+ import type { GrimoireConfig, WsRouteHandler } from "../types";
22
+ import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
23
+ import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
24
+ import { buildProject, rebuildClient } from "./build";
25
+ import { clientAddressOf, trackClientAddress } from "./client-address";
26
+ import { CLIENT_URL, clientDir } from "./client-dir";
27
+ import { createCookies } from "./cookie-utils";
28
+ import type {
29
+ Handle,
30
+ HandleError,
31
+ HandleFetch,
32
+ InitFunction,
33
+ RequestEvent,
34
+ ResolveFunction,
35
+ } from "./hooks";
36
+ import {
37
+ collectServices,
38
+ composeHandle,
39
+ runDeserializeLocals,
40
+ runHook,
41
+ runRequestHooks,
42
+ } from "./plugins";
43
+ import { projectAliases, resolverPlugin } from "./resolver";
44
+ import { preloadModules, startWarming, type Warmer } from "./warm.ts";
45
+ import { withHeaders } from "./with-headers";
46
+
47
+ /** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
48
+ const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
49
+
50
+ const logger = log.scope("server");
51
+
52
+ /**
53
+ * Directories to watch in dev. `src` covers components and libs that pages
54
+ * import; the routes directory is added separately when it lives outside it.
55
+ */
56
+ function watchRoots(projectRoot: string, routesDir: string): string[] {
57
+ const src = join(projectRoot, "src");
58
+ const roots = existsSync(src) ? [src] : [];
59
+ const key = normalizePath(routesDir);
60
+ if (
61
+ !roots.some(
62
+ (r) => key === normalizePath(r) || key.startsWith(`${normalizePath(r)}/`),
63
+ )
64
+ )
65
+ roots.push(routesDir);
66
+ return roots;
67
+ }
68
+
69
+ /**
70
+ * ETags by file, keyed on size and modification time. Hashing the content on
71
+ * every request read the whole file and ran sha256 over it for each page
72
+ * view; the answer only changes when the file does.
73
+ */
74
+ const etags = new Map<string, { stamp: string; etag: string }>();
75
+
76
+ async function etagFor(file: ReturnType<typeof Bun.file>): Promise<string> {
77
+ const key = file.name ?? "";
78
+ const stamp = `${file.size}:${file.lastModified}`;
79
+ const hit = etags.get(key);
80
+ if (hit && hit.stamp === stamp) return hit.etag;
81
+ const hasher = new Bun.CryptoHasher("sha256");
82
+ hasher.update(await file.arrayBuffer());
83
+ const etag = `"${hasher.digest("hex").slice(0, 16)}"`;
84
+ etags.set(key, { stamp, etag });
85
+ return etag;
86
+ }
87
+
88
+ /**
89
+ * Serve a file from public/, or the client bundle from .grimoire/client for
90
+ * a /__grimoire__/ path, or return null when the path is neither.
91
+ *
92
+ * `immutable` is sent only for a URL that changes with its content, and
93
+ * `must-revalidate` with an ETag for everything else. That distinction is
94
+ * the whole point: telling a browser to cache a stylesheet for a year at a
95
+ * URL that never changes means a deploy which edits the CSS is invisible to
96
+ * anyone already holding it — the new HTML loads, and the old stylesheet
97
+ * stays. Unconditional `immutable` was the bug here, and it was worse than
98
+ * no caching at all, because it looked like it was working.
99
+ *
100
+ * Callers must not put user input in the pathname: this joins it onto
101
+ * public/ directly.
102
+ */
103
+ async function servePublicAsset(
104
+ pathname: string,
105
+ search: string,
106
+ ifNoneMatch: string | null,
107
+ ): Promise<Response | null> {
108
+ // Reject traversal before touching the filesystem.
109
+ if (pathname.includes("..") || pathname.includes("\0")) return null;
110
+ const file = Bun.file(
111
+ pathname.startsWith(CLIENT_URL)
112
+ ? join(clientDir(), pathname.slice(CLIENT_URL.length))
113
+ : join(process.cwd(), "public", pathname),
114
+ );
115
+ if (!(await file.exists())) return null;
116
+
117
+ const headers: Record<string, string> = {};
118
+ // Bun sets Content-Type from the extension, but be explicit for the
119
+ // cases where a wrong guess is expensive: a stylesheet served as
120
+ // text/plain is refused outright by the browser.
121
+ const type = file.type;
122
+ if (type) headers["Content-Type"] = type;
123
+
124
+ const policy = cacheControlFor(pathname, search);
125
+ headers["Cache-Control"] = CACHE_CONTROL[policy];
126
+ if (policy === "revalidate") {
127
+ // The hash of the content, so a revalidation can be answered with
128
+ // 304 instead of the whole file.
129
+ const etag = await etagFor(file);
130
+ headers["ETag"] = etag;
131
+
132
+ // Compared here rather than left to Bun: a Bun.file body does not
133
+ // honour If-None-Match on its own, so without this the conditional
134
+ // request would get a 200 and re-download the whole file, and
135
+ // max-age=0 would cost a full transfer on every single page load.
136
+ //
137
+ // Weak comparison, and a match on `*`: both are what the HTTP spec
138
+ // asks for here. `W/` is stripped because these are strong ETags and
139
+ // a client may legitimately send the weak form of one.
140
+ const current = ifNoneMatch
141
+ ?.split(",")
142
+ .map((v) => v.trim())
143
+ .some((v) => v === "*" || v.replace(/^W\//, "") === etag);
144
+ if (current) {
145
+ return new Response(null, { status: 304, headers });
146
+ }
147
+ }
148
+ // Content-Length and Last-Modified come from the File; let Bun set them.
149
+ if (file.lastModified) {
150
+ headers["Last-Modified"] = new Date(file.lastModified).toUTCString();
151
+ }
152
+ return new Response(file, { headers });
153
+ }
154
+ /**
155
+ * Try to load hooks.server.ts from the project root.
156
+ */
157
+ async function loadHooks(projectRoot: string): Promise<{
158
+ handle?: Handle;
159
+ init?: InitFunction;
160
+ handleError?: HandleError;
161
+ handleFetch?: HandleFetch;
162
+ }> {
163
+ const hooksPath = `${projectRoot}/hooks.server.ts`;
164
+ // no hooks file is fine; a hooks file that fails to load is not, and
165
+ // swallowing that silently switched off auth and every other handle
166
+ if (!existsSync(hooksPath)) return {};
167
+ const mod = await import(hooksPath);
168
+ return {
169
+ handle: mod.handle,
170
+ init: mod.init,
171
+ handleError: mod.handleError,
172
+ handleFetch: mod.handleFetch,
173
+ };
174
+ }
175
+
176
+ let resolverRegistered = false;
177
+ function registerServerResolver(config: GrimoireConfig): void {
178
+ if (resolverRegistered) return;
179
+ resolverRegistered = true;
180
+ bunPlugin(resolverPlugin(config, "server"));
181
+ }
182
+
183
+ interface _WsInternalData {
184
+ params: Record<string, string>;
185
+ // always present at runtime — optional only to satisfy TypeScript;
186
+ // upgrade block gates on mod.websocket before calling server.upgrade()
187
+ __handler?: WsRouteHandler<any>;
188
+ [key: string]: unknown;
189
+ }
190
+
191
+ /**
192
+ * Everything a server is except the socket: the request handler, the
193
+ * websocket handlers and the scanned route tree.
194
+ *
195
+ * Split from `createServer` so something that is not a listening server can
196
+ * use the real pipeline — `sigil build` prerenders by sending requests
197
+ * through `fetch`, which means `hooks.server.ts`, plugins and layouts run
198
+ * exactly as they will in production. `createServer` is this plus a port.
199
+ */
200
+ export interface GrimoireApp {
201
+ /** The full request pipeline: plugins, hooks, routing, rendering. */
202
+ fetch(req: Request): Promise<Response>;
203
+ /** Handlers to hand to `Bun.serve({ websocket })`. */
204
+ websocket: ServerWebSocketHandlers;
205
+ tree: RouteTree;
206
+ /** `src/params/*.ts` matchers by name, for `[param=name]` routes. */
207
+ matchers: Record<string, (value: string) => boolean>;
208
+ config: GrimoireConfig;
209
+ plugins: GrimoirePlugin[];
210
+ /** Tell the app which server it runs in, so it can upgrade websockets. */
211
+ bind(server: Server<any>): void;
212
+ /**
213
+ * Run `onStop` and let pending after-response work finish. Begins a
214
+ * process-wide shutdown (`afterResponse()` rejects afterwards), so call it
215
+ * once, when the process is done with the app.
216
+ */
217
+ close(
218
+ reason?: "shutdown" | "restart",
219
+ options?: { drainMs?: number },
220
+ ): Promise<void>;
221
+ /** Import every route module now, so the first visitor does not pay for it. */
222
+ preload(): Promise<void>;
223
+ }
224
+
225
+ type ServerWebSocketHandlers = {
226
+ open(ws: ServerWebSocket<any>): void;
227
+ message(ws: ServerWebSocket<any>, data: string | Buffer): void;
228
+ close(ws: ServerWebSocket<any>, code: number, reason?: string): void;
229
+ drain(ws: ServerWebSocket<any>): void;
230
+ };
231
+
232
+ export async function createApp(config: GrimoireConfig = {}): Promise<GrimoireApp> {
233
+ // run config hooks
234
+ let finalConfig = config;
235
+ const earlyPlugins = config.plugins ?? [];
236
+ for (const plugin of earlyPlugins) {
237
+ finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
238
+ }
239
+
240
+ // Last word on `dev`: a plugin's config hook runs above and could have set
241
+ // it. The worker does the same for the same reason.
242
+ if (finalConfig._forceProduction) finalConfig = { ...finalConfig, dev: false };
243
+
244
+ // Before the build, which can take a minute: a missing variable is the
245
+ // cheapest thing to find out about and the most annoying to learn late.
246
+ assertRequiredEnv(finalConfig);
247
+
248
+ // A base that would 404 every asset is a startup error, not a mystery.
249
+ const appBase = normalizeBase(finalConfig.base);
250
+ setBase(appBase);
251
+
252
+ const {
253
+ port = 3000,
254
+ host = "localhost",
255
+ plugins = [],
256
+ dev = false,
257
+ routes = "src/routes",
258
+ cspNonce,
259
+ //biome-ignore lint: not implemented yet
260
+ devEditor = "code",
261
+ _skipBuild = false,
262
+ } = finalConfig;
263
+
264
+ let tree: any;
265
+ if (!config._skipBuild) {
266
+ const { result, tree: _tree } = await buildProject(finalConfig, plugins);
267
+ if (!result.success) throw new Error("Grimoire: build failed");
268
+ tree = _tree;
269
+ } else {
270
+ // worker — build already done by loom, just scan routes
271
+ const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
272
+ const { scanRoutes } = await import("../routing/scanner");
273
+ tree = await scanRoutes(routesDir, process.cwd());
274
+ }
275
+
276
+ // SSR plugin should NOT INTNERCEPT FILES BUNDLEDFOR CLIENT
277
+ // WHAT ARE WE DOINGGGGGGGGG
278
+ // $lib and config.alias in every server module, and the $env/* modules
279
+ registerSSRPlugin(plugins, projectAliases(finalConfig));
280
+ registerServerResolver(finalConfig);
281
+
282
+ // Set by bind(); the handlers below only use it once a request arrives.
283
+ let server: Server<any> | undefined;
284
+
285
+ const graph = new DevGraph();
286
+ const hmr = dev ? new HmrServer() : null;
287
+
288
+ const aliases = finalConfig.alias ?? {};
289
+ setServerTiming(finalConfig.serverTiming ?? dev);
290
+
291
+ if (dev) {
292
+ const { ensureRuntimeBundle } = await import("../dev/runtime-bundle.ts");
293
+ await ensureRuntimeBundle(process.cwd());
294
+
295
+ // clean dev-modules cache from previous session
296
+ const { rmSync, mkdirSync } = await import("node:fs");
297
+ const devModulesDir = join(process.cwd(), ".grimoire/dev-modules");
298
+ try {
299
+ rmSync(devModulesDir, { recursive: true, force: true });
300
+ } catch {}
301
+ mkdirSync(devModulesDir, { recursive: true });
302
+
303
+ const scanCtx = { graph, projectRoot: process.cwd(), aliases };
304
+ const entryFiles = () => {
305
+ const all = [
306
+ ...tree.routes,
307
+ ...tree.layouts,
308
+ ...tree.servers,
309
+ ...tree.errors,
310
+ ];
311
+ for (const rf of all) {
312
+ graph.getOrCreate(rf.filePath, rf.filePath);
313
+ graph.markRoute(rf.filePath, rf);
314
+ }
315
+ return all.map((rf) => rf.filePath);
316
+ };
317
+
318
+ // crawl the whole import graph, not just each route's direct imports:
319
+ // an edit is traced back to the routes that render it through however
320
+ // many component hops lie between
321
+ await crawlFrom(entryFiles(), scanCtx);
322
+
323
+ const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
324
+
325
+ // one rebuild at a time; saves that land during a build fold into one
326
+ // follow-up pass instead of queueing a Bun.build each
327
+ let rebuilding: Promise<void> | null = null;
328
+ let rebuildQueued = false;
329
+ const runRebuild = (): Promise<void> => {
330
+ if (rebuilding) {
331
+ rebuildQueued = true;
332
+ return rebuilding;
333
+ }
334
+ rebuilding = (async () => {
335
+ do {
336
+ rebuildQueued = false;
337
+ const { result, tree: rescanned } = await rebuildClient(
338
+ finalConfig,
339
+ plugins,
340
+ );
341
+ if (!result.success) {
342
+ logger.error("client rebuild failed:", result.errors.join("\n"));
343
+ break;
344
+ }
345
+ // adopt the rescanned tree so routes added since startup match
346
+ tree = rescanned;
347
+ await crawlFrom(entryFiles(), scanCtx);
348
+ } while (rebuildQueued);
349
+ })().finally(() => {
350
+ rebuilding = null;
351
+ });
352
+ return rebuilding;
353
+ };
354
+
355
+ const devCtx: DevContext = {
356
+ graph,
357
+ hmr: hmr!,
358
+ projectRoot: process.cwd(),
359
+ aliases,
360
+ entries: entryFiles,
361
+ rebuild: runRebuild,
362
+ scheduleRebuild: () => {
363
+ runRebuild().catch((e: unknown) =>
364
+ logger.error("client rebuild failed:", e),
365
+ );
366
+ },
367
+ };
368
+
369
+ startWatcher(watchRoots(process.cwd(), routesDir), (f) =>
370
+ handleChange(f, devCtx),
371
+ );
372
+ }
373
+
374
+ const loader = dev
375
+ ? makeDevLoader(graph, process.cwd(), { aliases })
376
+ : (p: string) => import(p);
377
+
378
+ // [param=matcher] validation — load src/params/*.ts once at startup
379
+ const paramMatcherFns: Record<string, (value: string) => boolean> = {};
380
+ for (const pm of tree.paramMatcherFiles ?? []) {
381
+ try {
382
+ const mod = await loader(pm.filePath);
383
+ if (typeof mod.match === "function") {
384
+ paramMatcherFns[pm.name] = mod.match;
385
+ }
386
+ } catch (e) {
387
+ logger.warn(`failed to load param matcher "${pm.name}":`, e);
388
+ }
389
+ }
390
+ // Load hooks.server.ts
391
+ const {
392
+ handle: appHandle,
393
+ init: hooksInit,
394
+ handleError: hooksHandleError,
395
+ handleFetch: hooksHandleFetch,
396
+ } = await loadHooks(process.cwd());
397
+
398
+ const hooksHandle = composeHandle(plugins, appHandle);
399
+
400
+ // Resolved once at startup, not per request: services() may open a pool,
401
+ // and the object is immutable for the process lifetime, so building it
402
+ // inside handleRequest would open a connection per visitor.
403
+ //
404
+ // Before init(), so hooks.server.ts can use what plugins opened — a
405
+ // database for a warm-up query or a migration check is the usual case,
406
+ // and running init first meant it could only fail.
407
+ // The same hook the coordinator fires, for every process that serves
408
+ // requests. It used to run only in the coordinator, so `sigil dev` and a
409
+ // single-process `sigil start` never gave plugins their moment to look at
410
+ // each other.
411
+ await runHook(plugins, "onPluginsResolved", {
412
+ mode: dev ? "development" : "production",
413
+ plugins: new Map(plugins.map((p) => [p.name, p])),
414
+ logger: log.scope("plugins"),
415
+ });
416
+
417
+ const services = await collectServices(plugins);
418
+
419
+ // Run init hook if present
420
+ await hooksInit?.();
421
+
422
+ // onRouteRender forces the whole response to be buffered into a string,
423
+ // which silently disables streaming for every route a plugin touches. That
424
+ // is a real cost and an invisible one, so say it once at boot rather than
425
+ // letting someone discover it as "streaming stopped working".
426
+ for (const p of plugins) {
427
+ if (p.onRouteRender) {
428
+ logger.warn(
429
+ `plugin "${p.name}" implements onRouteRender, which buffers the full HTML response and disables streaming (including the \`loading\` shell) on every route it touches. Use rewriteHtml(rewriter) to change the HTML while it streams, or onRequest to change headers.`,
430
+ );
431
+ }
432
+ }
433
+
434
+ async function handleRequest(req: Request) {
435
+ // Only the coordinator is trusted to say who the user is. A server that
436
+ // answers the public directly ignores the header, so nobody can send
437
+ // their own `locals` to it.
438
+ const rawLocals = finalConfig._behindCoordinator
439
+ ? req.headers.get("X-Grimoire-Locals")
440
+ : null;
441
+ const locals: App.Locals = rawLocals
442
+ ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
443
+ : {};
444
+ // Plugin services sit under the request's own locals: what the app
445
+ // set (a session, a user) always wins over what a plugin declared,
446
+ // so a plugin cannot clobber auth by defining a common key.
447
+ for (const [key, value] of Object.entries(services)) {
448
+ if (!(key in locals)) locals[key] = value;
449
+ }
450
+ const url = new URL(req.url);
451
+
452
+ if (dev && url.pathname === "/__grimoire__/hmr") {
453
+ //@ts-expect-error holy shut up
454
+ if (server?.upgrade(req, { data: { __hmrClient: true } })) {
455
+ return undefined as unknown as Response;
456
+ }
457
+ return new Response("Upgrade Required", { status: 426 });
458
+ }
459
+ if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
460
+ return new Response(HMR_CLIENT_SOURCE, {
461
+ headers: { "Content-Type": "application/javascript" },
462
+ });
463
+ }
464
+ if (dev && url.pathname === "/__grimoire__/open") {
465
+ const file = url.searchParams.get("file") ?? "";
466
+ const line = url.searchParams.get("line") ?? "1";
467
+ const col = url.searchParams.get("col") ?? "1";
468
+ const editor = finalConfig.devEditor ?? "code";
469
+ //@ts-expect-error Bun spawn has werird types just shut up
470
+ Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
471
+ return new Response(null, { status: 204 });
472
+ }
473
+ if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
474
+ const depName = decodeURIComponent(
475
+ url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
476
+ );
477
+
478
+ // grimoire shim
479
+ if (depName.includes("@sigil-dev__grimoire")) {
480
+ return Response.redirect("/__grimoire__/grimoire-client.js", 302);
481
+ }
482
+
483
+ // convert URL-safe name back to package name
484
+ // @codex__shared → @codex/shared
485
+ const pkgName = depName.startsWith("@")
486
+ ? depName.replace("__", "/")
487
+ : depName;
488
+
489
+ const depsDir = join(process.cwd(), ".grimoire/deps");
490
+ mkdirSync(depsDir, { recursive: true });
491
+ const outFile = join(depsDir, `${depName}.js`);
492
+
493
+ if (!(await Bun.file(outFile).exists())) {
494
+ logger.debug("bundling dep:", pkgName);
495
+ try {
496
+ const entry = Bun.resolveSync(pkgName, process.cwd());
497
+ const result = await Bun.build({
498
+ entrypoints: [entry],
499
+ outdir: depsDir,
500
+ naming: `${depName}.js`,
501
+ target: "browser",
502
+ format: "esm",
503
+ minify: false,
504
+ external: ["@sigil-dev/runtime"],
505
+ });
506
+ if (!result.success) {
507
+ logger.error("dep bundle failed:", pkgName, result.logs);
508
+ return new Response(
509
+ `throw new Error("failed to bundle dep: ${pkgName}")`,
510
+ { headers: { "Content-Type": "application/javascript" } },
511
+ );
512
+ }
513
+ logger.debug("bundled dep:", pkgName);
514
+ } catch (e: any) {
515
+ return new Response(
516
+ `throw new Error("dep not found: ${pkgName}: ${e.message}")`,
517
+ { headers: { "Content-Type": "application/javascript" } },
518
+ );
519
+ }
520
+ }
521
+
522
+ return new Response(Bun.file(outFile), {
523
+ headers: {
524
+ "Content-Type": "application/javascript",
525
+ "Cache-Control": "no-store",
526
+ },
527
+ });
528
+ }
529
+
530
+ if (dev && url.pathname.startsWith("/__grimoire__/env/")) {
531
+ const specifier = `$env/${url.pathname.slice("/__grimoire__/env/".length).replace(/\.js$/, "")}`;
532
+ let js: string;
533
+ try {
534
+ js = envModuleSource(specifier, "browser");
535
+ } catch (e: unknown) {
536
+ const message = e instanceof Error ? e.message : String(e);
537
+ js = `throw new Error(${JSON.stringify(message)})`;
538
+ }
539
+ return new Response(js, {
540
+ headers: {
541
+ "Content-Type": "application/javascript",
542
+ "Cache-Control": "no-store",
543
+ },
544
+ });
545
+ }
546
+
547
+ if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
548
+ const clientPath = decodeURIComponent(
549
+ url.pathname.slice("/__grimoire__/m/".length),
550
+ );
551
+ const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
552
+ try {
553
+ // compiled at the module's current graph version, which is what
554
+ // the `?v=` in the URL was derived from
555
+ const { js } = await getDevModule(absPath, {
556
+ projectRoot: process.cwd(),
557
+ aliases,
558
+ graph,
559
+ });
560
+ return new Response(js, {
561
+ headers: {
562
+ "Content-Type": "application/javascript",
563
+ "Cache-Control": "no-store",
564
+ },
565
+ });
566
+ } catch (e: unknown) {
567
+ const message = e instanceof Error ? e.message : String(e);
568
+ return new Response(`throw new Error(${JSON.stringify(message)})`, {
569
+ headers: { "Content-Type": "application/javascript" },
570
+ });
571
+ }
572
+ }
573
+
574
+ // Static files are served BEFORE the plugin pipeline. A CSS file or
575
+ // an image has nothing to do with a plugin's onRequest hook, and
576
+ // running them through it costs a hook round-trip plus a stat on
577
+ // every asset request.
578
+ //
579
+ // Caching rule, decided per asset by servePublicAsset: the document
580
+ // is never cached, a content-addressed URL is immutable, and
581
+ // anything else revalidates against an ETag.
582
+ const staticAsset = await servePublicAsset(
583
+ url.pathname,
584
+ url.search,
585
+ req.headers.get("if-none-match"),
586
+ );
587
+ if (staticAsset) return staticAsset;
588
+
589
+ return runRequestHooks(plugins, req, async () => {
590
+ const HTTP_METHODS = [
591
+ "GET",
592
+ "POST",
593
+ "PUT",
594
+ "PATCH",
595
+ "DELETE",
596
+ "HEAD",
597
+ "OPTIONS",
598
+ ] as const;
599
+
600
+ // Build event BEFORE matching — handle() runs pre-match like SvelteKit
601
+ trackClientAddress(req, server);
602
+ const cookieHeader = req.headers.get("cookie") ?? "";
603
+ const cookies = createCookies(cookieHeader);
604
+ const setHeadersMap: Record<string, string> = {};
605
+
606
+ const event: RequestEvent = {
607
+ request: req,
608
+ url,
609
+ params: {},
610
+ locals,
611
+ cookies,
612
+ route: { id: "" },
613
+ fetch: globalThis.fetch,
614
+ setHeaders: (headers) => Object.assign(setHeadersMap, headers),
615
+ getClientAddress: () => clientAddressOf(req),
616
+ };
617
+
618
+ if (hooksHandleFetch) {
619
+ event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
620
+ const r = new Request(reqInfo, init);
621
+ return Promise.resolve(
622
+ hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
623
+ );
624
+ };
625
+ }
626
+ const patchedFetch: typeof fetch = (input, init) => {
627
+ const resolved =
628
+ typeof input === "string" && input.startsWith("/")
629
+ ? new URL(input, url.origin).toString()
630
+ : input;
631
+ return globalThis.fetch(resolved as any, init);
632
+ };
633
+ const resolve: ResolveFunction = async (evt) => {
634
+ // matching happens here — after handle() has run
635
+ let matched = matchRoute(tree, evt.url, paramMatcherFns);
636
+ if (!matched) {
637
+ // the nearest +error.tsx inside the layouts that cover the
638
+ // address, like a page whose load throws error(404)
639
+ return renderRoute(
640
+ matchNotFound(tree, evt.url),
641
+ evt.request,
642
+ tree.errors,
643
+ loader,
644
+ evt.locals,
645
+ plugins,
646
+ cspNonce,
647
+ dev,
648
+ patchedFetch,
649
+ );
650
+ }
651
+
652
+ // patch event with match results so handle() epilogue can read them
653
+ evt.params = matched.params;
654
+ evt.route = { id: matched.route.path };
655
+
656
+ // API routes (+server.ts)
657
+ if (matched.route.type === "server") {
658
+ const mod = await loader(matched.route.filePath);
659
+
660
+ const isWsUpgrade =
661
+ evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
662
+ if (isWsUpgrade && mod.websocket) {
663
+ let extraData: Record<string, unknown> = {};
664
+ if (mod.upgrade) {
665
+ try {
666
+ const result = await mod.upgrade({
667
+ request: evt.request,
668
+ params: matched.params,
669
+ url: evt.url,
670
+ locals: evt.locals,
671
+ });
672
+ if (result && typeof result === "object") extraData = result;
673
+ } catch {
674
+ return new Response("Upgrade Required", { status: 426 });
675
+ }
676
+ }
677
+ const wsData: _WsInternalData = {
678
+ params: matched.params,
679
+ __handler: mod.websocket,
680
+ ...extraData,
681
+ };
682
+ //@ts-expect-error i dont know what you are talking about please
683
+ if (server?.upgrade(req, { data: wsData })) {
684
+ return undefined as unknown as Response;
685
+ }
686
+ return new Response("Upgrade Required", { status: 426 });
687
+ }
688
+
689
+ const handler = mod[evt.request.method];
690
+ if (handler) {
691
+ try {
692
+ return await handler({
693
+ request: evt.request,
694
+ params: matched.params,
695
+ url: evt.url,
696
+ locals: evt.locals,
697
+ fetch: patchedFetch,
698
+ cookies,
699
+ setHeaders: (headers) => Object.assign(setHeadersMap, headers),
700
+ getClientAddress: () => clientAddressOf(evt.request),
701
+ });
702
+ } catch (e) {
703
+ // `throw redirect(303, "/login")` works here as in an action
704
+ if (isRedirectResult(e)) {
705
+ return new Response(null, {
706
+ status: e.status,
707
+ headers: { Location: e.location },
708
+ });
709
+ }
710
+ throw e;
711
+ }
712
+ }
713
+ // no handler for this method: a page at the same URL (say a
714
+ // chat page next to its WebSocket endpoint) takes the request
715
+ const page = matchRoute(
716
+ { ...tree, servers: [] },
717
+ evt.url,
718
+ paramMatcherFns,
719
+ );
720
+ if (!page) {
721
+ return new Response("Method Not Allowed", { status: 405 });
722
+ }
723
+ matched = page;
724
+ evt.params = page.params;
725
+ evt.route = { id: page.route.path };
726
+ }
727
+
728
+ // form actions (+page.server.ts)
729
+ if (
730
+ matched.pageServer &&
731
+ HTTP_METHODS.includes(evt.request.method as any)
732
+ ) {
733
+ const mod = await loader(matched.pageServer.filePath);
734
+
735
+ // named actions: ?/create dispatches export `create`. Only for
736
+ // non-GET requests: a GET must never run an action, or any link
737
+ // or <img> on another site could trigger one with the visitor's
738
+ // cookies and no CSRF check (GET skips it)
739
+ const isRead =
740
+ evt.request.method === "GET" || evt.request.method === "HEAD";
741
+ const actionName = isRead
742
+ ? undefined
743
+ : [...evt.url.searchParams.keys()]
744
+ .find((k) => k.startsWith("/"))
745
+ ?.slice(1);
746
+ // every other function export is callable by name, but the
747
+ // module's own hooks are not actions
748
+ const reserved =
749
+ actionName !== undefined && RESERVED_EXPORTS.has(actionName);
750
+ // reads render the page; an exported GET is not an action either
751
+ const handler =
752
+ reserved || isRead
753
+ ? undefined
754
+ : actionName
755
+ ? mod[actionName]
756
+ : mod[evt.request.method];
757
+ if (actionName && typeof handler !== "function") {
758
+ return new Response("Not Found", { status: 404 });
759
+ }
760
+
761
+ if (mod.csrf !== false && !isRead) {
762
+ const cookieToken = cookies.get("_csrf");
763
+ const formData = await evt.request
764
+ .clone()
765
+ .formData()
766
+ .catch(() => null);
767
+ const bodyToken = formData?.get("_csrf");
768
+ if (!cookieToken || cookieToken !== String(bodyToken)) {
769
+ return new Response("Forbidden", { status: 403 });
770
+ }
771
+ }
772
+ // enhance() submits with fetch, which follows a 303 on its own
773
+ // and can't read where it went; it asks for the outcome as JSON
774
+ // instead and navigates itself
775
+ const enhanced = evt.request.headers.get("x-grimoire-form") === "1";
776
+ if (handler) {
777
+ let result: any;
778
+ try {
779
+ result = await handler({
780
+ request: evt.request,
781
+ params: matched.params,
782
+ url: evt.url,
783
+ locals: evt.locals,
784
+ fetch: patchedFetch,
785
+ cookies,
786
+ getClientAddress: () => clientAddressOf(evt.request),
787
+ });
788
+ } catch (e) {
789
+ // A thrown Response is the reply, like a returned one: it
790
+ // used to fall through to the 500 path and be swallowed.
791
+ if (e instanceof Response) return e;
792
+ if (isRedirectResult(e)) {
793
+ if (enhanced) {
794
+ return Response.json({
795
+ type: "redirect",
796
+ status: e.status,
797
+ location: e.location,
798
+ });
799
+ }
800
+ return new Response(null, {
801
+ status: e.status,
802
+ headers: { Location: e.location },
803
+ });
804
+ }
805
+ if (isErrorResult(e)) {
806
+ const isApi =
807
+ enhanced ||
808
+ evt.request.headers
809
+ .get("accept")
810
+ ?.includes("application/json");
811
+ if (isApi) {
812
+ return Response.json(
813
+ { error: true, status: e.status, message: e.message },
814
+ { status: e.status },
815
+ );
816
+ }
817
+ const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
818
+ // no layoutPairs here: layout data comes from the load
819
+ // pipeline in renderRoute, which a form action bypasses —
820
+ // wrapping layouts without their data would crash them
821
+ return (
822
+ (await renderErrorPage(
823
+ tree.errors,
824
+ evt.url.pathname,
825
+ e.status,
826
+ e.message,
827
+ e,
828
+ loader,
829
+ { params: matched.params, nonceAttr, dev },
830
+ )) ??
831
+ new Response(e.message, { status: e.status, headers: TEXT })
832
+ );
833
+ }
834
+ throw e;
835
+ }
836
+
837
+ if (result instanceof Response) return result;
838
+
839
+ if (isFailResult(result)) {
840
+ if (enhanced) {
841
+ return Response.json(
842
+ { fail: true, status: result.status, data: result.data },
843
+ { status: result.status },
844
+ );
845
+ }
846
+ // a plain form post (no JavaScript): show the page again,
847
+ // with the failure as its `form` prop
848
+ return renderRoute(
849
+ matched,
850
+ evt.request,
851
+ tree.errors,
852
+ loader,
853
+ evt.locals,
854
+ plugins,
855
+ cspNonce,
856
+ dev,
857
+ patchedFetch,
858
+ { status: result.status, data: result.data },
859
+ );
860
+ }
861
+
862
+ const redirectTo =
863
+ result?.redirect ??
864
+ evt.request.headers.get("referer") ??
865
+ withBase("/");
866
+ if (enhanced) {
867
+ return Response.json({
868
+ type: "success",
869
+ location: redirectTo,
870
+ data: result ?? null,
871
+ });
872
+ }
873
+ return new Response(null, {
874
+ status: 303,
875
+ headers: { Location: redirectTo },
876
+ });
877
+ }
878
+ if (!actionName && !isRead) {
879
+ return new Response("Method Not Allowed", { status: 405 });
880
+ }
881
+ }
882
+
883
+ // page routes
884
+ const response = await renderRoute(
885
+ matched,
886
+ evt.request,
887
+ tree.errors,
888
+ loader,
889
+ evt.locals,
890
+ plugins,
891
+ cspNonce,
892
+ dev,
893
+ patchedFetch,
894
+ );
895
+
896
+ if (evt.request.headers.get("x-grimoire-navigate") === "1") {
897
+ return response;
898
+ }
899
+
900
+ // Streaming-safe rewrites first, then the buffered legacy hook.
901
+ const rewritten = await applyRewriters(response, plugins, {
902
+ route: matched.route,
903
+ request: evt.request,
904
+ params: matched.params,
905
+ data: undefined,
906
+ });
907
+ const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
908
+ if (!hasRenderPlugins) return rewritten;
909
+ let html = await rewritten.text();
910
+ for (const plugin of plugins) {
911
+ html =
912
+ (await plugin.onRouteRender?.(html, {
913
+ route: matched.route,
914
+ request: evt.request,
915
+ params: matched.params,
916
+ data: undefined,
917
+ })) ?? html;
918
+ }
919
+ // Carry the original headers over. Rebuilding with a fixed set
920
+ // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
921
+ // plugin silently broke form actions and cache correctness.
922
+ const headers = new Headers(rewritten.headers);
923
+ headers.set("Content-Type", "text/html");
924
+ return new Response(html, {
925
+ status: rewritten.status,
926
+ statusText: rewritten.statusText,
927
+ headers,
928
+ });
929
+ };
930
+
931
+ let response: Response;
932
+ try {
933
+ if (!hooksHandle) {
934
+ response = await resolve(event);
935
+ } else {
936
+ response = await hooksHandle({ event, resolve });
937
+ }
938
+ } catch (err) {
939
+ logger.error(
940
+ `${event.request.method} ${event.url.pathname} failed:`,
941
+ err,
942
+ );
943
+ await hooksHandleError?.({
944
+ error: err,
945
+ event,
946
+ status: 500,
947
+ message: "Internal Server Error",
948
+ });
949
+ // an unexpected error gets the nearest +error.tsx too, with a
950
+ // generic message: details stay in the log
951
+ try {
952
+ const page = await renderErrorPage(
953
+ tree.errors,
954
+ event.url.pathname,
955
+ 500,
956
+ "Internal Server Error",
957
+ process.env.NODE_ENV === "production" ? null : err,
958
+ loader,
959
+ { nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
960
+ );
961
+ if (page) return page;
962
+ } catch (pageErr) {
963
+ logger.error("+error.tsx failed while rendering an error:", pageErr);
964
+ }
965
+ const errorHtmlPath = `${process.cwd()}/error.html`;
966
+ try {
967
+ const errorFile = Bun.file(errorHtmlPath);
968
+ if (await errorFile.exists()) {
969
+ return new Response(errorFile, {
970
+ status: 500,
971
+ headers: { "Content-Type": "text/html" },
972
+ });
973
+ }
974
+ } catch {}
975
+ const message =
976
+ process.env.NODE_ENV === "production"
977
+ ? "Internal Server Error"
978
+ : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
979
+ return new Response(message, { status: 500, headers: TEXT });
980
+ }
981
+
982
+ const setCookieHeaders = cookies.toHeaders();
983
+ if (
984
+ !response ||
985
+ (setCookieHeaders.length === 0 &&
986
+ Object.keys(setHeadersMap).length === 0)
987
+ ) {
988
+ return response;
989
+ }
990
+ return withHeaders(
991
+ response,
992
+ Object.entries(setHeadersMap),
993
+ setCookieHeaders.map((sc) => ["Set-Cookie", sc] as [string, string]),
994
+ );
995
+ });
996
+ }
997
+
998
+ const websocket: ServerWebSocketHandlers = {
999
+ open(ws: ServerWebSocket<any>) {
1000
+ if (ws.data.__hmrClient) {
1001
+ hmr?.addClient(ws);
1002
+ return;
1003
+ }
1004
+ (ws.data as _WsInternalData).__handler?.open?.(ws);
1005
+ },
1006
+ message(ws: ServerWebSocket<any>, data: string | Buffer) {
1007
+ if (ws.data.__hmrClient) return;
1008
+ (ws.data as _WsInternalData).__handler?.message?.(ws, data);
1009
+ },
1010
+ close(ws: ServerWebSocket<any>, code: number, reason?: string) {
1011
+ if (ws.data.__hmrClient) {
1012
+ hmr?.removeClient(ws);
1013
+ return;
1014
+ }
1015
+ (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
1016
+ },
1017
+ drain(ws: ServerWebSocket<any>) {
1018
+ if (ws.data.__hmrClient) return;
1019
+ (ws.data as _WsInternalData).__handler?.drain?.(ws);
1020
+ },
1021
+ };
1022
+
1023
+ // Wrapping is what makes afterResponse() mean "after the response",
1024
+ // including for streaming responses: the tasks fire when the body
1025
+ // finishes, not when the handler returns.
1026
+ const fetchHandler = (req: Request) => withAfterResponse(req, handleRequest);
1027
+
1028
+ // Under a base, the request is stripped to a route path once, here, so
1029
+ // nothing past this point has to know about it.
1030
+ const fetchUnderBase = (req: Request): Promise<Response> | Response => {
1031
+ if (!appBase) return fetchHandler(req);
1032
+ const url = new URL(req.url);
1033
+ if (url.pathname === appBase) {
1034
+ return new Response(null, {
1035
+ status: 308,
1036
+ headers: { Location: `${appBase}/${url.search}` },
1037
+ });
1038
+ }
1039
+ const route = stripBase(url.pathname, appBase);
1040
+ if (route === null) {
1041
+ // dev modules import each other root-relative
1042
+ if (dev && url.pathname.startsWith("/__grimoire__/")) {
1043
+ return fetchHandler(req);
1044
+ }
1045
+ return new Response(outsideBaseMessage(url.pathname, appBase, dev), {
1046
+ status: 404,
1047
+ headers: { "Content-Type": "text/plain" },
1048
+ });
1049
+ }
1050
+ url.pathname = route;
1051
+ return fetchHandler(new Request(url, req));
1052
+ };
1053
+
1054
+ const preload = async () => {
1055
+ if (dev || finalConfig.warm?.preload === false) return;
1056
+ const files = [
1057
+ ...tree.routes,
1058
+ ...tree.layouts,
1059
+ ...tree.servers,
1060
+ ...tree.errors,
1061
+ ].map((rf: { filePath: string }) => rf.filePath);
1062
+ const t0 = performance.now();
1063
+ const loaded = await preloadModules(files, loader, (msg, err) =>
1064
+ logger.warn(msg, err),
1065
+ );
1066
+ logger.info(
1067
+ `preloaded ${loaded}/${new Set(files).size} route modules in ${Math.round(performance.now() - t0)}ms`,
1068
+ );
1069
+ };
1070
+
1071
+ return {
1072
+ fetch: fetchUnderBase,
1073
+ websocket,
1074
+ tree,
1075
+ matchers: paramMatcherFns,
1076
+ config: finalConfig,
1077
+ plugins,
1078
+ bind(s) {
1079
+ server = s;
1080
+ },
1081
+ preload,
1082
+ async close(reason = "shutdown", options) {
1083
+ await runHook(plugins, "onStop", reason);
1084
+ // Drain before stopping, so a task already registered for a response
1085
+ // that has been sent gets to finish rather than being killed with the
1086
+ // process. Bounded: a hung task must not block a deploy forever.
1087
+ await drainAfterResponse(options?.drainMs);
1088
+ },
1089
+ };
1090
+ }
1091
+
1092
+ export async function createServer(config: GrimoireConfig = {}) {
1093
+ const app = await createApp(config);
1094
+ const { plugins, config: finalConfig } = app;
1095
+ const { port = 3000, host = "localhost", dev = false } = finalConfig;
1096
+
1097
+ // Before the port opens, so the first visitor never pays for compiling a
1098
+ // route: a worker only reports ready once this has finished.
1099
+ await app.preload();
1100
+
1101
+ const server = Bun.serve({
1102
+ port,
1103
+ hostname: host,
1104
+ fetch: app.fetch,
1105
+ websocket: app.websocket,
1106
+ });
1107
+ app.bind(server);
1108
+
1109
+ const warmConfig = finalConfig.warm;
1110
+ let warmer: Warmer | null = null;
1111
+ if (!dev && warmConfig?.paths?.length) {
1112
+ warmer = startWarming({
1113
+ paths: warmConfig.paths,
1114
+ every: warmConfig.every,
1115
+ origin: `http://${host}:${server.port}`,
1116
+ headers: finalConfig._warmHeaders,
1117
+ handle: async (req) => app.fetch(req),
1118
+ log: (msg) => logger.info(msg),
1119
+ });
1120
+ }
1121
+
1122
+ let stopping = false;
1123
+ const handleShutdown = async () => {
1124
+ if (stopping) return;
1125
+ stopping = true;
1126
+ warmer?.stop();
1127
+ await app.close("shutdown");
1128
+ // stop(true), not stop(): the graceful form waits for open connections,
1129
+ // and a dev HMR websocket never closes on its own, so shutdown hangs.
1130
+ server.stop(true);
1131
+ process.exit(0);
1132
+ };
1133
+ process.on("SIGINT", handleShutdown);
1134
+ process.on("SIGTERM", handleShutdown);
1135
+
1136
+ await runHook(plugins, "onStart", server);
1137
+ return server;
1138
+ }