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