@sigil-dev/grimoire 0.9.4 → 0.9.5

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 (78) hide show
  1. package/index.ts +37 -37
  2. package/package.json +3 -3
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +36 -36
  6. package/src/client/enhance.ts +102 -102
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +5 -5
  9. package/src/client/router.ts +42 -20
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +215 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +109 -114
  14. package/src/dev/hmr-client.ts +202 -185
  15. package/src/dev/hmr-server.ts +261 -187
  16. package/src/dev/loader.ts +120 -47
  17. package/src/dev/paths.ts +14 -14
  18. package/src/dev/resolve.ts +70 -0
  19. package/src/dev/runtime-bundle.ts +52 -52
  20. package/src/dev/scan.ts +78 -0
  21. package/src/dev/watcher.ts +69 -47
  22. package/src/env/dynamic-private.ts +19 -19
  23. package/src/env/dynamic-public.ts +22 -22
  24. package/src/env/index.ts +25 -25
  25. package/src/env/plugin.ts +19 -19
  26. package/src/env/private.ts +5 -5
  27. package/src/env/public.ts +7 -7
  28. package/src/env/typegen.ts +61 -61
  29. package/src/headers.ts +114 -114
  30. package/src/integrations/vite.ts +73 -73
  31. package/src/logger/index.ts +4 -4
  32. package/src/logger/instance.ts +6 -6
  33. package/src/logger/logger.ts +113 -113
  34. package/src/logger/request-middleware.ts +24 -24
  35. package/src/logger/transports.ts +117 -117
  36. package/src/logger/types.ts +39 -39
  37. package/src/rendering/head.ts +52 -47
  38. package/src/rendering/hydrate.ts +16 -3
  39. package/src/rendering/index.ts +10 -6
  40. package/src/rendering/ssrPlugin.ts +78 -69
  41. package/src/routing/manifest-gen.ts +55 -55
  42. package/src/routing/router.ts +135 -135
  43. package/src/routing/scanner.ts +196 -187
  44. package/src/routing/transform-routes.ts +102 -102
  45. package/src/sentinels/error.ts +52 -52
  46. package/src/sentinels/fail.ts +41 -41
  47. package/src/sentinels/redirect.ts +35 -35
  48. package/src/server/build.ts +250 -255
  49. package/src/server/context.ts +10 -10
  50. package/src/server/cookie-utils.ts +66 -66
  51. package/src/server/coordinator.ts +364 -364
  52. package/src/server/hooks.ts +114 -114
  53. package/src/server/index.ts +711 -677
  54. package/src/server/interactive.ts +56 -56
  55. package/src/server/plugins.ts +121 -121
  56. package/src/server/worker.ts +58 -58
  57. package/src/typegen/index.ts +389 -389
  58. package/src/types.ts +286 -286
  59. package/test/client-router.test.ts +295 -298
  60. package/test/context.test.ts +52 -52
  61. package/test/env.test.ts +90 -90
  62. package/test/exports.test.ts +37 -37
  63. package/test/fail.test.ts +46 -46
  64. package/test/headers.test.ts +100 -100
  65. package/test/hmr.test.ts +426 -0
  66. package/test/hydration.test.ts +119 -119
  67. package/test/middleware.test.ts +223 -223
  68. package/test/preload.ts +5 -5
  69. package/test/redirect-error.test.ts +112 -112
  70. package/test/rendering.test.ts +719 -728
  71. package/test/routing.test.ts +197 -194
  72. package/test/scanning.test.ts +314 -254
  73. package/test/scope.test.ts +195 -195
  74. package/test/server.test.ts +360 -354
  75. package/test/streaming.test.ts +242 -242
  76. package/test/transform-routes.test.ts +87 -87
  77. package/test/typegen.test.ts +697 -697
  78. package/tsconfig.json +10 -10
@@ -1,677 +1,711 @@
1
- import { mkdirSync } from "node:fs";
2
- import { dirname, isAbsolute, join } from "node:path";
3
- import { plugin as bunPlugin, type ServerWebSocket } from "bun";
4
- import { DevGraph } from "../dev/graph.ts";
5
- import { HMR_CLIENT_SOURCE } from "../dev/hmr-client.ts";
6
- import { HmrServer, handleChange } from "../dev/hmr-server.ts";
7
- import { makeDevLoader } from "../dev/loader.ts";
8
- import { startWatcher } from "../dev/watcher.ts";
9
- import { log } from "../logger/instance.ts";
10
- import { renderErrorPage, renderRoute } from "../rendering";
11
- import { registerSSRPlugin } from "../rendering/ssrPlugin";
12
- import { findClosestError, matchRoute } from "../routing/router";
13
- import { isErrorResult } from "../sentinels/error.ts";
14
- import { isFailResult } from "../sentinels/fail.ts";
15
- import { isRedirectResult } from "../sentinels/redirect.ts";
16
- import type { GrimoireConfig, WsRouteHandler } from "../types";
17
- import { buildProject } from "./build";
18
- import { createCookies } from "./cookie-utils";
19
- import type {
20
- Handle,
21
- HandleError,
22
- HandleFetch,
23
- InitFunction,
24
- RequestEvent,
25
- ResolveFunction,
26
- } from "./hooks";
27
- import { runDeserializeLocals, runHook, runRequestHooks } from "./plugins";
28
-
29
- const logger = log.scope("server");
30
- /**
31
- * Try to load hooks.server.ts from the project root.
32
- */
33
- async function loadHooks(projectRoot: string): Promise<{
34
- handle?: Handle;
35
- init?: InitFunction;
36
- handleError?: HandleError;
37
- handleFetch?: HandleFetch;
38
- }> {
39
- const hooksPath = `${projectRoot}/hooks.server.ts`;
40
- try {
41
- const mod = await import(hooksPath);
42
- return {
43
- handle: mod.handle,
44
- init: mod.init,
45
- handleError: mod.handleError,
46
- handleFetch: mod.handleFetch,
47
- };
48
- } catch {
49
- // no hooks file — that's fine
50
- return {};
51
- }
52
- }
53
-
54
- interface _WsInternalData {
55
- params: Record<string, string>;
56
- // always present at runtime — optional only to satisfy TypeScript;
57
- // upgrade block gates on mod.websocket before calling server.upgrade()
58
- __handler?: WsRouteHandler<any>;
59
- [key: string]: unknown;
60
- }
61
-
62
- export async function createServer(config: GrimoireConfig = {}) {
63
- // run config hooks
64
- let finalConfig = config;
65
- const earlyPlugins = config.plugins ?? [];
66
- for (const plugin of earlyPlugins) {
67
- finalConfig = plugin.config?.(finalConfig) ?? finalConfig;
68
- }
69
-
70
- const {
71
- port = 3000,
72
- host = "localhost",
73
- plugins = [],
74
- dev = false,
75
- routes = "src/routes",
76
- cspNonce,
77
- //biome-ignore lint: not implemented yet
78
- devEditor = "code",
79
- _skipBuild = false,
80
- } = finalConfig;
81
-
82
- let tree: any;
83
- if (!config._skipBuild) {
84
- const { result, tree: _tree } = await buildProject(finalConfig, plugins);
85
- if (!result.success) throw new Error("Grimoire: build failed");
86
- tree = _tree;
87
- } else {
88
- // worker — build already done by loom, just scan routes
89
- const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
90
- const { scanRoutes } = await import("../routing/scanner");
91
- tree = await scanRoutes(routesDir, process.cwd());
92
- }
93
-
94
- // SSR plugin should NOT INTNERCEPT FILES BUNDLEDFOR CLIENT
95
- // WHAT ARE WE DOINGGGGGGGGG
96
- registerSSRPlugin(plugins);
97
-
98
- const graph = new DevGraph();
99
- const hmr = dev ? new HmrServer() : null;
100
-
101
- if (dev) {
102
- const { ensureRuntimeBundle } = await import("../dev/runtime-bundle.ts");
103
- await ensureRuntimeBundle(process.cwd());
104
-
105
- // clean dev-modules cache from previous session
106
- const { rmSync, mkdirSync } = await import("node:fs");
107
- const devModulesDir = join(process.cwd(), ".grimoire/dev-modules");
108
- try {
109
- rmSync(devModulesDir, { recursive: true, force: true });
110
- } catch {}
111
- mkdirSync(devModulesDir, { recursive: true });
112
-
113
- // register route files and scan their imports for the graph
114
- const srcDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
115
- const allFiles = [
116
- ...tree.routes,
117
- ...tree.layouts,
118
- ...tree.servers,
119
- ...tree.errors,
120
- ];
121
-
122
- await Promise.all(
123
- allFiles.map(async (rf) => {
124
- graph.getOrCreate(rf.filePath, rf.filePath);
125
- graph.markRoute(rf.filePath, rf);
126
- try {
127
- const source = await Bun.file(rf.filePath).text();
128
- const imports = new Bun.Transpiler({ loader: "tsx" }).scanImports(
129
- source,
130
- );
131
- for (const imp of imports) {
132
- if (imp.path.startsWith(".") || imp.path.startsWith("$lib")) {
133
- const resolved = imp.path.startsWith("$lib")
134
- ? join(process.cwd(), "src/lib", imp.path.slice(5))
135
- : join(dirname(rf.filePath), imp.path);
136
- graph.addEdge(rf.filePath, resolved);
137
- // also register lib files as graph nodes
138
- graph.getOrCreate(resolved, resolved);
139
- }
140
- }
141
- } catch {}
142
- }),
143
- );
144
-
145
- startWatcher(srcDir, (f) =>
146
- handleChange(f, graph, hmr!, srcDir, process.cwd(), tree),
147
- );
148
- }
149
-
150
- const loader = dev
151
- ? makeDevLoader(graph, process.cwd())
152
- : (p: string) => import(p);
153
-
154
- // [param=matcher] validation — load src/params/*.ts once at startup
155
- const paramMatcherFns: Record<string, (value: string) => boolean> = {};
156
- for (const pm of tree.paramMatcherFiles ?? []) {
157
- try {
158
- const mod = await loader(pm.filePath);
159
- if (typeof mod.match === "function") {
160
- paramMatcherFns[pm.name] = mod.match;
161
- }
162
- } catch (e) {
163
- logger.warn(`failed to load param matcher "${pm.name}":`, e);
164
- }
165
- }
166
- // Load hooks.server.ts
167
- const {
168
- handle: hooksHandle,
169
- init: hooksInit,
170
- handleError: hooksHandleError,
171
- handleFetch: hooksHandleFetch,
172
- } = await loadHooks(process.cwd());
173
-
174
- // Run init hook if present
175
- await hooksInit?.();
176
-
177
- // Register alias plugin so dynamically-imported +server.ts routes can resolve custom aliases
178
- const aliases = finalConfig.alias ?? {};
179
- if (Object.keys(aliases).length > 0) {
180
- bunPlugin({
181
- name: "grimoire-alias",
182
- setup(build) {
183
- for (const [prefix, target] of Object.entries(aliases)) {
184
- const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
185
- build.onResolve(
186
- { filter: new RegExp(`^${escaped}(/|$)`) },
187
- (args) => ({
188
- path: args.path.replace(prefix, join(process.cwd(), target)),
189
- }),
190
- );
191
- }
192
- },
193
- });
194
- }
195
- const server = Bun.serve({
196
- port,
197
- hostname: host,
198
- fetch: async (req) => {
199
- const rawLocals = req.headers.get("X-Grimoire-Locals");
200
- const locals: App.Locals = rawLocals
201
- ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
202
- : {};
203
- const url = new URL(req.url);
204
-
205
- if (dev && url.pathname === "/__grimoire__/hmr") {
206
- //@ts-expect-error holy shut up
207
- if (server.upgrade(req, { data: { __hmrClient: true } })) {
208
- return undefined as unknown as Response;
209
- }
210
- return new Response("Upgrade Required", { status: 426 });
211
- }
212
- if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
213
- return new Response(HMR_CLIENT_SOURCE, {
214
- headers: { "Content-Type": "application/javascript" },
215
- });
216
- }
217
- if (dev && url.pathname === "/__grimoire__/open") {
218
- const file = url.searchParams.get("file") ?? "";
219
- const line = url.searchParams.get("line") ?? "1";
220
- const col = url.searchParams.get("col") ?? "1";
221
- const editor = finalConfig.devEditor ?? "code";
222
- //@ts-expect-error Bun spawn has werird types just shut up
223
- Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
224
- return new Response(null, { status: 204 });
225
- }
226
- if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
227
- const depName = decodeURIComponent(
228
- url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
229
- );
230
-
231
- // grimoire shim
232
- if (depName.includes("@sigil-dev__grimoire")) {
233
- return Response.redirect("/__grimoire__/grimoire-client.js", 302);
234
- }
235
-
236
- // convert URL-safe name back to package name
237
- // @codex__shared → @codex/shared
238
- const pkgName = depName.startsWith("@")
239
- ? depName.replace("__", "/")
240
- : depName;
241
-
242
- const depsDir = join(process.cwd(), ".grimoire/deps");
243
- mkdirSync(depsDir, { recursive: true });
244
- const outFile = join(depsDir, `${depName}.js`);
245
-
246
- if (!(await Bun.file(outFile).exists())) {
247
- logger.debug("bundling dep:", pkgName);
248
- try {
249
- const entry = Bun.resolveSync(pkgName, process.cwd());
250
- const result = await Bun.build({
251
- entrypoints: [entry],
252
- outdir: depsDir,
253
- naming: `${depName}.js`,
254
- target: "browser",
255
- format: "esm",
256
- minify: false,
257
- external: ["@sigil-dev/runtime"],
258
- });
259
- if (!result.success) {
260
- logger.error("dep bundle failed:", pkgName, result.logs);
261
- return new Response(
262
- `throw new Error("failed to bundle dep: ${pkgName}")`,
263
- { headers: { "Content-Type": "application/javascript" } },
264
- );
265
- }
266
- logger.debug("bundled dep:", pkgName);
267
- } catch (e: any) {
268
- return new Response(
269
- `throw new Error("dep not found: ${pkgName}: ${e.message}")`,
270
- { headers: { "Content-Type": "application/javascript" } },
271
- );
272
- }
273
- }
274
-
275
- return new Response(Bun.file(outFile), {
276
- headers: {
277
- "Content-Type": "application/javascript",
278
- "Cache-Control": "no-store",
279
- },
280
- });
281
- }
282
-
283
- if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
284
- const clientPath = decodeURIComponent(
285
- url.pathname.slice("/__grimoire__/m/".length),
286
- );
287
- const v = url.searchParams.get("v");
288
-
289
- if (v) {
290
- // versioned request — serve from dev-modules cache
291
- // find the cache file for this version
292
- const { createHash } = await import("node:crypto");
293
- const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
294
- const fileHash = createHash("md5")
295
- .update(absPath)
296
- .digest("hex")
297
- .slice(0, 8);
298
- const cachePath = join(
299
- process.cwd(),
300
- `.grimoire/dev-modules/${fileHash}_v${v}.js`,
301
- );
302
- const file = Bun.file(cachePath);
303
- if (await file.exists()) {
304
- return new Response(file, {
305
- headers: {
306
- "Content-Type": "application/javascript",
307
- "Cache-Control": "no-store",
308
- },
309
- });
310
- }
311
- }
312
-
313
- // unversioned or cache miss — compile on demand
314
- const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
315
- try {
316
- const { compileForBrowser } = await import("../dev/compile-module");
317
- const result = await compileForBrowser(absPath, process.cwd());
318
- return new Response(result.js, {
319
- headers: {
320
- "Content-Type": "application/javascript",
321
- "Cache-Control": "no-store",
322
- },
323
- });
324
- } catch (e: any) {
325
- return new Response(`throw new Error(${JSON.stringify(e.message)})`, {
326
- headers: { "Content-Type": "application/javascript" },
327
- });
328
- }
329
- }
330
-
331
- return runRequestHooks(plugins, req, async () => {
332
- const publicFile = Bun.file(`${process.cwd()}/public${url.pathname}`);
333
- if (await publicFile.exists()) {
334
- return new Response(publicFile);
335
- }
336
-
337
- const HTTP_METHODS = [
338
- "GET",
339
- "POST",
340
- "PUT",
341
- "PATCH",
342
- "DELETE",
343
- "HEAD",
344
- "OPTIONS",
345
- ] as const;
346
-
347
- // Build event BEFORE matching — handle() runs pre-match like SvelteKit
348
- const cookieHeader = req.headers.get("cookie") ?? "";
349
- const cookies = createCookies(cookieHeader);
350
- const setHeadersMap: Record<string, string> = {};
351
-
352
- const event: RequestEvent = {
353
- request: req,
354
- url,
355
- params: {},
356
- locals,
357
- cookies,
358
- route: { id: "" },
359
- fetch: globalThis.fetch,
360
- setHeaders: (headers) => Object.assign(setHeadersMap, headers),
361
- };
362
-
363
- if (hooksHandleFetch) {
364
- event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
365
- const r = new Request(reqInfo, init);
366
- return Promise.resolve(
367
- hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
368
- );
369
- };
370
- }
371
- const patchedFetch: typeof fetch = (input, init) => {
372
- const resolved =
373
- typeof input === "string" && input.startsWith("/")
374
- ? new URL(input, url.origin).toString()
375
- : input;
376
- return globalThis.fetch(resolved as any, init);
377
- };
378
- const resolve: ResolveFunction = async (evt) => {
379
- // matching happens here — after handle() has run
380
- const matched = matchRoute(tree, evt.url, paramMatcherFns);
381
- if (!matched) {
382
- const error = findClosestError(tree.errors, evt.url.pathname);
383
- if (error) {
384
- const mod = await loader(error.filePath);
385
- const html = mod.default({ status: 404, message: "Not Found" });
386
- return new Response(html, {
387
- status: 404,
388
- headers: { "Content-Type": "text/html" },
389
- });
390
- }
391
- return new Response("Not Found", { status: 404 });
392
- }
393
-
394
- // patch event with match results so handle() epilogue can read them
395
- evt.params = matched.params;
396
- evt.route = { id: matched.route.path };
397
-
398
- // API routes (+server.ts)
399
- if (matched.route.type === "server") {
400
- const mod = await loader(matched.route.filePath);
401
-
402
- const isWsUpgrade =
403
- evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
404
- if (isWsUpgrade && mod.websocket) {
405
- let extraData: Record<string, unknown> = {};
406
- if (mod.upgrade) {
407
- try {
408
- const result = await mod.upgrade({
409
- request: evt.request,
410
- params: matched.params,
411
- url: evt.url,
412
- locals: evt.locals,
413
- });
414
- if (result && typeof result === "object") extraData = result;
415
- } catch {
416
- return new Response("Upgrade Required", { status: 426 });
417
- }
418
- }
419
- const wsData: _WsInternalData = {
420
- params: matched.params,
421
- __handler: mod.websocket,
422
- ...extraData,
423
- };
424
- //@ts-expect-error i dont know what you are talking about please
425
- if (server.upgrade(req, { data: wsData })) {
426
- return undefined as unknown as Response;
427
- }
428
- return new Response("Upgrade Required", { status: 426 });
429
- }
430
-
431
- const handler = mod[evt.request.method];
432
- if (!handler) {
433
- return new Response("Method Not Allowed", { status: 405 });
434
- }
435
- return handler({
436
- request: evt.request,
437
- params: matched.params,
438
- url: evt.url,
439
- locals: evt.locals,
440
- });
441
- }
442
-
443
- // form actions (+page.server.ts)
444
- if (
445
- matched.pageServer &&
446
- HTTP_METHODS.includes(evt.request.method as any)
447
- ) {
448
- const mod = await loader(matched.pageServer.filePath);
449
-
450
- // named actions: ?/create dispatches export `create`
451
- const actionName = [...evt.url.searchParams.keys()]
452
- .find((k) => k.startsWith("/"))
453
- ?.slice(1);
454
- const handler = actionName
455
- ? mod[actionName]
456
- : mod[evt.request.method];
457
- if (actionName && !handler) {
458
- return new Response("Not Found", { status: 404 });
459
- }
460
-
461
- if (
462
- mod.csrf !== false &&
463
- evt.request.method !== "GET" &&
464
- evt.request.method !== "HEAD"
465
- ) {
466
- const cookieToken = cookies.get("_csrf");
467
- const formData = await evt.request
468
- .clone()
469
- .formData()
470
- .catch(() => null);
471
- const bodyToken = formData?.get("_csrf");
472
- if (!cookieToken || cookieToken !== String(bodyToken)) {
473
- return new Response("Forbidden", { status: 403 });
474
- }
475
- }
476
- if (handler) {
477
- let result: any;
478
- try {
479
- result = await handler({
480
- request: evt.request,
481
- params: matched.params,
482
- url: evt.url,
483
- locals: evt.locals,
484
- fetch: patchedFetch,
485
- cookies,
486
- });
487
- } catch (e) {
488
- if (isRedirectResult(e)) {
489
- return new Response(null, {
490
- status: e.status,
491
- headers: { Location: e.location },
492
- });
493
- }
494
- if (isErrorResult(e)) {
495
- const isApi = evt.request.headers
496
- .get("accept")
497
- ?.includes("application/json");
498
- if (isApi) {
499
- return Response.json(
500
- { error: true, status: e.status, message: e.message },
501
- { status: e.status },
502
- );
503
- }
504
- const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
505
- // no layoutPairs here: layout data comes from the load
506
- // pipeline in renderRoute, which a form action bypasses —
507
- // wrapping layouts without their data would crash them
508
- return (
509
- (await renderErrorPage(
510
- tree.errors,
511
- evt.url.pathname,
512
- e.status,
513
- e.message,
514
- e,
515
- loader,
516
- { params: matched.params, nonceAttr, dev },
517
- )) ?? new Response(e.message, { status: e.status })
518
- );
519
- }
520
- throw e;
521
- }
522
-
523
- if (isFailResult(result)) {
524
- return Response.json(
525
- { fail: true, status: result.status, data: result.data },
526
- { status: result.status },
527
- );
528
- }
529
-
530
- const redirectTo =
531
- result?.redirect ?? evt.request.headers.get("referer") ?? "/";
532
- return new Response(null, {
533
- status: 303,
534
- headers: { Location: redirectTo },
535
- });
536
- }
537
- if (!actionName && evt.request.method !== "GET") {
538
- return new Response("Method Not Allowed", { status: 405 });
539
- }
540
- }
541
-
542
- // page routes
543
- const response = await renderRoute(
544
- matched,
545
- evt.request,
546
- tree.errors,
547
- loader,
548
- evt.locals,
549
- plugins,
550
- cspNonce,
551
- dev,
552
- patchedFetch,
553
- );
554
-
555
- if (evt.request.headers.get("x-grimoire-navigate") === "1") {
556
- return response;
557
- }
558
-
559
- const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
560
- if (hasRenderPlugins) {
561
- let html = await response.text();
562
- for (const plugin of plugins) {
563
- html =
564
- (await plugin.onRouteRender?.(html, {
565
- route: matched.route,
566
- request: evt.request,
567
- params: matched.params,
568
- data: undefined,
569
- })) ?? html;
570
- }
571
- return new Response(html, {
572
- status: response.status,
573
- statusText: response.statusText,
574
- headers: { "Content-Type": "text/html" },
575
- });
576
- }
577
-
578
- return response;
579
- };
580
-
581
- let response: Response;
582
- try {
583
- if (!hooksHandle) {
584
- response = await resolve(event);
585
- } else {
586
- response = await hooksHandle({ event, resolve });
587
- }
588
- } catch (err) {
589
- logger.error(
590
- `${event.request.method} ${event.url.pathname} failed:`,
591
- err,
592
- );
593
- await hooksHandleError?.({
594
- error: err,
595
- event,
596
- status: 500,
597
- message: "Internal Server Error",
598
- });
599
- const errorHtmlPath = `${process.cwd()}/error.html`;
600
- try {
601
- const errorFile = Bun.file(errorHtmlPath);
602
- if (await errorFile.exists()) {
603
- return new Response(errorFile, {
604
- status: 500,
605
- headers: { "Content-Type": "text/html" },
606
- });
607
- }
608
- } catch {}
609
- const message =
610
- process.env.NODE_ENV === "production"
611
- ? "Internal Server Error"
612
- : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
613
- return new Response(message, { status: 500 });
614
- }
615
-
616
- const setCookieHeaders = cookies.toHeaders();
617
- if (
618
- setCookieHeaders.length > 0 ||
619
- Object.keys(setHeadersMap).length > 0
620
- ) {
621
- const headers = new Headers(response.headers);
622
- for (const [k, v] of Object.entries(setHeadersMap)) {
623
- headers.set(k, v);
624
- }
625
- for (const sc of setCookieHeaders) {
626
- headers.append("Set-Cookie", sc);
627
- }
628
- response = new Response(response.body, {
629
- status: response.status,
630
- statusText: response.statusText,
631
- headers,
632
- });
633
- }
634
-
635
- return response;
636
- });
637
- },
638
- websocket: {
639
- open(ws: ServerWebSocket<any>) {
640
- if (ws.data.__hmrClient) {
641
- hmr?.addClient(ws);
642
- return;
643
- }
644
- (ws.data as _WsInternalData).__handler?.open?.(ws);
645
- },
646
- message(ws: ServerWebSocket<any>, data: string | Buffer) {
647
- if (ws.data.__hmrClient) return;
648
- (ws.data as _WsInternalData).__handler?.message?.(ws, data);
649
- },
650
- close(ws: ServerWebSocket<any>, code: number, reason?: string) {
651
- if (ws.data.__hmrClient) {
652
- hmr?.removeClient(ws);
653
- return;
654
- }
655
- (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
656
- },
657
- drain(ws: ServerWebSocket<any>) {
658
- if (ws.data.__hmrClient) return;
659
- (ws.data as _WsInternalData).__handler?.drain?.(ws);
660
- },
661
- },
662
- });
663
-
664
- let stopping = false;
665
- const handleShutdown = async () => {
666
- if (stopping) return;
667
- stopping = true;
668
- await runHook(plugins, "onStop", "shutdown");
669
- server.stop();
670
- process.exit(0);
671
- };
672
- process.on("SIGINT", handleShutdown);
673
- process.on("SIGTERM", handleShutdown);
674
-
675
- await runHook(plugins, "onStart", server);
676
- return server;
677
- }
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 { log } from "../logger/instance.ts";
13
+ import { renderErrorPage, renderRoute } from "../rendering";
14
+ import { registerSSRPlugin } from "../rendering/ssrPlugin";
15
+ import { findClosestError, matchRoute } from "../routing/router";
16
+ import { isErrorResult } from "../sentinels/error.ts";
17
+ import { isFailResult } from "../sentinels/fail.ts";
18
+ import { isRedirectResult } from "../sentinels/redirect.ts";
19
+ import type { GrimoireConfig, WsRouteHandler } from "../types";
20
+ import { buildProject, rebuildClient } from "./build";
21
+ import { createCookies } from "./cookie-utils";
22
+ import type {
23
+ Handle,
24
+ HandleError,
25
+ HandleFetch,
26
+ InitFunction,
27
+ RequestEvent,
28
+ ResolveFunction,
29
+ } from "./hooks";
30
+ import { runDeserializeLocals, runHook, runRequestHooks } from "./plugins";
31
+
32
+ const logger = log.scope("server");
33
+
34
+ /**
35
+ * Directories to watch in dev. `src` covers components and libs that pages
36
+ * import; the routes directory is added separately when it lives outside it.
37
+ */
38
+ function watchRoots(projectRoot: string, routesDir: string): string[] {
39
+ const src = join(projectRoot, "src");
40
+ const roots = existsSync(src) ? [src] : [];
41
+ const key = normalizePath(routesDir);
42
+ if (
43
+ !roots.some(
44
+ (r) => key === normalizePath(r) || key.startsWith(`${normalizePath(r)}/`),
45
+ )
46
+ )
47
+ roots.push(routesDir);
48
+ return roots;
49
+ }
50
+ /**
51
+ * Try to load hooks.server.ts from the project root.
52
+ */
53
+ async function loadHooks(projectRoot: string): Promise<{
54
+ handle?: Handle;
55
+ init?: InitFunction;
56
+ handleError?: HandleError;
57
+ handleFetch?: HandleFetch;
58
+ }> {
59
+ const hooksPath = `${projectRoot}/hooks.server.ts`;
60
+ try {
61
+ const mod = await import(hooksPath);
62
+ return {
63
+ handle: mod.handle,
64
+ init: mod.init,
65
+ handleError: mod.handleError,
66
+ handleFetch: mod.handleFetch,
67
+ };
68
+ } catch {
69
+ // no hooks file — that's fine
70
+ return {};
71
+ }
72
+ }
73
+
74
+ interface _WsInternalData {
75
+ params: Record<string, string>;
76
+ // always present at runtime — optional only to satisfy TypeScript;
77
+ // upgrade block gates on mod.websocket before calling server.upgrade()
78
+ __handler?: WsRouteHandler<any>;
79
+ [key: string]: unknown;
80
+ }
81
+
82
+ export async function createServer(config: GrimoireConfig = {}) {
83
+ // run config hooks
84
+ let finalConfig = config;
85
+ const earlyPlugins = config.plugins ?? [];
86
+ for (const plugin of earlyPlugins) {
87
+ finalConfig = plugin.config?.(finalConfig) ?? finalConfig;
88
+ }
89
+
90
+ const {
91
+ port = 3000,
92
+ host = "localhost",
93
+ plugins = [],
94
+ dev = false,
95
+ routes = "src/routes",
96
+ cspNonce,
97
+ //biome-ignore lint: not implemented yet
98
+ devEditor = "code",
99
+ _skipBuild = false,
100
+ } = finalConfig;
101
+
102
+ let tree: any;
103
+ if (!config._skipBuild) {
104
+ const { result, tree: _tree } = await buildProject(finalConfig, plugins);
105
+ if (!result.success) throw new Error("Grimoire: build failed");
106
+ tree = _tree;
107
+ } else {
108
+ // worker — build already done by loom, just scan routes
109
+ const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
110
+ const { scanRoutes } = await import("../routing/scanner");
111
+ tree = await scanRoutes(routesDir, process.cwd());
112
+ }
113
+
114
+ // SSR plugin should NOT INTNERCEPT FILES BUNDLEDFOR CLIENT
115
+ // WHAT ARE WE DOINGGGGGGGGG
116
+ registerSSRPlugin(plugins);
117
+
118
+ const graph = new DevGraph();
119
+ const hmr = dev ? new HmrServer() : null;
120
+
121
+ const aliases = finalConfig.alias ?? {};
122
+
123
+ if (dev) {
124
+ const { ensureRuntimeBundle } = await import("../dev/runtime-bundle.ts");
125
+ await ensureRuntimeBundle(process.cwd());
126
+
127
+ // clean dev-modules cache from previous session
128
+ const { rmSync, mkdirSync } = await import("node:fs");
129
+ const devModulesDir = join(process.cwd(), ".grimoire/dev-modules");
130
+ try {
131
+ rmSync(devModulesDir, { recursive: true, force: true });
132
+ } catch {}
133
+ mkdirSync(devModulesDir, { recursive: true });
134
+
135
+ const scanCtx = { graph, projectRoot: process.cwd(), aliases };
136
+ const entryFiles = () => {
137
+ const all = [
138
+ ...tree.routes,
139
+ ...tree.layouts,
140
+ ...tree.servers,
141
+ ...tree.errors,
142
+ ];
143
+ for (const rf of all) {
144
+ graph.getOrCreate(rf.filePath, rf.filePath);
145
+ graph.markRoute(rf.filePath, rf);
146
+ }
147
+ return all.map((rf) => rf.filePath);
148
+ };
149
+
150
+ // crawl the whole import graph, not just each route's direct imports:
151
+ // an edit is traced back to the routes that render it through however
152
+ // many component hops lie between
153
+ await crawlFrom(entryFiles(), scanCtx);
154
+
155
+ const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
156
+
157
+ // one rebuild at a time; saves that land during a build fold into one
158
+ // follow-up pass instead of queueing a Bun.build each
159
+ let rebuilding: Promise<void> | null = null;
160
+ let rebuildQueued = false;
161
+ const runRebuild = (): Promise<void> => {
162
+ if (rebuilding) {
163
+ rebuildQueued = true;
164
+ return rebuilding;
165
+ }
166
+ rebuilding = (async () => {
167
+ do {
168
+ rebuildQueued = false;
169
+ const { result, tree: rescanned } = await rebuildClient(
170
+ finalConfig,
171
+ plugins,
172
+ );
173
+ if (!result.success) {
174
+ logger.error("client rebuild failed:", result.errors.join("\n"));
175
+ break;
176
+ }
177
+ // adopt the rescanned tree so routes added since startup match
178
+ tree = rescanned;
179
+ await crawlFrom(entryFiles(), scanCtx);
180
+ } while (rebuildQueued);
181
+ })().finally(() => {
182
+ rebuilding = null;
183
+ });
184
+ return rebuilding;
185
+ };
186
+
187
+ const devCtx: DevContext = {
188
+ graph,
189
+ hmr: hmr!,
190
+ projectRoot: process.cwd(),
191
+ aliases,
192
+ entries: entryFiles,
193
+ rebuild: runRebuild,
194
+ scheduleRebuild: () => {
195
+ runRebuild().catch((e: unknown) =>
196
+ logger.error("client rebuild failed:", e),
197
+ );
198
+ },
199
+ };
200
+
201
+ startWatcher(watchRoots(process.cwd(), routesDir), (f) =>
202
+ handleChange(f, devCtx),
203
+ );
204
+ }
205
+
206
+ const loader = dev
207
+ ? makeDevLoader(graph, process.cwd(), { aliases })
208
+ : (p: string) => import(p);
209
+
210
+ // [param=matcher] validation — load src/params/*.ts once at startup
211
+ const paramMatcherFns: Record<string, (value: string) => boolean> = {};
212
+ for (const pm of tree.paramMatcherFiles ?? []) {
213
+ try {
214
+ const mod = await loader(pm.filePath);
215
+ if (typeof mod.match === "function") {
216
+ paramMatcherFns[pm.name] = mod.match;
217
+ }
218
+ } catch (e) {
219
+ logger.warn(`failed to load param matcher "${pm.name}":`, e);
220
+ }
221
+ }
222
+ // Load hooks.server.ts
223
+ const {
224
+ handle: hooksHandle,
225
+ init: hooksInit,
226
+ handleError: hooksHandleError,
227
+ handleFetch: hooksHandleFetch,
228
+ } = await loadHooks(process.cwd());
229
+
230
+ // Run init hook if present
231
+ await hooksInit?.();
232
+
233
+ // Register alias plugin so dynamically-imported +server.ts routes can resolve custom aliases
234
+ if (Object.keys(aliases).length > 0) {
235
+ bunPlugin({
236
+ name: "grimoire-alias",
237
+ setup(build) {
238
+ for (const [prefix, target] of Object.entries(aliases)) {
239
+ const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
240
+ build.onResolve(
241
+ { filter: new RegExp(`^${escaped}(/|$)`) },
242
+ (args) => ({
243
+ path: args.path.replace(prefix, join(process.cwd(), target)),
244
+ }),
245
+ );
246
+ }
247
+ },
248
+ });
249
+ }
250
+ const server = Bun.serve({
251
+ port,
252
+ hostname: host,
253
+ fetch: async (req) => {
254
+ const rawLocals = req.headers.get("X-Grimoire-Locals");
255
+ const locals: App.Locals = rawLocals
256
+ ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
257
+ : {};
258
+ const url = new URL(req.url);
259
+
260
+ if (dev && url.pathname === "/__grimoire__/hmr") {
261
+ //@ts-expect-error holy shut up
262
+ if (server.upgrade(req, { data: { __hmrClient: true } })) {
263
+ return undefined as unknown as Response;
264
+ }
265
+ return new Response("Upgrade Required", { status: 426 });
266
+ }
267
+ if (dev && url.pathname === "/__grimoire__/hmr-client.js") {
268
+ return new Response(HMR_CLIENT_SOURCE, {
269
+ headers: { "Content-Type": "application/javascript" },
270
+ });
271
+ }
272
+ if (dev && url.pathname === "/__grimoire__/open") {
273
+ const file = url.searchParams.get("file") ?? "";
274
+ const line = url.searchParams.get("line") ?? "1";
275
+ const col = url.searchParams.get("col") ?? "1";
276
+ const editor = finalConfig.devEditor ?? "code";
277
+ //@ts-expect-error Bun spawn has werird types just shut up
278
+ Bun.spawn([editor, "--goto", `${file}:${line}:${col}`]);
279
+ return new Response(null, { status: 204 });
280
+ }
281
+ if (dev && url.pathname.startsWith("/__grimoire__/dep/")) {
282
+ const depName = decodeURIComponent(
283
+ url.pathname.slice("/__grimoire__/dep/".length).replace(/\.js$/, ""),
284
+ );
285
+
286
+ // grimoire shim
287
+ if (depName.includes("@sigil-dev__grimoire")) {
288
+ return Response.redirect("/__grimoire__/grimoire-client.js", 302);
289
+ }
290
+
291
+ // convert URL-safe name back to package name
292
+ // @codex__shared → @codex/shared
293
+ const pkgName = depName.startsWith("@")
294
+ ? depName.replace("__", "/")
295
+ : depName;
296
+
297
+ const depsDir = join(process.cwd(), ".grimoire/deps");
298
+ mkdirSync(depsDir, { recursive: true });
299
+ const outFile = join(depsDir, `${depName}.js`);
300
+
301
+ if (!(await Bun.file(outFile).exists())) {
302
+ logger.debug("bundling dep:", pkgName);
303
+ try {
304
+ const entry = Bun.resolveSync(pkgName, process.cwd());
305
+ const result = await Bun.build({
306
+ entrypoints: [entry],
307
+ outdir: depsDir,
308
+ naming: `${depName}.js`,
309
+ target: "browser",
310
+ format: "esm",
311
+ minify: false,
312
+ external: ["@sigil-dev/runtime"],
313
+ });
314
+ if (!result.success) {
315
+ logger.error("dep bundle failed:", pkgName, result.logs);
316
+ return new Response(
317
+ `throw new Error("failed to bundle dep: ${pkgName}")`,
318
+ { headers: { "Content-Type": "application/javascript" } },
319
+ );
320
+ }
321
+ logger.debug("bundled dep:", pkgName);
322
+ } catch (e: any) {
323
+ return new Response(
324
+ `throw new Error("dep not found: ${pkgName}: ${e.message}")`,
325
+ { headers: { "Content-Type": "application/javascript" } },
326
+ );
327
+ }
328
+ }
329
+
330
+ return new Response(Bun.file(outFile), {
331
+ headers: {
332
+ "Content-Type": "application/javascript",
333
+ "Cache-Control": "no-store",
334
+ },
335
+ });
336
+ }
337
+
338
+ if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
339
+ const clientPath = decodeURIComponent(
340
+ url.pathname.slice("/__grimoire__/m/".length),
341
+ );
342
+ const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
343
+ try {
344
+ // compiled at the module's current graph version, which is what
345
+ // the `?v=` in the URL was derived from
346
+ const { js } = await getDevModule(absPath, {
347
+ projectRoot: process.cwd(),
348
+ aliases,
349
+ graph,
350
+ });
351
+ return new Response(js, {
352
+ headers: {
353
+ "Content-Type": "application/javascript",
354
+ "Cache-Control": "no-store",
355
+ },
356
+ });
357
+ } catch (e: unknown) {
358
+ const message = e instanceof Error ? e.message : String(e);
359
+ return new Response(`throw new Error(${JSON.stringify(message)})`, {
360
+ headers: { "Content-Type": "application/javascript" },
361
+ });
362
+ }
363
+ }
364
+
365
+ return runRequestHooks(plugins, req, async () => {
366
+ const publicFile = Bun.file(`${process.cwd()}/public${url.pathname}`);
367
+ if (await publicFile.exists()) {
368
+ return new Response(publicFile);
369
+ }
370
+
371
+ const HTTP_METHODS = [
372
+ "GET",
373
+ "POST",
374
+ "PUT",
375
+ "PATCH",
376
+ "DELETE",
377
+ "HEAD",
378
+ "OPTIONS",
379
+ ] as const;
380
+
381
+ // Build event BEFORE matching — handle() runs pre-match like SvelteKit
382
+ const cookieHeader = req.headers.get("cookie") ?? "";
383
+ const cookies = createCookies(cookieHeader);
384
+ const setHeadersMap: Record<string, string> = {};
385
+
386
+ const event: RequestEvent = {
387
+ request: req,
388
+ url,
389
+ params: {},
390
+ locals,
391
+ cookies,
392
+ route: { id: "" },
393
+ fetch: globalThis.fetch,
394
+ setHeaders: (headers) => Object.assign(setHeadersMap, headers),
395
+ };
396
+
397
+ if (hooksHandleFetch) {
398
+ event.fetch = (reqInfo: RequestInfo | URL, init?: RequestInit) => {
399
+ const r = new Request(reqInfo, init);
400
+ return Promise.resolve(
401
+ hooksHandleFetch({ request: r, fetch: globalThis.fetch, event }),
402
+ );
403
+ };
404
+ }
405
+ const patchedFetch: typeof fetch = (input, init) => {
406
+ const resolved =
407
+ typeof input === "string" && input.startsWith("/")
408
+ ? new URL(input, url.origin).toString()
409
+ : input;
410
+ return globalThis.fetch(resolved as any, init);
411
+ };
412
+ const resolve: ResolveFunction = async (evt) => {
413
+ // matching happens here — after handle() has run
414
+ const matched = matchRoute(tree, evt.url, paramMatcherFns);
415
+ if (!matched) {
416
+ const error = findClosestError(tree.errors, evt.url.pathname);
417
+ if (error) {
418
+ const mod = await loader(error.filePath);
419
+ const html = mod.default({ status: 404, message: "Not Found" });
420
+ return new Response(html, {
421
+ status: 404,
422
+ headers: { "Content-Type": "text/html" },
423
+ });
424
+ }
425
+ return new Response("Not Found", { status: 404 });
426
+ }
427
+
428
+ // patch event with match results so handle() epilogue can read them
429
+ evt.params = matched.params;
430
+ evt.route = { id: matched.route.path };
431
+
432
+ // API routes (+server.ts)
433
+ if (matched.route.type === "server") {
434
+ const mod = await loader(matched.route.filePath);
435
+
436
+ const isWsUpgrade =
437
+ evt.request.headers.get("upgrade")?.toLowerCase() === "websocket";
438
+ if (isWsUpgrade && mod.websocket) {
439
+ let extraData: Record<string, unknown> = {};
440
+ if (mod.upgrade) {
441
+ try {
442
+ const result = await mod.upgrade({
443
+ request: evt.request,
444
+ params: matched.params,
445
+ url: evt.url,
446
+ locals: evt.locals,
447
+ });
448
+ if (result && typeof result === "object") extraData = result;
449
+ } catch {
450
+ return new Response("Upgrade Required", { status: 426 });
451
+ }
452
+ }
453
+ const wsData: _WsInternalData = {
454
+ params: matched.params,
455
+ __handler: mod.websocket,
456
+ ...extraData,
457
+ };
458
+ //@ts-expect-error i dont know what you are talking about please
459
+ if (server.upgrade(req, { data: wsData })) {
460
+ return undefined as unknown as Response;
461
+ }
462
+ return new Response("Upgrade Required", { status: 426 });
463
+ }
464
+
465
+ const handler = mod[evt.request.method];
466
+ if (!handler) {
467
+ return new Response("Method Not Allowed", { status: 405 });
468
+ }
469
+ return handler({
470
+ request: evt.request,
471
+ params: matched.params,
472
+ url: evt.url,
473
+ locals: evt.locals,
474
+ });
475
+ }
476
+
477
+ // form actions (+page.server.ts)
478
+ if (
479
+ matched.pageServer &&
480
+ HTTP_METHODS.includes(evt.request.method as any)
481
+ ) {
482
+ const mod = await loader(matched.pageServer.filePath);
483
+
484
+ // named actions: ?/create dispatches export `create`
485
+ const actionName = [...evt.url.searchParams.keys()]
486
+ .find((k) => k.startsWith("/"))
487
+ ?.slice(1);
488
+ const handler = actionName
489
+ ? mod[actionName]
490
+ : mod[evt.request.method];
491
+ if (actionName && !handler) {
492
+ return new Response("Not Found", { status: 404 });
493
+ }
494
+
495
+ if (
496
+ mod.csrf !== false &&
497
+ evt.request.method !== "GET" &&
498
+ evt.request.method !== "HEAD"
499
+ ) {
500
+ const cookieToken = cookies.get("_csrf");
501
+ const formData = await evt.request
502
+ .clone()
503
+ .formData()
504
+ .catch(() => null);
505
+ const bodyToken = formData?.get("_csrf");
506
+ if (!cookieToken || cookieToken !== String(bodyToken)) {
507
+ return new Response("Forbidden", { status: 403 });
508
+ }
509
+ }
510
+ if (handler) {
511
+ let result: any;
512
+ try {
513
+ result = await handler({
514
+ request: evt.request,
515
+ params: matched.params,
516
+ url: evt.url,
517
+ locals: evt.locals,
518
+ fetch: patchedFetch,
519
+ cookies,
520
+ });
521
+ } catch (e) {
522
+ if (isRedirectResult(e)) {
523
+ return new Response(null, {
524
+ status: e.status,
525
+ headers: { Location: e.location },
526
+ });
527
+ }
528
+ if (isErrorResult(e)) {
529
+ const isApi = evt.request.headers
530
+ .get("accept")
531
+ ?.includes("application/json");
532
+ if (isApi) {
533
+ return Response.json(
534
+ { error: true, status: e.status, message: e.message },
535
+ { status: e.status },
536
+ );
537
+ }
538
+ const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
539
+ // no layoutPairs here: layout data comes from the load
540
+ // pipeline in renderRoute, which a form action bypasses —
541
+ // wrapping layouts without their data would crash them
542
+ return (
543
+ (await renderErrorPage(
544
+ tree.errors,
545
+ evt.url.pathname,
546
+ e.status,
547
+ e.message,
548
+ e,
549
+ loader,
550
+ { params: matched.params, nonceAttr, dev },
551
+ )) ?? new Response(e.message, { status: e.status })
552
+ );
553
+ }
554
+ throw e;
555
+ }
556
+
557
+ if (isFailResult(result)) {
558
+ return Response.json(
559
+ { fail: true, status: result.status, data: result.data },
560
+ { status: result.status },
561
+ );
562
+ }
563
+
564
+ const redirectTo =
565
+ result?.redirect ?? evt.request.headers.get("referer") ?? "/";
566
+ return new Response(null, {
567
+ status: 303,
568
+ headers: { Location: redirectTo },
569
+ });
570
+ }
571
+ if (!actionName && evt.request.method !== "GET") {
572
+ return new Response("Method Not Allowed", { status: 405 });
573
+ }
574
+ }
575
+
576
+ // page routes
577
+ const response = await renderRoute(
578
+ matched,
579
+ evt.request,
580
+ tree.errors,
581
+ loader,
582
+ evt.locals,
583
+ plugins,
584
+ cspNonce,
585
+ dev,
586
+ patchedFetch,
587
+ );
588
+
589
+ if (evt.request.headers.get("x-grimoire-navigate") === "1") {
590
+ return response;
591
+ }
592
+
593
+ const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
594
+ if (hasRenderPlugins) {
595
+ let html = await response.text();
596
+ for (const plugin of plugins) {
597
+ html =
598
+ (await plugin.onRouteRender?.(html, {
599
+ route: matched.route,
600
+ request: evt.request,
601
+ params: matched.params,
602
+ data: undefined,
603
+ })) ?? html;
604
+ }
605
+ return new Response(html, {
606
+ status: response.status,
607
+ statusText: response.statusText,
608
+ headers: { "Content-Type": "text/html" },
609
+ });
610
+ }
611
+
612
+ return response;
613
+ };
614
+
615
+ let response: Response;
616
+ try {
617
+ if (!hooksHandle) {
618
+ response = await resolve(event);
619
+ } else {
620
+ response = await hooksHandle({ event, resolve });
621
+ }
622
+ } catch (err) {
623
+ logger.error(
624
+ `${event.request.method} ${event.url.pathname} failed:`,
625
+ err,
626
+ );
627
+ await hooksHandleError?.({
628
+ error: err,
629
+ event,
630
+ status: 500,
631
+ message: "Internal Server Error",
632
+ });
633
+ const errorHtmlPath = `${process.cwd()}/error.html`;
634
+ try {
635
+ const errorFile = Bun.file(errorHtmlPath);
636
+ if (await errorFile.exists()) {
637
+ return new Response(errorFile, {
638
+ status: 500,
639
+ headers: { "Content-Type": "text/html" },
640
+ });
641
+ }
642
+ } catch {}
643
+ const message =
644
+ process.env.NODE_ENV === "production"
645
+ ? "Internal Server Error"
646
+ : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
647
+ return new Response(message, { status: 500 });
648
+ }
649
+
650
+ const setCookieHeaders = cookies.toHeaders();
651
+ if (
652
+ setCookieHeaders.length > 0 ||
653
+ Object.keys(setHeadersMap).length > 0
654
+ ) {
655
+ const headers = new Headers(response.headers);
656
+ for (const [k, v] of Object.entries(setHeadersMap)) {
657
+ headers.set(k, v);
658
+ }
659
+ for (const sc of setCookieHeaders) {
660
+ headers.append("Set-Cookie", sc);
661
+ }
662
+ response = new Response(response.body, {
663
+ status: response.status,
664
+ statusText: response.statusText,
665
+ headers,
666
+ });
667
+ }
668
+
669
+ return response;
670
+ });
671
+ },
672
+ websocket: {
673
+ open(ws: ServerWebSocket<any>) {
674
+ if (ws.data.__hmrClient) {
675
+ hmr?.addClient(ws);
676
+ return;
677
+ }
678
+ (ws.data as _WsInternalData).__handler?.open?.(ws);
679
+ },
680
+ message(ws: ServerWebSocket<any>, data: string | Buffer) {
681
+ if (ws.data.__hmrClient) return;
682
+ (ws.data as _WsInternalData).__handler?.message?.(ws, data);
683
+ },
684
+ close(ws: ServerWebSocket<any>, code: number, reason?: string) {
685
+ if (ws.data.__hmrClient) {
686
+ hmr?.removeClient(ws);
687
+ return;
688
+ }
689
+ (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
690
+ },
691
+ drain(ws: ServerWebSocket<any>) {
692
+ if (ws.data.__hmrClient) return;
693
+ (ws.data as _WsInternalData).__handler?.drain?.(ws);
694
+ },
695
+ },
696
+ });
697
+
698
+ let stopping = false;
699
+ const handleShutdown = async () => {
700
+ if (stopping) return;
701
+ stopping = true;
702
+ await runHook(plugins, "onStop", "shutdown");
703
+ server.stop();
704
+ process.exit(0);
705
+ };
706
+ process.on("SIGINT", handleShutdown);
707
+ process.on("SIGTERM", handleShutdown);
708
+
709
+ await runHook(plugins, "onStart", server);
710
+ return server;
711
+ }