@sigil-dev/grimoire 0.9.6 → 0.9.7

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.
@@ -1,718 +1,723 @@
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
- // Carry the original headers over. Rebuilding with a fixed set
606
- // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
607
- // plugin silently broke form actions and cache correctness.
608
- const headers = new Headers(response.headers);
609
- headers.set("Content-Type", "text/html");
610
- return new Response(html, {
611
- status: response.status,
612
- statusText: response.statusText,
613
- headers,
614
- });
615
- }
616
-
617
- return response;
618
- };
619
-
620
- let response: Response;
621
- try {
622
- if (!hooksHandle) {
623
- response = await resolve(event);
624
- } else {
625
- response = await hooksHandle({ event, resolve });
626
- }
627
- } catch (err) {
628
- logger.error(
629
- `${event.request.method} ${event.url.pathname} failed:`,
630
- err,
631
- );
632
- await hooksHandleError?.({
633
- error: err,
634
- event,
635
- status: 500,
636
- message: "Internal Server Error",
637
- });
638
- const errorHtmlPath = `${process.cwd()}/error.html`;
639
- try {
640
- const errorFile = Bun.file(errorHtmlPath);
641
- if (await errorFile.exists()) {
642
- return new Response(errorFile, {
643
- status: 500,
644
- headers: { "Content-Type": "text/html" },
645
- });
646
- }
647
- } catch {}
648
- const message =
649
- process.env.NODE_ENV === "production"
650
- ? "Internal Server Error"
651
- : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
652
- return new Response(message, { status: 500 });
653
- }
654
-
655
- const setCookieHeaders = cookies.toHeaders();
656
- if (
657
- setCookieHeaders.length > 0 ||
658
- Object.keys(setHeadersMap).length > 0
659
- ) {
660
- const headers = new Headers(response.headers);
661
- for (const [k, v] of Object.entries(setHeadersMap)) {
662
- headers.set(k, v);
663
- }
664
- for (const sc of setCookieHeaders) {
665
- headers.append("Set-Cookie", sc);
666
- }
667
- response = new Response(response.body, {
668
- status: response.status,
669
- statusText: response.statusText,
670
- headers,
671
- });
672
- }
673
-
674
- return response;
675
- });
676
- },
677
- websocket: {
678
- open(ws: ServerWebSocket<any>) {
679
- if (ws.data.__hmrClient) {
680
- hmr?.addClient(ws);
681
- return;
682
- }
683
- (ws.data as _WsInternalData).__handler?.open?.(ws);
684
- },
685
- message(ws: ServerWebSocket<any>, data: string | Buffer) {
686
- if (ws.data.__hmrClient) return;
687
- (ws.data as _WsInternalData).__handler?.message?.(ws, data);
688
- },
689
- close(ws: ServerWebSocket<any>, code: number, reason?: string) {
690
- if (ws.data.__hmrClient) {
691
- hmr?.removeClient(ws);
692
- return;
693
- }
694
- (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
695
- },
696
- drain(ws: ServerWebSocket<any>) {
697
- if (ws.data.__hmrClient) return;
698
- (ws.data as _WsInternalData).__handler?.drain?.(ws);
699
- },
700
- },
701
- });
702
-
703
- let stopping = false;
704
- const handleShutdown = async () => {
705
- if (stopping) return;
706
- stopping = true;
707
- await runHook(plugins, "onStop", "shutdown");
708
- // stop(true), not stop(): the graceful form waits for open connections,
709
- // and a dev HMR websocket never closes on its own, so shutdown hangs.
710
- server.stop(true);
711
- process.exit(0);
712
- };
713
- process.on("SIGINT", handleShutdown);
714
- process.on("SIGTERM", handleShutdown);
715
-
716
- await runHook(plugins, "onStart", server);
717
- return server;
718
- }
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
+ fetch: patchedFetch,
475
+ cookies,
476
+ setHeaders: (headers) => Object.assign(setHeadersMap, headers),
477
+ });
478
+ }
479
+
480
+ // form actions (+page.server.ts)
481
+ if (
482
+ matched.pageServer &&
483
+ HTTP_METHODS.includes(evt.request.method as any)
484
+ ) {
485
+ const mod = await loader(matched.pageServer.filePath);
486
+
487
+ // named actions: ?/create dispatches export `create`
488
+ const actionName = [...evt.url.searchParams.keys()]
489
+ .find((k) => k.startsWith("/"))
490
+ ?.slice(1);
491
+ const handler = actionName
492
+ ? mod[actionName]
493
+ : mod[evt.request.method];
494
+ if (actionName && !handler) {
495
+ return new Response("Not Found", { status: 404 });
496
+ }
497
+
498
+ if (
499
+ mod.csrf !== false &&
500
+ evt.request.method !== "GET" &&
501
+ evt.request.method !== "HEAD"
502
+ ) {
503
+ const cookieToken = cookies.get("_csrf");
504
+ const formData = await evt.request
505
+ .clone()
506
+ .formData()
507
+ .catch(() => null);
508
+ const bodyToken = formData?.get("_csrf");
509
+ if (!cookieToken || cookieToken !== String(bodyToken)) {
510
+ return new Response("Forbidden", { status: 403 });
511
+ }
512
+ }
513
+ if (handler) {
514
+ let result: any;
515
+ try {
516
+ result = await handler({
517
+ request: evt.request,
518
+ params: matched.params,
519
+ url: evt.url,
520
+ locals: evt.locals,
521
+ fetch: patchedFetch,
522
+ cookies,
523
+ });
524
+ } catch (e) {
525
+ if (isRedirectResult(e)) {
526
+ return new Response(null, {
527
+ status: e.status,
528
+ headers: { Location: e.location },
529
+ });
530
+ }
531
+ if (isErrorResult(e)) {
532
+ const isApi = evt.request.headers
533
+ .get("accept")
534
+ ?.includes("application/json");
535
+ if (isApi) {
536
+ return Response.json(
537
+ { error: true, status: e.status, message: e.message },
538
+ { status: e.status },
539
+ );
540
+ }
541
+ const nonceAttr = cspNonce ? ` nonce="${cspNonce}"` : "";
542
+ // no layoutPairs here: layout data comes from the load
543
+ // pipeline in renderRoute, which a form action bypasses —
544
+ // wrapping layouts without their data would crash them
545
+ return (
546
+ (await renderErrorPage(
547
+ tree.errors,
548
+ evt.url.pathname,
549
+ e.status,
550
+ e.message,
551
+ e,
552
+ loader,
553
+ { params: matched.params, nonceAttr, dev },
554
+ )) ?? new Response(e.message, { status: e.status })
555
+ );
556
+ }
557
+ throw e;
558
+ }
559
+
560
+ if (isFailResult(result)) {
561
+ return Response.json(
562
+ { fail: true, status: result.status, data: result.data },
563
+ { status: result.status },
564
+ );
565
+ }
566
+
567
+ const redirectTo =
568
+ result?.redirect ?? evt.request.headers.get("referer") ?? "/";
569
+ return new Response(null, {
570
+ status: 303,
571
+ headers: { Location: redirectTo },
572
+ });
573
+ }
574
+ if (!actionName && evt.request.method !== "GET") {
575
+ return new Response("Method Not Allowed", { status: 405 });
576
+ }
577
+ }
578
+
579
+ // page routes
580
+ const response = await renderRoute(
581
+ matched,
582
+ evt.request,
583
+ tree.errors,
584
+ loader,
585
+ evt.locals,
586
+ plugins,
587
+ cspNonce,
588
+ dev,
589
+ patchedFetch,
590
+ );
591
+
592
+ if (evt.request.headers.get("x-grimoire-navigate") === "1") {
593
+ return response;
594
+ }
595
+
596
+ const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
597
+ if (hasRenderPlugins) {
598
+ let html = await response.text();
599
+ for (const plugin of plugins) {
600
+ html =
601
+ (await plugin.onRouteRender?.(html, {
602
+ route: matched.route,
603
+ request: evt.request,
604
+ params: matched.params,
605
+ data: undefined,
606
+ })) ?? html;
607
+ }
608
+ // Carry the original headers over. Rebuilding with a fixed set
609
+ // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
610
+ // plugin silently broke form actions and cache correctness.
611
+ const headers = new Headers(response.headers);
612
+ headers.set("Content-Type", "text/html");
613
+ return new Response(html, {
614
+ status: response.status,
615
+ statusText: response.statusText,
616
+ headers,
617
+ });
618
+ }
619
+
620
+ return response;
621
+ };
622
+
623
+ let response: Response;
624
+ try {
625
+ if (!hooksHandle) {
626
+ response = await resolve(event);
627
+ } else {
628
+ response = await hooksHandle({ event, resolve });
629
+ }
630
+ } catch (err) {
631
+ logger.error(
632
+ `${event.request.method} ${event.url.pathname} failed:`,
633
+ err,
634
+ );
635
+ await hooksHandleError?.({
636
+ error: err,
637
+ event,
638
+ status: 500,
639
+ message: "Internal Server Error",
640
+ });
641
+ const errorHtmlPath = `${process.cwd()}/error.html`;
642
+ try {
643
+ const errorFile = Bun.file(errorHtmlPath);
644
+ if (await errorFile.exists()) {
645
+ return new Response(errorFile, {
646
+ status: 500,
647
+ headers: { "Content-Type": "text/html" },
648
+ });
649
+ }
650
+ } catch {}
651
+ const message =
652
+ process.env.NODE_ENV === "production"
653
+ ? "Internal Server Error"
654
+ : `${err instanceof Error ? `${err.message}\n${err.stack}` : String(err)}`;
655
+ return new Response(message, { status: 500 });
656
+ }
657
+
658
+ const setCookieHeaders = cookies.toHeaders();
659
+ if (
660
+ !response ||
661
+ (setCookieHeaders.length === 0 &&
662
+ Object.keys(setHeadersMap).length === 0)
663
+ ) {
664
+ return response;
665
+ }
666
+ const headers = new Headers(response.headers);
667
+ for (const [k, v] of Object.entries(setHeadersMap)) {
668
+ headers.set(k, v);
669
+ }
670
+ for (const sc of setCookieHeaders) {
671
+ headers.append("Set-Cookie", sc);
672
+ }
673
+ response = new Response(response.body, {
674
+ status: response.status,
675
+ statusText: response.statusText,
676
+ headers,
677
+ });
678
+
679
+ return response;
680
+ });
681
+ },
682
+ websocket: {
683
+ open(ws: ServerWebSocket<any>) {
684
+ if (ws.data.__hmrClient) {
685
+ hmr?.addClient(ws);
686
+ return;
687
+ }
688
+ (ws.data as _WsInternalData).__handler?.open?.(ws);
689
+ },
690
+ message(ws: ServerWebSocket<any>, data: string | Buffer) {
691
+ if (ws.data.__hmrClient) return;
692
+ (ws.data as _WsInternalData).__handler?.message?.(ws, data);
693
+ },
694
+ close(ws: ServerWebSocket<any>, code: number, reason?: string) {
695
+ if (ws.data.__hmrClient) {
696
+ hmr?.removeClient(ws);
697
+ return;
698
+ }
699
+ (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
700
+ },
701
+ drain(ws: ServerWebSocket<any>) {
702
+ if (ws.data.__hmrClient) return;
703
+ (ws.data as _WsInternalData).__handler?.drain?.(ws);
704
+ },
705
+ },
706
+ });
707
+
708
+ let stopping = false;
709
+ const handleShutdown = async () => {
710
+ if (stopping) return;
711
+ stopping = true;
712
+ await runHook(plugins, "onStop", "shutdown");
713
+ // stop(true), not stop(): the graceful form waits for open connections,
714
+ // and a dev HMR websocket never closes on its own, so shutdown hangs.
715
+ server.stop(true);
716
+ process.exit(0);
717
+ };
718
+ process.on("SIGINT", handleShutdown);
719
+ process.on("SIGTERM", handleShutdown);
720
+
721
+ await runHook(plugins, "onStart", server);
722
+ return server;
723
+ }