@sigil-dev/grimoire 0.9.21 → 0.9.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +22 -10
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +871 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -105
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -749
  28. package/src/rendering/preload.ts +102 -101
  29. package/src/rendering/ssrPlugin.ts +1 -1
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -206
  35. package/src/server/asset-cache.ts +57 -57
  36. package/src/server/build.ts +262 -262
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -44
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +211 -80
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -27
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -132
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -101
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +1 -1
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +799 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +381 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +808 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +1 -1
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
@@ -1,122 +1,122 @@
1
- /**
2
- * SvelteKit-style server hooks.
3
- *
4
- * Create a hooks.server.ts in your project root:
5
- *
6
- * import type { Handle } from "@sigil-dev/grimoire/hooks";
7
- *
8
- * export const handle: Handle = async ({ event, resolve }) => {
9
- * event.locals.user = await getUser(event.cookies.get("session"));
10
- * const response = await resolve(event);
11
- * response.headers.set("x-custom", "value");
12
- * return response;
13
- * };
14
- *
15
- * export const handleError: HandleError = ({ error, status, message }) => {
16
- * console.error(`[${status}] ${message}`, error);
17
- * };
18
- *
19
- * // optional: runs once at server start
20
- * export const init = () => {
21
- * console.log("Server started");
22
- * };
23
- *
24
- * Chain multiple handlers with sequence():
25
- *
26
- * import { sequence } from "@sigil-dev/grimoire/hooks";
27
- * import { logger } from "./hooks/logger";
28
- * import { auth } from "./hooks/auth";
29
- *
30
- * export const handle = sequence(logger, auth);
31
- */
32
-
33
- export type MaybePromise<T> = T | Promise<T>;
34
-
35
- export interface RequestEvent {
36
- request: Request;
37
- url: URL;
38
- params: Record<string, string>;
39
- locals: App.Locals;
40
- cookies: Cookies;
41
- route: { id: string };
42
- fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
43
- setHeaders: (headers: Record<string, string>) => void;
44
- /**
45
- * The visitor's IP address. Behind a reverse proxy on the same machine or
46
- * network, it is the address the proxy reports; a visitor connecting
47
- * directly cannot claim another one.
48
- */
49
- getClientAddress: () => string;
50
- }
51
-
52
- export interface Cookies {
53
- get(name: string): string | undefined;
54
- /** Path defaults to "/". */
55
- set(name: string, value: string, options?: CookieOptions): void;
56
- /** Pass the path and domain the cookie was set with; path defaults to "/". */
57
- delete(name: string, options?: Pick<CookieOptions, "path" | "domain">): void;
58
- }
59
-
60
- export interface CookieOptions {
61
- path?: string;
62
- domain?: string;
63
- maxAge?: number;
64
- expires?: Date;
65
- httpOnly?: boolean;
66
- secure?: boolean;
67
- sameSite?: "strict" | "lax" | "none";
68
- }
69
-
70
- export type ResolveFunction = (event: RequestEvent) => MaybePromise<Response>;
71
-
72
- export type Handle = (input: {
73
- event: RequestEvent;
74
- resolve: ResolveFunction;
75
- }) => MaybePromise<Response>;
76
-
77
- export interface HandleErrorInput {
78
- error: unknown;
79
- event: RequestEvent;
80
- status: number;
81
- message: string;
82
- }
83
- export type HandleError = (input: HandleErrorInput) => void | Promise<void>;
84
-
85
- export interface HandleFetchInput {
86
- request: Request;
87
- fetch: typeof globalThis.fetch;
88
- event: RequestEvent;
89
- }
90
- export type HandleFetch = (input: HandleFetchInput) => MaybePromise<Response>;
91
-
92
- export type InitFunction = () => void | Promise<void>;
93
-
94
- /**
95
- * Chain multiple Handle functions into one.
96
- * First handler in the array runs first.
97
- */
98
- export function sequence(...handlers: Handle[]): Handle {
99
- return async ({ event, resolve }) => {
100
- let i = 0;
101
-
102
- const next: ResolveFunction = async (evt) => {
103
- if (i < handlers.length) {
104
- const handler = handlers[i++];
105
- return handler!({ event: evt, resolve: next });
106
- }
107
- return resolve(evt);
108
- };
109
-
110
- return next(event);
111
- };
112
- }
113
-
114
- /**
115
- * Create a hooks object with handle and optional init.
116
- */
117
- export function createHooks(
118
- handle: Handle,
119
- init?: InitFunction,
120
- ): { handle: Handle; init?: InitFunction } {
121
- return { handle, init };
122
- }
1
+ /**
2
+ * SvelteKit-style server hooks.
3
+ *
4
+ * Create a hooks.server.ts in your project root:
5
+ *
6
+ * import type { Handle } from "@sigil-dev/grimoire/hooks";
7
+ *
8
+ * export const handle: Handle = async ({ event, resolve }) => {
9
+ * event.locals.user = await getUser(event.cookies.get("session"));
10
+ * const response = await resolve(event);
11
+ * response.headers.set("x-custom", "value");
12
+ * return response;
13
+ * };
14
+ *
15
+ * export const handleError: HandleError = ({ error, status, message }) => {
16
+ * console.error(`[${status}] ${message}`, error);
17
+ * };
18
+ *
19
+ * // optional: runs once at server start
20
+ * export const init = () => {
21
+ * console.log("Server started");
22
+ * };
23
+ *
24
+ * Chain multiple handlers with sequence():
25
+ *
26
+ * import { sequence } from "@sigil-dev/grimoire/hooks";
27
+ * import { logger } from "./hooks/logger";
28
+ * import { auth } from "./hooks/auth";
29
+ *
30
+ * export const handle = sequence(logger, auth);
31
+ */
32
+
33
+ export type MaybePromise<T> = T | Promise<T>;
34
+
35
+ export interface RequestEvent {
36
+ request: Request;
37
+ url: URL;
38
+ params: Record<string, string>;
39
+ locals: App.Locals;
40
+ cookies: Cookies;
41
+ route: { id: string };
42
+ fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
43
+ setHeaders: (headers: Record<string, string>) => void;
44
+ /**
45
+ * The visitor's IP address. Behind a reverse proxy on the same machine or
46
+ * network, it is the address the proxy reports; a visitor connecting
47
+ * directly cannot claim another one.
48
+ */
49
+ getClientAddress: () => string;
50
+ }
51
+
52
+ export interface Cookies {
53
+ get(name: string): string | undefined;
54
+ /** Path defaults to "/". */
55
+ set(name: string, value: string, options?: CookieOptions): void;
56
+ /** Pass the path and domain the cookie was set with; path defaults to "/". */
57
+ delete(name: string, options?: Pick<CookieOptions, "path" | "domain">): void;
58
+ }
59
+
60
+ export interface CookieOptions {
61
+ path?: string;
62
+ domain?: string;
63
+ maxAge?: number;
64
+ expires?: Date;
65
+ httpOnly?: boolean;
66
+ secure?: boolean;
67
+ sameSite?: "strict" | "lax" | "none";
68
+ }
69
+
70
+ export type ResolveFunction = (event: RequestEvent) => MaybePromise<Response>;
71
+
72
+ export type Handle = (input: {
73
+ event: RequestEvent;
74
+ resolve: ResolveFunction;
75
+ }) => MaybePromise<Response>;
76
+
77
+ export interface HandleErrorInput {
78
+ error: unknown;
79
+ event: RequestEvent;
80
+ status: number;
81
+ message: string;
82
+ }
83
+ export type HandleError = (input: HandleErrorInput) => void | Promise<void>;
84
+
85
+ export interface HandleFetchInput {
86
+ request: Request;
87
+ fetch: typeof globalThis.fetch;
88
+ event: RequestEvent;
89
+ }
90
+ export type HandleFetch = (input: HandleFetchInput) => MaybePromise<Response>;
91
+
92
+ export type InitFunction = () => void | Promise<void>;
93
+
94
+ /**
95
+ * Chain multiple Handle functions into one.
96
+ * First handler in the array runs first.
97
+ */
98
+ export function sequence(...handlers: Handle[]): Handle {
99
+ return async ({ event, resolve }) => {
100
+ let i = 0;
101
+
102
+ const next: ResolveFunction = async (evt) => {
103
+ if (i < handlers.length) {
104
+ const handler = handlers[i++];
105
+ return handler!({ event: evt, resolve: next });
106
+ }
107
+ return resolve(evt);
108
+ };
109
+
110
+ return next(event);
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Create a hooks object with handle and optional init.
116
+ */
117
+ export function createHooks(
118
+ handle: Handle,
119
+ init?: InitFunction,
120
+ ): { handle: Handle; init?: InitFunction } {
121
+ return { handle, init };
122
+ }
@@ -1,6 +1,6 @@
1
1
  import { existsSync, mkdirSync } from "node:fs";
2
2
  import { isAbsolute, join } from "node:path";
3
- import { plugin as bunPlugin, type ServerWebSocket } from "bun";
3
+ import { plugin as bunPlugin, type Server, type ServerWebSocket } from "bun";
4
4
  import { getDevModule } from "../dev/compile-module.ts";
5
5
  import { DevGraph } from "../dev/graph.ts";
6
6
  import { HMR_CLIENT_SOURCE } from "../dev/hmr-client.ts";
@@ -10,6 +10,7 @@ import { normalizePath } from "../dev/paths.ts";
10
10
  import { crawlFrom } from "../dev/scan.ts";
11
11
  import { startWatcher } from "../dev/watcher.ts";
12
12
  import { envModuleSource } from "../env/modules";
13
+ import { assertRequiredEnv } from "../env/required";
13
14
  import { log } from "../logger/instance.ts";
14
15
  import { renderErrorPage, renderRoute } from "../rendering";
15
16
  import { registerSSRPlugin } from "../rendering/ssrPlugin";
@@ -18,7 +19,17 @@ import { matchNotFound, matchRoute } from "../routing/router";
18
19
  import { isErrorResult } from "../sentinels/error.ts";
19
20
  import { isFailResult } from "../sentinels/fail.ts";
20
21
  import { isRedirectResult } from "../sentinels/redirect.ts";
21
- import type { GrimoireConfig, WsRouteHandler } from "../types";
22
+ import type { RouteTree } from "../routing/scanner";
23
+ import type { GrimoireConfig, GrimoirePlugin, WsRouteHandler } from "../types";
24
+ import {
25
+ normalizeBase,
26
+ outsideBaseMessage,
27
+ setBase,
28
+ stripBase,
29
+ withBase,
30
+ } from "../base";
31
+ import { RESERVED_EXPORTS } from "./reserved";
32
+ import { applyRewriters } from "./rewrite";
22
33
  import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
23
34
  import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
24
35
  import { buildProject, rebuildClient } from "./build";
@@ -49,15 +60,6 @@ const TEXT = { "Content-Type": "text/plain; charset=utf-8" };
49
60
 
50
61
  const logger = log.scope("server");
51
62
 
52
- /** +page.server.ts exports that are never dispatched as named actions. */
53
- const RESERVED_EXPORTS = new Set([
54
- "load",
55
- "canMatch",
56
- "csrf",
57
- "loading",
58
- "default",
59
- ]);
60
-
61
63
  /**
62
64
  * Directories to watch in dev. `src` covers components and libs that pages
63
65
  * import; the routes directory is added separately when it lives outside it.
@@ -197,7 +199,48 @@ interface _WsInternalData {
197
199
  [key: string]: unknown;
198
200
  }
199
201
 
200
- export async function createServer(config: GrimoireConfig = {}) {
202
+ /**
203
+ * Everything a server is except the socket: the request handler, the
204
+ * websocket handlers and the scanned route tree.
205
+ *
206
+ * Split from `createServer` so something that is not a listening server can
207
+ * use the real pipeline — `sigil build` prerenders by sending requests
208
+ * through `fetch`, which means `hooks.server.ts`, plugins and layouts run
209
+ * exactly as they will in production. `createServer` is this plus a port.
210
+ */
211
+ export interface GrimoireApp {
212
+ /** The full request pipeline: plugins, hooks, routing, rendering. */
213
+ fetch(req: Request): Promise<Response>;
214
+ /** Handlers to hand to `Bun.serve({ websocket })`. */
215
+ websocket: ServerWebSocketHandlers;
216
+ tree: RouteTree;
217
+ /** `src/params/*.ts` matchers by name, for `[param=name]` routes. */
218
+ matchers: Record<string, (value: string) => boolean>;
219
+ config: GrimoireConfig;
220
+ plugins: GrimoirePlugin[];
221
+ /** Tell the app which server it runs in, so it can upgrade websockets. */
222
+ bind(server: Server<any>): void;
223
+ /**
224
+ * Run `onStop` and let pending after-response work finish. Begins a
225
+ * process-wide shutdown (`afterResponse()` rejects afterwards), so call it
226
+ * once, when the process is done with the app.
227
+ */
228
+ close(
229
+ reason?: "shutdown" | "restart",
230
+ options?: { drainMs?: number },
231
+ ): Promise<void>;
232
+ /** Import every route module now, so the first visitor does not pay for it. */
233
+ preload(): Promise<void>;
234
+ }
235
+
236
+ type ServerWebSocketHandlers = {
237
+ open(ws: ServerWebSocket<any>): void;
238
+ message(ws: ServerWebSocket<any>, data: string | Buffer): void;
239
+ close(ws: ServerWebSocket<any>, code: number, reason?: string): void;
240
+ drain(ws: ServerWebSocket<any>): void;
241
+ };
242
+
243
+ export async function createApp(config: GrimoireConfig = {}): Promise<GrimoireApp> {
201
244
  // run config hooks
202
245
  let finalConfig = config;
203
246
  const earlyPlugins = config.plugins ?? [];
@@ -205,6 +248,18 @@ export async function createServer(config: GrimoireConfig = {}) {
205
248
  finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
206
249
  }
207
250
 
251
+ // Last word on `dev`: a plugin's config hook runs above and could have set
252
+ // it. The worker does the same for the same reason.
253
+ if (finalConfig._forceProduction) finalConfig = { ...finalConfig, dev: false };
254
+
255
+ // Before the build, which can take a minute: a missing variable is the
256
+ // cheapest thing to find out about and the most annoying to learn late.
257
+ assertRequiredEnv(finalConfig);
258
+
259
+ // A base that would 404 every asset is a startup error, not a mystery.
260
+ const appBase = normalizeBase(finalConfig.base);
261
+ setBase(appBase);
262
+
208
263
  const {
209
264
  port = 3000,
210
265
  host = "localhost",
@@ -235,6 +290,9 @@ export async function createServer(config: GrimoireConfig = {}) {
235
290
  registerSSRPlugin(plugins, projectAliases(finalConfig));
236
291
  registerServerResolver(finalConfig);
237
292
 
293
+ // Set by bind(); the handlers below only use it once a request arrives.
294
+ let server: Server<any> | undefined;
295
+
238
296
  const graph = new DevGraph();
239
297
  const hmr = dev ? new HmrServer() : null;
240
298
 
@@ -357,6 +415,16 @@ export async function createServer(config: GrimoireConfig = {}) {
357
415
  // Before init(), so hooks.server.ts can use what plugins opened — a
358
416
  // database for a warm-up query or a migration check is the usual case,
359
417
  // and running init first meant it could only fail.
418
+ // The same hook the coordinator fires, for every process that serves
419
+ // requests. It used to run only in the coordinator, so `sigil dev` and a
420
+ // single-process `sigil start` never gave plugins their moment to look at
421
+ // each other.
422
+ await runHook(plugins, "onPluginsResolved", {
423
+ mode: dev ? "development" : "production",
424
+ plugins: new Map(plugins.map((p) => [p.name, p])),
425
+ logger: log.scope("plugins"),
426
+ });
427
+
360
428
  const services = await collectServices(plugins);
361
429
 
362
430
  // Run init hook if present
@@ -369,13 +437,18 @@ export async function createServer(config: GrimoireConfig = {}) {
369
437
  for (const p of plugins) {
370
438
  if (p.onRouteRender) {
371
439
  logger.warn(
372
- `plugin "${p.name}" implements onRouteRender, which buffers the full HTML response and disables streaming (including the \`loading\` shell) on every route it touches. If you only need to change headers, use onRequest instead.`,
440
+ `plugin "${p.name}" implements onRouteRender, which buffers the full HTML response and disables streaming (including the \`loading\` shell) on every route it touches. Use rewriteHtml(rewriter) to change the HTML while it streams, or onRequest to change headers.`,
373
441
  );
374
442
  }
375
443
  }
376
444
 
377
445
  async function handleRequest(req: Request) {
378
- const rawLocals = req.headers.get("X-Grimoire-Locals");
446
+ // Only the coordinator is trusted to say who the user is. A server that
447
+ // answers the public directly ignores the header, so nobody can send
448
+ // their own `locals` to it.
449
+ const rawLocals = finalConfig._behindCoordinator
450
+ ? req.headers.get("X-Grimoire-Locals")
451
+ : null;
379
452
  const locals: App.Locals = rawLocals
380
453
  ? ((await runDeserializeLocals(plugins, rawLocals)) ?? {})
381
454
  : {};
@@ -389,7 +462,7 @@ export async function createServer(config: GrimoireConfig = {}) {
389
462
 
390
463
  if (dev && url.pathname === "/__grimoire__/hmr") {
391
464
  //@ts-expect-error holy shut up
392
- if (server.upgrade(req, { data: { __hmrClient: true } })) {
465
+ if (server?.upgrade(req, { data: { __hmrClient: true } })) {
393
466
  return undefined as unknown as Response;
394
467
  }
395
468
  return new Response("Upgrade Required", { status: 426 });
@@ -618,7 +691,7 @@ export async function createServer(config: GrimoireConfig = {}) {
618
691
  ...extraData,
619
692
  };
620
693
  //@ts-expect-error i dont know what you are talking about please
621
- if (server.upgrade(req, { data: wsData })) {
694
+ if (server?.upgrade(req, { data: wsData })) {
622
695
  return undefined as unknown as Response;
623
696
  }
624
697
  return new Response("Upgrade Required", { status: 426 });
@@ -724,6 +797,9 @@ export async function createServer(config: GrimoireConfig = {}) {
724
797
  getClientAddress: () => clientAddressOf(evt.request),
725
798
  });
726
799
  } catch (e) {
800
+ // A thrown Response is the reply, like a returned one: it
801
+ // used to fall through to the 500 path and be swallowed.
802
+ if (e instanceof Response) return e;
727
803
  if (isRedirectResult(e)) {
728
804
  if (enhanced) {
729
805
  return Response.json({
@@ -769,6 +845,8 @@ export async function createServer(config: GrimoireConfig = {}) {
769
845
  throw e;
770
846
  }
771
847
 
848
+ if (result instanceof Response) return result;
849
+
772
850
  if (isFailResult(result)) {
773
851
  if (enhanced) {
774
852
  return Response.json(
@@ -793,7 +871,9 @@ export async function createServer(config: GrimoireConfig = {}) {
793
871
  }
794
872
 
795
873
  const redirectTo =
796
- result?.redirect ?? evt.request.headers.get("referer") ?? "/";
874
+ result?.redirect ??
875
+ evt.request.headers.get("referer") ??
876
+ withBase("/");
797
877
  if (enhanced) {
798
878
  return Response.json({
799
879
  type: "success",
@@ -828,31 +908,35 @@ export async function createServer(config: GrimoireConfig = {}) {
828
908
  return response;
829
909
  }
830
910
 
911
+ // Streaming-safe rewrites first, then the buffered legacy hook.
912
+ const rewritten = await applyRewriters(response, plugins, {
913
+ route: matched.route,
914
+ request: evt.request,
915
+ params: matched.params,
916
+ data: undefined,
917
+ });
831
918
  const hasRenderPlugins = plugins.some((p) => p.onRouteRender);
832
- if (hasRenderPlugins) {
833
- let html = await response.text();
834
- for (const plugin of plugins) {
835
- html =
836
- (await plugin.onRouteRender?.(html, {
837
- route: matched.route,
838
- request: evt.request,
839
- params: matched.params,
840
- data: undefined,
841
- })) ?? html;
842
- }
843
- // Carry the original headers over. Rebuilding with a fixed set
844
- // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
845
- // plugin silently broke form actions and cache correctness.
846
- const headers = new Headers(response.headers);
847
- headers.set("Content-Type", "text/html");
848
- return new Response(html, {
849
- status: response.status,
850
- statusText: response.statusText,
851
- headers,
852
- });
919
+ if (!hasRenderPlugins) return rewritten;
920
+ let html = await rewritten.text();
921
+ for (const plugin of plugins) {
922
+ html =
923
+ (await plugin.onRouteRender?.(html, {
924
+ route: matched.route,
925
+ request: evt.request,
926
+ params: matched.params,
927
+ data: undefined,
928
+ })) ?? html;
853
929
  }
854
-
855
- return response;
930
+ // Carry the original headers over. Rebuilding with a fixed set
931
+ // dropped Vary and the _csrf Set-Cookie, so any onRouteRender
932
+ // plugin silently broke form actions and cache correctness.
933
+ const headers = new Headers(rewritten.headers);
934
+ headers.set("Content-Type", "text/html");
935
+ return new Response(html, {
936
+ status: rewritten.status,
937
+ statusText: rewritten.statusText,
938
+ headers,
939
+ });
856
940
  };
857
941
 
858
942
  let response: Response;
@@ -922,45 +1006,64 @@ export async function createServer(config: GrimoireConfig = {}) {
922
1006
  });
923
1007
  }
924
1008
 
925
- const wsConfig = {
926
- websocket: {
927
- open(ws: ServerWebSocket<any>) {
928
- if (ws.data.__hmrClient) {
929
- hmr?.addClient(ws);
930
- return;
931
- }
932
- (ws.data as _WsInternalData).__handler?.open?.(ws);
933
- },
934
- message(ws: ServerWebSocket<any>, data: string | Buffer) {
935
- if (ws.data.__hmrClient) return;
936
- (ws.data as _WsInternalData).__handler?.message?.(ws, data);
937
- },
938
- close(ws: ServerWebSocket<any>, code: number, reason?: string) {
939
- if (ws.data.__hmrClient) {
940
- hmr?.removeClient(ws);
941
- return;
942
- }
943
- (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
944
- },
945
- drain(ws: ServerWebSocket<any>) {
946
- if (ws.data.__hmrClient) return;
947
- (ws.data as _WsInternalData).__handler?.drain?.(ws);
948
- },
1009
+ const websocket: ServerWebSocketHandlers = {
1010
+ open(ws: ServerWebSocket<any>) {
1011
+ if (ws.data.__hmrClient) {
1012
+ hmr?.addClient(ws);
1013
+ return;
1014
+ }
1015
+ (ws.data as _WsInternalData).__handler?.open?.(ws);
1016
+ },
1017
+ message(ws: ServerWebSocket<any>, data: string | Buffer) {
1018
+ if (ws.data.__hmrClient) return;
1019
+ (ws.data as _WsInternalData).__handler?.message?.(ws, data);
1020
+ },
1021
+ close(ws: ServerWebSocket<any>, code: number, reason?: string) {
1022
+ if (ws.data.__hmrClient) {
1023
+ hmr?.removeClient(ws);
1024
+ return;
1025
+ }
1026
+ (ws.data as _WsInternalData).__handler?.close?.(ws, code, reason);
1027
+ },
1028
+ drain(ws: ServerWebSocket<any>) {
1029
+ if (ws.data.__hmrClient) return;
1030
+ (ws.data as _WsInternalData).__handler?.drain?.(ws);
949
1031
  },
950
1032
  };
951
1033
 
952
- // Bun.serve is called here rather than alongside the websocket config
953
- // because handleRequest is referenced before its declaration; function
954
- // hoisting makes that safe, and this keeps the two blocks readable.
955
1034
  // Wrapping is what makes afterResponse() mean "after the response",
956
1035
  // including for streaming responses: the tasks fire when the body
957
1036
  // finishes, not when the handler returns.
958
1037
  const fetchHandler = (req: Request) => withAfterResponse(req, handleRequest);
959
1038
 
960
- // Before the port opens, so the first visitor never pays for compiling a
961
- // route: a worker only reports ready once this has finished.
962
- const warmConfig = finalConfig.warm;
963
- if (!dev && warmConfig?.preload !== false) {
1039
+ // Under a base, the request is stripped to a route path once, here, so
1040
+ // nothing past this point has to know about it.
1041
+ const fetchUnderBase = (req: Request): Promise<Response> | Response => {
1042
+ if (!appBase) return fetchHandler(req);
1043
+ const url = new URL(req.url);
1044
+ if (url.pathname === appBase) {
1045
+ return new Response(null, {
1046
+ status: 308,
1047
+ headers: { Location: `${appBase}/${url.search}` },
1048
+ });
1049
+ }
1050
+ const route = stripBase(url.pathname, appBase);
1051
+ if (route === null) {
1052
+ // dev modules import each other root-relative
1053
+ if (dev && url.pathname.startsWith("/__grimoire__/")) {
1054
+ return fetchHandler(req);
1055
+ }
1056
+ return new Response(outsideBaseMessage(url.pathname, appBase, dev), {
1057
+ status: 404,
1058
+ headers: { "Content-Type": "text/plain" },
1059
+ });
1060
+ }
1061
+ url.pathname = route;
1062
+ return fetchHandler(new Request(url, req));
1063
+ };
1064
+
1065
+ const preload = async () => {
1066
+ if (dev || finalConfig.warm?.preload === false) return;
964
1067
  const files = [
965
1068
  ...tree.routes,
966
1069
  ...tree.layouts,
@@ -974,15 +1077,47 @@ export async function createServer(config: GrimoireConfig = {}) {
974
1077
  logger.info(
975
1078
  `preloaded ${loaded}/${new Set(files).size} route modules in ${Math.round(performance.now() - t0)}ms`,
976
1079
  );
977
- }
1080
+ };
1081
+
1082
+ return {
1083
+ fetch: fetchUnderBase,
1084
+ websocket,
1085
+ tree,
1086
+ matchers: paramMatcherFns,
1087
+ config: finalConfig,
1088
+ plugins,
1089
+ bind(s) {
1090
+ server = s;
1091
+ },
1092
+ preload,
1093
+ async close(reason = "shutdown", options) {
1094
+ await runHook(plugins, "onStop", reason);
1095
+ // Drain before stopping, so a task already registered for a response
1096
+ // that has been sent gets to finish rather than being killed with the
1097
+ // process. Bounded: a hung task must not block a deploy forever.
1098
+ await drainAfterResponse(options?.drainMs);
1099
+ },
1100
+ };
1101
+ }
1102
+
1103
+ export async function createServer(config: GrimoireConfig = {}) {
1104
+ const app = await createApp(config);
1105
+ const { plugins, config: finalConfig } = app;
1106
+ const { port = 3000, host = "localhost", dev = false } = finalConfig;
1107
+
1108
+ // Before the port opens, so the first visitor never pays for compiling a
1109
+ // route: a worker only reports ready once this has finished.
1110
+ await app.preload();
978
1111
 
979
1112
  const server = Bun.serve({
980
1113
  port,
981
1114
  hostname: host,
982
- fetch: fetchHandler,
983
- ...wsConfig,
1115
+ fetch: app.fetch,
1116
+ websocket: app.websocket,
984
1117
  });
1118
+ app.bind(server);
985
1119
 
1120
+ const warmConfig = finalConfig.warm;
986
1121
  let warmer: Warmer | null = null;
987
1122
  if (!dev && warmConfig?.paths?.length) {
988
1123
  warmer = startWarming({
@@ -990,7 +1125,7 @@ export async function createServer(config: GrimoireConfig = {}) {
990
1125
  every: warmConfig.every,
991
1126
  origin: `http://${host}:${server.port}`,
992
1127
  headers: finalConfig._warmHeaders,
993
- handle: async (req) => fetchHandler(req),
1128
+ handle: async (req) => app.fetch(req),
994
1129
  log: (msg) => logger.info(msg),
995
1130
  });
996
1131
  }
@@ -1000,11 +1135,7 @@ export async function createServer(config: GrimoireConfig = {}) {
1000
1135
  if (stopping) return;
1001
1136
  stopping = true;
1002
1137
  warmer?.stop();
1003
- await runHook(plugins, "onStop", "shutdown");
1004
- // Drain before stopping, so a task already registered for a response
1005
- // that has been sent gets to finish rather than being killed with the
1006
- // process. Bounded: a hung task must not block a deploy forever.
1007
- await drainAfterResponse();
1138
+ await app.close("shutdown");
1008
1139
  // stop(true), not stop(): the graceful form waits for open connections,
1009
1140
  // and a dev HMR websocket never closes on its own, so shutdown hangs.
1010
1141
  server.stop(true);