@sigil-dev/grimoire 0.9.21 → 0.9.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +83 -83
  2. package/index.ts +50 -48
  3. package/package.json +16 -5
  4. package/public/__grimoire__/grimoire-client.js +12 -0
  5. package/public/__grimoire__/runtime.js +1241 -0
  6. package/server.ts +22 -20
  7. package/src/adapters/bun.ts +17 -0
  8. package/src/adapters/static.ts +41 -0
  9. package/src/adapters/types.ts +36 -0
  10. package/src/base.ts +91 -0
  11. package/src/client/csrf.ts +47 -47
  12. package/src/client/deferred.ts +179 -179
  13. package/src/client/enhance.ts +160 -160
  14. package/src/client/router.ts +870 -833
  15. package/src/dev/compile-module.ts +211 -211
  16. package/src/dev/loader.ts +141 -141
  17. package/src/dev/resolve.ts +70 -70
  18. package/src/dev/runtime-bundle.ts +51 -51
  19. package/src/env/modules.ts +62 -62
  20. package/src/env/required.ts +42 -0
  21. package/src/env/typegen.ts +61 -61
  22. package/src/headers.ts +105 -105
  23. package/src/logger/transports.ts +117 -117
  24. package/src/rendering/head.ts +49 -49
  25. package/src/rendering/hydrate.ts +161 -161
  26. package/src/rendering/images.ts +43 -43
  27. package/src/rendering/index.ts +755 -749
  28. package/src/rendering/preload.ts +101 -101
  29. package/src/rendering/ssrPlugin.ts +108 -108
  30. package/src/rendering/timing.ts +40 -40
  31. package/src/routing/router.ts +186 -186
  32. package/src/routing/scanner.ts +225 -196
  33. package/src/routing/transform-routes.ts +102 -102
  34. package/src/server/after-response.ts +206 -206
  35. package/src/server/asset-cache.ts +57 -57
  36. package/src/server/build.ts +262 -262
  37. package/src/server/cached.ts +114 -114
  38. package/src/server/client-address.ts +82 -82
  39. package/src/server/client-dir.ts +57 -57
  40. package/src/server/client-entry.ts +44 -44
  41. package/src/server/cookie-utils.ts +80 -80
  42. package/src/server/coordinator.ts +476 -471
  43. package/src/server/hooks.ts +122 -122
  44. package/src/server/index.ts +1138 -1018
  45. package/src/server/plugins.ts +172 -172
  46. package/src/server/prerender.ts +444 -0
  47. package/src/server/reserved.ts +17 -0
  48. package/src/server/resolver.ts +98 -98
  49. package/src/server/rewrite.ts +28 -0
  50. package/src/server/warm.ts +91 -91
  51. package/src/server/with-headers.ts +27 -27
  52. package/src/server/worker.ts +74 -72
  53. package/src/testing/dom.ts +73 -0
  54. package/src/testing/index.ts +169 -0
  55. package/src/testing/server.ts +162 -0
  56. package/src/typegen/index.ts +450 -450
  57. package/src/types.ts +501 -432
  58. package/test/after-response.test.ts +132 -132
  59. package/test/asset-cache-policy.test.ts +96 -96
  60. package/test/base.test.ts +134 -0
  61. package/test/cached.test.ts +126 -126
  62. package/test/client-address.test.ts +78 -78
  63. package/test/client-csrf.test.ts +61 -61
  64. package/test/client-dir.test.ts +101 -101
  65. package/test/client-router.test.ts +789 -734
  66. package/test/coordinator.test.ts +96 -94
  67. package/test/deferred.test.ts +256 -256
  68. package/test/dev-loader.test.ts +30 -30
  69. package/test/env.test.ts +168 -168
  70. package/test/force-production.test.ts +44 -0
  71. package/test/images.test.ts +49 -49
  72. package/test/locals-header.test.ts +61 -0
  73. package/test/middleware.test.ts +243 -243
  74. package/test/parser-plugins.test.ts +92 -92
  75. package/test/plugin-handle.test.ts +62 -62
  76. package/test/plugin-services-context.test.ts +97 -97
  77. package/test/preload.test.ts +48 -48
  78. package/test/prerender.test.ts +353 -0
  79. package/test/rendering.test.ts +798 -798
  80. package/test/required-env.test.ts +32 -0
  81. package/test/rewrite-html.test.ts +90 -0
  82. package/test/scanning.test.ts +349 -314
  83. package/test/server.test.ts +640 -619
  84. package/test/services.test.ts +90 -90
  85. package/test/streaming.test.ts +378 -378
  86. package/test/testing-helpers.test.ts +166 -0
  87. package/test/typegen.test.ts +805 -799
  88. package/test/warm.test.ts +96 -96
  89. package/test/worker-context.test.ts +59 -59
  90. package/test/workspace-files.test.ts +149 -146
  91. package/test/workspace-versions.test.ts +131 -131
  92. package/.grimoire/_routes.ts +0 -4
  93. package/public/__grimoire__/client.js +0 -55
  94. package/public/__grimoire__/hydrate.js +0 -63
package/src/types.ts CHANGED
@@ -1,432 +1,501 @@
1
- import type { Server, ServerWebSocket } from "bun";
2
- import type { ScopedLogger } from "./logger";
3
- import type { RouteFile, RouteTree } from "./routing/scanner";
4
- import type { Handle } from "./server/hooks";
5
-
6
- /**
7
- * Structural subset of commander's Command that plugins need to register
8
- * subcommands. Declared here rather than importing Command so that
9
- * @sigil-dev/grimoire does not take a dependency on commander — the CLI is
10
- * one consumer of plugins, not the only one.
11
- */
12
- export interface CliCommand {
13
- name(): string;
14
- command(nameAndArgs: string, opts?: { hidden?: boolean }): CliCommand;
15
- description(text: string): CliCommand;
16
- alias(alias: string): CliCommand;
17
- option(flags: string, description?: string, defaultValue?: unknown): CliCommand;
18
- argument(name: string, description?: string): CliCommand;
19
- action(fn: (...args: never[]) => unknown): CliCommand;
20
- }
21
-
22
- /// <reference types="bun-types">
23
- declare global {
24
- namespace App {
25
- // augment in your own project via src/app.d.ts
26
- interface Locals {}
27
- interface Error {
28
- message: string;
29
- status?: number;
30
- }
31
- interface PageData {}
32
- interface Platform {}
33
- }
34
- }
35
-
36
- export interface Route {
37
- path: string; // /blog/:slug
38
- params: Record<string, string>;
39
- filePath: string; // absolute path to +page.tsx
40
- loadPath?: string; // absolute path to +page.ts
41
- serverPath?: string; // absolute path to +server.ts
42
- layoutPath?: string; // absolute path to +layout.tsx
43
- }
44
-
45
- export interface RouteInfo {
46
- path: string; // /blog/:slug
47
- filePath: string; // absolute path
48
- type: string; // page, layout etc
49
- }
50
-
51
- export interface LoadContext {
52
- request: Request;
53
- params: Record<string, string>;
54
- url: URL;
55
- locals: Record<string, unknown>; // set by plugins/hooks
56
- fetch: typeof globalThis.fetch;
57
- /** The visitor's IP address; see RequestEvent.getClientAddress. */
58
- getClientAddress: () => string;
59
- /** Data returned by parent layouts' loads, merged outermost-first. */
60
- parent: () => Promise<Record<string, unknown>>;
61
- }
62
-
63
- export interface TypedLoadContext<
64
- P extends Record<string, string> = Record<string, string>,
65
- > {
66
- request: Request;
67
- params: P;
68
- url: URL;
69
- locals: App.Locals;
70
- fetch: typeof fetch;
71
- /** Data returned by parent layouts' loads, merged outermost-first. */
72
- parent: () => Promise<Record<string, unknown>>;
73
- }
74
-
75
- export interface RenderContext {
76
- route: RouteInfo;
77
- request: Request;
78
- params: Record<string, string>;
79
- data: unknown; // return value of load()
80
- }
81
-
82
- export interface PluginContext {
83
- mode: "development" | "production";
84
- plugins: ReadonlyMap<string, GrimoirePlugin>;
85
- logger: ScopedLogger;
86
- }
87
-
88
- /**
89
- * Which worker this process is, and how many there are.
90
- *
91
- * A plugin that creates one resource per worker — a connection pool, an
92
- * embedded database handle — needs both numbers to divide a global budget
93
- * correctly. `maxConnections: 20` across 4 workers is 5 each; a plugin that
94
- * only knows its own index has no way to work that out and quietly opens 80.
95
- *
96
- * The coordinator sets both as env vars at spawn, so this resolves in a
97
- * worker process. Running without a coordinator (`sigil dev`, or a single
98
- * process) is one worker of one, which is the honest answer rather than a
99
- * guess.
100
- */
101
- export interface WorkerContext {
102
- /** 0-based within this mode. 0 when there is no coordinator. */
103
- workerId: number;
104
- /** Total workers across all modes. At least 1. */
105
- workers: number;
106
- /** Whether the server is in development mode. */
107
- dev: boolean;
108
- }
109
-
110
- export function workerContext(env: Record<string, string | undefined> = process.env): WorkerContext {
111
- const parsed = Number(env.GRIMOIRE_WORKER_INDEX);
112
- const count = Number(env.GRIMOIRE_WORKER_COUNT);
113
- return {
114
- // A NaN here means no coordinator set them, which is one worker.
115
- workerId: Number.isFinite(parsed) && parsed > 0 ? parsed - 1 : 0,
116
- // Never 0: a budget divided by zero is Infinity, and a pool of
117
- // Infinity is a crash at the first connection.
118
- workers: Number.isFinite(count) && count > 0 ? count : 1,
119
- dev: env.GRIMOIRE_MODE === "development",
120
- };
121
- }
122
-
123
- export interface BuildResult {
124
- success: boolean;
125
- outputs: string[];
126
- errors: string[];
127
- }
128
-
129
- export interface ServicesContext {
130
- /**
131
- * What the plugins before this one published, keyed the same way it will
132
- * appear on `locals`. A snapshot: mutating it changes nothing.
133
- */
134
- services: Record<string, unknown>;
135
- }
136
-
137
- export interface GrimoirePlugin {
138
- name: string;
139
-
140
- // plugin lifecycle
141
- onPluginsResolved?(ctx: PluginContext): void | Promise<void>;
142
-
143
- /**
144
- * Expose values on `locals` for the whole app to use.
145
- *
146
- * Returns an object merged into the per-request `locals` before any
147
- * route, load, action or +server.ts handler runs, so a route reaches it
148
- * as `locals.<key>` with nothing imported and nothing exported from
149
- * sigil.config.ts.
150
- *
151
- * The merge is shallow and runs in plugin order, so a later plugin
152
- * overriding an earlier plugin's key wins — same rule as every other
153
- * merge in the pipeline. It is collected once, at startup, and the same
154
- * values are merged into every request, so a request-scoped value here
155
- * is a mistake.
156
- *
157
- * This is the place to open a connection pool. It runs only where
158
- * requests are served — `sigil dev` and each `sigil start` worker, not
159
- * the coordinator or `sigil build`, which do run `config()` — and before
160
- * hooks.server.ts `init()`, so `init` can use what it opened.
161
- *
162
- * `ctx.services` is what the plugins before this one published, so a
163
- * plugin can build on a resource another plugin owns instead of opening
164
- * a second one. Register the SQL plugin first and a consumer reads
165
- * `ctx.services.db` — the same client, not a parallel pool.
166
- *
167
- * It is a snapshot taken before this plugin runs, so a plugin registered
168
- * before the one it needs sees nothing. Plugins that must not depend on
169
- * ordering should fail loudly when the key is absent rather than quietly
170
- * open their own fallback.
171
- */
172
- services?(ctx: ServicesContext): Record<string, unknown> | Promise<Record<string, unknown>>;
173
-
174
- // server lifecycle
175
- // we dont care about what the impl puts as websocket data therefore unknown.
176
- onStart?(server: Server<unknown>): void | Promise<void>;
177
- onStop?(reason: "shutdown" | "restart"): void | Promise<void>;
178
-
179
- /**
180
- * Wrap each request's route handling, with the same event and `resolve`
181
- * as `handle` in hooks.server.ts.
182
- *
183
- * Unlike `onRequest`, which sees a raw Request, this sees the
184
- * `RequestEvent`: it can read and set cookies, fill `event.locals`
185
- * (`locals.user`) and answer a request itself without calling `resolve`.
186
- * Plugin handles run in plugin order, then hooks.server.ts `handle`, so
187
- * the app's own handle sees whatever the plugins put on `locals`.
188
- */
189
- handle?: Handle;
190
-
191
- // request pipeline
192
- onRequest?(
193
- req: Request,
194
- next: () => Promise<Response>,
195
- ): Response | Promise<Response>;
196
-
197
- // route lifecycle
198
- onRouteLoad?(route: Route, context: LoadContext): void | Promise<void>;
199
- /**
200
- * Called after the page HTML is fully rendered.
201
- * NOTE: When any plugin implements this hook, the streaming response is
202
- * buffered into a single string. Streaming is preserved for routes where
203
- * no plugin uses this hook. To avoid buffering, use onRequest to intercept
204
- * at the Response level.
205
- */
206
- onRouteRender?(
207
- html: string,
208
- context: RenderContext,
209
- ): string | Promise<string>;
210
-
211
- // build
212
- onBuildStart?(): void | Promise<void>;
213
- onBuildEnd?(result: BuildResult): void | Promise<void>;
214
-
215
- // config
216
- /**
217
- * Transform the project config at load time.
218
- *
219
- * May be async. Plugins need this to open a database connection or run
220
- * migrations before the server starts, and a sync-only signature makes
221
- * that impossible without blocking module scope. Every call site awaits
222
- * the result, so a returned Promise is never mistaken for a config.
223
- */
224
- config?: (config: GrimoireConfig) =>
225
- | GrimoireConfig
226
- | undefined
227
- | Promise<GrimoireConfig | undefined>;
228
-
229
- /**
230
- * Register CLI subcommands for this plugin.
231
- *
232
- * Called by the `sigil` CLI after it has loaded the project's sigil.config.ts,
233
- * before command parsing, so a plugin can add `sigil jobs work` or similar.
234
- * The project config is passed through as-is (after this plugin's own
235
- * `config` transform, so it reflects the same values the server sees).
236
- *
237
- * Plugins without this hook are simply skipped. A plugin that throws here
238
- * aborts the CLI with that error rather than failing obscurely later.
239
- */
240
- cli?: (
241
- program: CliCommand,
242
- context: GrimoireConfig,
243
- ) => void | Promise<void>;
244
-
245
- // process lifecycle
246
-
247
- /**
248
- * Runs AFTER Sigil/Babel compilation. Receives compiled JS, not source TSX.
249
- * Suitable for string-level transforms (import rewriting, comment injection, etc.).
250
- * Return null/undefined to pass through unchanged.
251
- */
252
- transform?(
253
- code: string,
254
- id: string,
255
- ): string | null | undefined | Promise<string | null | undefined>;
256
-
257
- /**
258
- * Fires once after all workers are spawned and ready.
259
- * Use for coordinator-level setup (e.g. opening a shared store).
260
- */
261
- onCoordinatorStart?(ctx: CoordinatorContext): void | Promise<void>;
262
-
263
- /**
264
- * Fires for each worker before Bun.spawn is called.
265
- * Return WorkerEnv to inject env vars or set the worker name.
266
- * ALL plugins are called and results are merged.
267
- */
268
- onWorkerSpawn?(
269
- worker: WorkerDescriptor,
270
- // biome-ignore lint/suspicious/noConfusingVoidType: doesn't have to return a thing.
271
- ): WorkerEnv | void | Promise<WorkerEnv | void>;
272
-
273
- /**
274
- * Fires when a worker process is up and accepting requests.
275
- */
276
- onWorkerReady?(worker: WorkerDescriptor): void | Promise<void>;
277
-
278
- /**
279
- * Fires when a worker process exits.
280
- * reason "crash" = unexpected exit, "intentional" = coordinator stopped it.
281
- * Use for cleanup or respawn logic (see plugin-scale).
282
- */
283
- onWorkerDeath?(
284
- worker: WorkerDescriptor,
285
- reason: "crash" | "intentional",
286
- ): void | Promise<void>;
287
-
288
- // ── Locals boundary ────────────────────────────────────────
289
-
290
- /**
291
- * Called by coordinator before forwarding a request to a worker.
292
- * Return a serialized string representation of locals.
293
- * First plugin to return non-null wins. Default: signed JSON header.
294
- */
295
- serializeLocals?(locals: App.Locals): string | Promise<string>;
296
-
297
- /**
298
- * Called by worker on receiving a forwarded request.
299
- * Return the deserialized locals object.
300
- * First plugin to return non-null wins. Default: verify + JSON.parse.
301
- */
302
- deserializeLocals?(raw: string): App.Locals | Promise<App.Locals>;
303
-
304
- // ── Routing policy ─────────────────────────────────────────
305
-
306
- /**
307
- * Called by coordinator to decide which worker handles a request.
308
- * First plugin to return non-null wins.
309
- * Default: ws routes → consistent hash, everything else → round robin.
310
- * routes is the full RouteTree so plugins can make route-aware decisions.
311
- */
312
- routeRequest?(
313
- req: Request,
314
- workers: WorkerDescriptor[],
315
- routes: RouteTree,
316
- ): WorkerDescriptor | Promise<WorkerDescriptor>;
317
- }
318
-
319
- export interface GrimoireConfig {
320
- port?: number;
321
- host?: string;
322
- plugins?: GrimoirePlugin[];
323
- routes?: string; // glob, default 'src/routes/**';
324
- dev?: boolean;
325
- devEditor?: boolean;
326
- vitePort?: number;
327
- alias?: Record<string, string>; // e.g. { "$lib": "src/lib" } — resolved relative to cwd
328
- cspNonce?: string; // CSP nonce for <script>/<style> tags
329
- bundleStrategy?: "split" | "single"; // 'split' (default) or 'single' bundle
330
- /**
331
- * Send a `Server-Timing` header (load / render durations) on page
332
- * responses. Default: on in dev, off in production.
333
- */
334
- serverTiming?: boolean;
335
- _skipBuild?: boolean;
336
- /**
337
- * Production cache warming. Route modules are imported before the server
338
- * takes traffic; `paths` are then requested through the real handler (once
339
- * per worker, and again every `every` ms) so in-memory caches are full
340
- * before a visitor arrives.
341
- */
342
- warm?: import("./server/warm.ts").WarmConfig;
343
- /** Set by the worker: headers the server's own warm-up requests carry. */
344
- _warmHeaders?: Record<string, string>;
345
- }
346
-
347
- export function defineConfig(config: GrimoireConfig): GrimoireConfig {
348
- return config;
349
- }
350
-
351
- /** Generic load type for +page.server.ts. For per-route typed params import PageServerLoad from './$types'. */
352
- export type PageServerLoad<
353
- P extends Record<string, string> = Record<string, string>,
354
- > = (
355
- ctx: TypedLoadContext<P>,
356
- ) => Record<string, unknown> | Promise<Record<string, unknown>>;
357
-
358
- /** Generic load type for +layout.server.ts. For per-route typed params import LayoutServerLoad from './$types'. */
359
- export type LayoutServerLoad<
360
- P extends Record<string, string> = Record<string, string>,
361
- > = (
362
- ctx: TypedLoadContext<P>,
363
- ) => Record<string, unknown> | Promise<Record<string, unknown>>;
364
-
365
- /** Generic handler type for +server.ts API routes. For per-route typed params import RequestHandler from './$types'. */
366
- export type RequestHandler<
367
- P extends Record<string, string> = Record<string, string>,
368
- > = (ctx: TypedLoadContext<P>) => Response | Promise<Response>;
369
-
370
- /**
371
- * Shape of the `websocket` export in a +server.ts file.
372
- * T is the resolved ws.data shape (params + upgrade() return value).
373
- * For per-route typing import WebSocketHandler from './$types'.
374
- */
375
- export interface WsRouteHandler<T = Record<string, unknown>> {
376
- open?(ws: ServerWebSocket<T>): void | Promise<void>;
377
- message?(ws: ServerWebSocket<T>, data: string | Buffer): void | Promise<void>;
378
- close?(
379
- ws: ServerWebSocket<T>,
380
- code: number,
381
- reason?: string,
382
- ): void | Promise<void>;
383
- drain?(ws: ServerWebSocket<T>): void | Promise<void>;
384
- }
385
-
386
- // ***BIG ONE***
387
-
388
- /**
389
- * Built-in worker modes understood by the coordinator.
390
- * Plugins may define custom modes via WorkerMode.
391
- */
392
- export type BuiltinWorkerMode = "api" | "frontend" | "ws" | "full";
393
-
394
- /**
395
- * Open union — (string & {}) preserves autocomplete for built-in
396
- * values while allowing plugin-defined modes like "db" or "queue".
397
- */
398
- export type WorkerMode = BuiltinWorkerMode | (string & {});
399
-
400
- /**
401
- * Describes a single worker process managed by the coordinator.
402
- * Coordinator derives behavior from routes, not mode string —
403
- * mode is informational and for plugin use only.
404
- */
405
- export interface WorkerDescriptor {
406
- mode: WorkerMode;
407
- index: number; // index within this mode (api-0, api-1...)
408
- globalIndex: number; // index across all workers
409
- internalUrl: string; // coordinator → worker base URL
410
- name?: string; // set by namepool or onWorkerSpawn
411
- routes: RouteFile[]; // route slice assigned by coordinator
412
- pid?: number; // set after Bun.spawn
413
- }
414
-
415
- /**
416
- * Return value of onWorkerSpawn. All plugins are called and results
417
- * are merged — env from all plugins is combined, last name wins.
418
- */
419
- export interface WorkerEnv {
420
- env?: Record<string, string>;
421
- name?: string;
422
- }
423
-
424
- /**
425
- * Passed to onCoordinatorStart once the coordinator is fully initialized.
426
- */
427
- export interface CoordinatorContext {
428
- workers: WorkerDescriptor[];
429
- port: number;
430
- secret: string; // ephemeral signing secret, generated per-run
431
- routes: RouteTree;
432
- }
1
+ import type { Server, ServerWebSocket } from "bun";
2
+ import type { ScopedLogger } from "./logger";
3
+ import type { RouteFile, RouteTree } from "./routing/scanner";
4
+ import type { Handle } from "./server/hooks";
5
+
6
+ /**
7
+ * Structural subset of commander's Command that plugins need to register
8
+ * subcommands. Declared here rather than importing Command so that
9
+ * @sigil-dev/grimoire does not take a dependency on commander — the CLI is
10
+ * one consumer of plugins, not the only one.
11
+ */
12
+ export interface CliCommand {
13
+ name(): string;
14
+ command(nameAndArgs: string, opts?: { hidden?: boolean }): CliCommand;
15
+ description(text: string): CliCommand;
16
+ alias(alias: string): CliCommand;
17
+ option(flags: string, description?: string, defaultValue?: unknown): CliCommand;
18
+ argument(name: string, description?: string): CliCommand;
19
+ action(fn: (...args: never[]) => unknown): CliCommand;
20
+ }
21
+
22
+ /// <reference types="bun-types">
23
+ declare global {
24
+ namespace App {
25
+ // augment in your own project via src/app.d.ts
26
+ interface Locals {}
27
+ interface Error {
28
+ message: string;
29
+ status?: number;
30
+ }
31
+ interface PageData {}
32
+ interface Platform {}
33
+ }
34
+ }
35
+
36
+ export interface Route {
37
+ path: string; // /blog/:slug
38
+ params: Record<string, string>;
39
+ filePath: string; // absolute path to +page.tsx
40
+ loadPath?: string; // absolute path to +page.ts
41
+ serverPath?: string; // absolute path to +server.ts
42
+ layoutPath?: string; // absolute path to +layout.tsx
43
+ }
44
+
45
+ export interface RouteInfo {
46
+ path: string; // /blog/:slug
47
+ filePath: string; // absolute path
48
+ type: string; // page, layout etc
49
+ }
50
+
51
+ export interface LoadContext {
52
+ request: Request;
53
+ params: Record<string, string>;
54
+ url: URL;
55
+ locals: Record<string, unknown>; // set by plugins/hooks
56
+ fetch: typeof globalThis.fetch;
57
+ /** The visitor's IP address; see RequestEvent.getClientAddress. */
58
+ getClientAddress: () => string;
59
+ /** Data returned by parent layouts' loads, merged outermost-first. */
60
+ parent: () => Promise<Record<string, unknown>>;
61
+ }
62
+
63
+ export interface TypedLoadContext<
64
+ P extends Record<string, string> = Record<string, string>,
65
+ > {
66
+ request: Request;
67
+ params: P;
68
+ url: URL;
69
+ locals: App.Locals;
70
+ fetch: typeof fetch;
71
+ /** Data returned by parent layouts' loads, merged outermost-first. */
72
+ parent: () => Promise<Record<string, unknown>>;
73
+ }
74
+
75
+ export interface RenderContext {
76
+ route: RouteInfo;
77
+ request: Request;
78
+ params: Record<string, string>;
79
+ data: unknown; // return value of load()
80
+ }
81
+
82
+ export interface PluginContext {
83
+ mode: "development" | "production";
84
+ plugins: ReadonlyMap<string, GrimoirePlugin>;
85
+ logger: ScopedLogger;
86
+ }
87
+
88
+ /**
89
+ * Which worker this process is, and how many there are.
90
+ *
91
+ * A plugin that creates one resource per worker — a connection pool, an
92
+ * embedded database handle — needs both numbers to divide a global budget
93
+ * correctly. `maxConnections: 20` across 4 workers is 5 each; a plugin that
94
+ * only knows its own index has no way to work that out and quietly opens 80.
95
+ *
96
+ * The coordinator sets both as env vars at spawn, so this resolves in a
97
+ * worker process. Running without a coordinator (`sigil dev`, or a single
98
+ * process) is one worker of one, which is the honest answer rather than a
99
+ * guess.
100
+ */
101
+ export interface WorkerContext {
102
+ /** 0-based within this mode. 0 when there is no coordinator. */
103
+ workerId: number;
104
+ /** Total workers across all modes. At least 1. */
105
+ workers: number;
106
+ /** Whether the server is in development mode. */
107
+ dev: boolean;
108
+ }
109
+
110
+ export function workerContext(env: Record<string, string | undefined> = process.env): WorkerContext {
111
+ const parsed = Number(env.GRIMOIRE_WORKER_INDEX);
112
+ const count = Number(env.GRIMOIRE_WORKER_COUNT);
113
+ return {
114
+ // A NaN here means no coordinator set them, which is one worker.
115
+ workerId: Number.isFinite(parsed) && parsed > 0 ? parsed - 1 : 0,
116
+ // Never 0: a budget divided by zero is Infinity, and a pool of
117
+ // Infinity is a crash at the first connection.
118
+ workers: Number.isFinite(count) && count > 0 ? count : 1,
119
+ dev: env.GRIMOIRE_MODE === "development",
120
+ };
121
+ }
122
+
123
+ export interface BuildResult {
124
+ success: boolean;
125
+ outputs: string[];
126
+ errors: string[];
127
+ }
128
+
129
+ export interface ServicesContext {
130
+ /**
131
+ * What the plugins before this one published, keyed the same way it will
132
+ * appear on `locals`. A snapshot: mutating it changes nothing.
133
+ */
134
+ services: Record<string, unknown>;
135
+ }
136
+
137
+ export interface GrimoirePlugin {
138
+ name: string;
139
+
140
+ /**
141
+ * Environment variables this plugin cannot run without. Checked when a
142
+ * server starts (not by `sigil build`); a missing or empty one fails the
143
+ * boot with every missing name listed.
144
+ */
145
+ requiredEnv?: string[];
146
+
147
+ // plugin lifecycle
148
+ onPluginsResolved?(ctx: PluginContext): void | Promise<void>;
149
+
150
+ /**
151
+ * Expose values on `locals` for the whole app to use.
152
+ *
153
+ * Returns an object merged into the per-request `locals` before any
154
+ * route, load, action or +server.ts handler runs, so a route reaches it
155
+ * as `locals.<key>` with nothing imported and nothing exported from
156
+ * sigil.config.ts.
157
+ *
158
+ * The merge is shallow and runs in plugin order, so a later plugin
159
+ * overriding an earlier plugin's key wins — same rule as every other
160
+ * merge in the pipeline. It is collected once, at startup, and the same
161
+ * values are merged into every request, so a request-scoped value here
162
+ * is a mistake.
163
+ *
164
+ * This is the place to open a connection pool. It runs only where
165
+ * requests are served — `sigil dev` and each `sigil start` worker, not
166
+ * the coordinator or `sigil build`, which do run `config()` — and before
167
+ * hooks.server.ts `init()`, so `init` can use what it opened.
168
+ *
169
+ * `ctx.services` is what the plugins before this one published, so a
170
+ * plugin can build on a resource another plugin owns instead of opening
171
+ * a second one. Register the SQL plugin first and a consumer reads
172
+ * `ctx.services.db` — the same client, not a parallel pool.
173
+ *
174
+ * It is a snapshot taken before this plugin runs, so a plugin registered
175
+ * before the one it needs sees nothing. Plugins that must not depend on
176
+ * ordering should fail loudly when the key is absent rather than quietly
177
+ * open their own fallback.
178
+ */
179
+ services?(ctx: ServicesContext): Record<string, unknown> | Promise<Record<string, unknown>>;
180
+
181
+ // server lifecycle
182
+ // we dont care about what the impl puts as websocket data therefore unknown.
183
+ onStart?(server: Server<unknown>): void | Promise<void>;
184
+ onStop?(reason: "shutdown" | "restart"): void | Promise<void>;
185
+
186
+ /**
187
+ * Wrap each request's route handling, with the same event and `resolve`
188
+ * as `handle` in hooks.server.ts.
189
+ *
190
+ * Unlike `onRequest`, which sees a raw Request, this sees the
191
+ * `RequestEvent`: it can read and set cookies, fill `event.locals`
192
+ * (`locals.user`) and answer a request itself without calling `resolve`.
193
+ * Plugin handles run in plugin order, then hooks.server.ts `handle`, so
194
+ * the app's own handle sees whatever the plugins put on `locals`.
195
+ */
196
+ handle?: Handle;
197
+
198
+ // request pipeline
199
+ onRequest?(
200
+ req: Request,
201
+ next: () => Promise<Response>,
202
+ ): Response | Promise<Response>;
203
+
204
+ // route lifecycle
205
+ onRouteLoad?(route: Route, context: LoadContext): void | Promise<void>;
206
+ /**
207
+ * Rewrite page HTML as it streams, without buffering it.
208
+ *
209
+ * Register handlers on the shared `HTMLRewriter` (Bun's built-in, backed by
210
+ * lol-html) and the framework runs them over the response body as it is
211
+ * produced, so the shell is rewritten and flushed while data is still
212
+ * loading. Streaming and the `loading` shell are untouched.
213
+ *
214
+ * ```ts
215
+ * rewriteHtml(rewriter, { request }) {
216
+ * rewriter.on("head", {
217
+ * element: (el) => el.append(`<script defer src="/stats.js"></script>`, { html: true }),
218
+ * });
219
+ * }
220
+ * ```
221
+ *
222
+ * Prefer this to `onRouteRender`. Only HTML bodies are rewritten; the
223
+ * navigation JSON, redirects and action results pass through.
224
+ */
225
+ rewriteHtml?(
226
+ rewriter: HTMLRewriter,
227
+ context: RenderContext,
228
+ ): void | Promise<void>;
229
+
230
+ /**
231
+ * Called after the page HTML is fully rendered.
232
+ * NOTE: When any plugin implements this hook, the streaming response is
233
+ * buffered into a single string. Streaming is preserved for routes where
234
+ * no plugin uses this hook. To avoid buffering, use onRequest to intercept
235
+ * at the Response level.
236
+ */
237
+ onRouteRender?(
238
+ html: string,
239
+ context: RenderContext,
240
+ ): string | Promise<string>;
241
+
242
+ // build
243
+ onBuildStart?(): void | Promise<void>;
244
+ onBuildEnd?(result: BuildResult): void | Promise<void>;
245
+
246
+ // config
247
+ /**
248
+ * Transform the project config at load time.
249
+ *
250
+ * May be async. Plugins need this to open a database connection or run
251
+ * migrations before the server starts, and a sync-only signature makes
252
+ * that impossible without blocking module scope. Every call site awaits
253
+ * the result, so a returned Promise is never mistaken for a config.
254
+ */
255
+ config?: (config: GrimoireConfig) =>
256
+ | GrimoireConfig
257
+ | undefined
258
+ | Promise<GrimoireConfig | undefined>;
259
+
260
+ /**
261
+ * Register CLI subcommands for this plugin.
262
+ *
263
+ * Called by the `sigil` CLI after it has loaded the project's sigil.config.ts,
264
+ * before command parsing, so a plugin can add `sigil jobs work` or similar.
265
+ * The project config is passed through as-is (after this plugin's own
266
+ * `config` transform, so it reflects the same values the server sees).
267
+ *
268
+ * Plugins without this hook are simply skipped. A plugin that throws here
269
+ * aborts the CLI with that error rather than failing obscurely later.
270
+ */
271
+ cli?: (
272
+ program: CliCommand,
273
+ context: GrimoireConfig,
274
+ ) => void | Promise<void>;
275
+
276
+ // process lifecycle
277
+
278
+ /**
279
+ * Runs AFTER Sigil/Babel compilation. Receives compiled JS, not source TSX.
280
+ * Suitable for string-level transforms (import rewriting, comment injection, etc.).
281
+ * Return null/undefined to pass through unchanged.
282
+ */
283
+ transform?(
284
+ code: string,
285
+ id: string,
286
+ ): string | null | undefined | Promise<string | null | undefined>;
287
+
288
+ /**
289
+ * Fires once after all workers are spawned and ready.
290
+ * Use for coordinator-level setup (e.g. opening a shared store).
291
+ */
292
+ onCoordinatorStart?(ctx: CoordinatorContext): void | Promise<void>;
293
+
294
+ /**
295
+ * Fires for each worker before Bun.spawn is called.
296
+ * Return WorkerEnv to inject env vars or set the worker name.
297
+ * ALL plugins are called and results are merged.
298
+ */
299
+ onWorkerSpawn?(
300
+ worker: WorkerDescriptor,
301
+ // biome-ignore lint/suspicious/noConfusingVoidType: doesn't have to return a thing.
302
+ ): WorkerEnv | void | Promise<WorkerEnv | void>;
303
+
304
+ /**
305
+ * Fires when a worker process is up and accepting requests.
306
+ */
307
+ onWorkerReady?(worker: WorkerDescriptor): void | Promise<void>;
308
+
309
+ /**
310
+ * Fires when a worker process exits.
311
+ * reason "crash" = unexpected exit, "intentional" = coordinator stopped it.
312
+ * Use for cleanup or respawn logic (see plugin-scale).
313
+ */
314
+ onWorkerDeath?(
315
+ worker: WorkerDescriptor,
316
+ reason: "crash" | "intentional",
317
+ ): void | Promise<void>;
318
+
319
+ // ── Locals boundary ────────────────────────────────────────
320
+
321
+ /**
322
+ * Called by coordinator before forwarding a request to a worker.
323
+ * Return a serialized string representation of locals.
324
+ * First plugin to return non-null wins. Default: signed JSON header.
325
+ */
326
+ serializeLocals?(locals: App.Locals): string | Promise<string>;
327
+
328
+ /**
329
+ * Called by worker on receiving a forwarded request.
330
+ * Return the deserialized locals object.
331
+ * First plugin to return non-null wins. Default: verify + JSON.parse.
332
+ */
333
+ deserializeLocals?(raw: string): App.Locals | Promise<App.Locals>;
334
+
335
+ // ── Routing policy ─────────────────────────────────────────
336
+
337
+ /**
338
+ * Called by coordinator to decide which worker handles a request.
339
+ * First plugin to return non-null wins.
340
+ * Default: ws routes → consistent hash, everything else → round robin.
341
+ * routes is the full RouteTree so plugins can make route-aware decisions.
342
+ */
343
+ routeRequest?(
344
+ req: Request,
345
+ workers: WorkerDescriptor[],
346
+ routes: RouteTree,
347
+ ): WorkerDescriptor | Promise<WorkerDescriptor>;
348
+ }
349
+
350
+ export interface GrimoireConfig {
351
+ port?: number;
352
+ host?: string;
353
+ /**
354
+ * The path the site is served under, for a host that gives you a
355
+ * sub-path (`/repo` on GitHub Pages) or a proxy that mounts the app there.
356
+ * Starts with a slash, no trailing slash. Default `""`, the root.
357
+ *
358
+ * Routes, `url.pathname` in loads and `matchRoute` never see it: the server
359
+ * strips it from every request. Everything that leaves the app does carry
360
+ * it, so links, `fetch`, `redirect()` and `navigate()` take `withBase()`
361
+ * paths. See `withBase` and `base`, exported from `@sigil-dev/grimoire`.
362
+ */
363
+ base?: string;
364
+ plugins?: GrimoirePlugin[];
365
+ routes?: string; // glob, default 'src/routes/**';
366
+ dev?: boolean;
367
+ devEditor?: boolean;
368
+ vitePort?: number;
369
+ alias?: Record<string, string>; // e.g. { "$lib": "src/lib" } — resolved relative to cwd
370
+ cspNonce?: string; // CSP nonce for <script>/<style> tags
371
+ bundleStrategy?: "split" | "single"; // 'split' (default) or 'single' bundle
372
+ /**
373
+ * Send a `Server-Timing` header (load / render durations) on page
374
+ * responses. Default: on in dev, off in production.
375
+ */
376
+ serverTiming?: boolean;
377
+ /**
378
+ * Environment the app cannot run without. A server (`sigil dev`,
379
+ * `sigil start`) refuses to boot while any listed name is unset or empty,
380
+ * and names all of them at once. `sigil build` does not check, since a
381
+ * build often runs somewhere that has no runtime secrets.
382
+ */
383
+ env?: { required?: string[] };
384
+
385
+ /**
386
+ * What `sigil build` does with the finished build. Omitted, the build is served by
387
+ * the Bun server (`sigil start`). See `@sigil-dev/grimoire/adapters/static`.
388
+ */
389
+ adapter?: import("./adapters/types").Adapter;
390
+ _skipBuild?: boolean;
391
+ /**
392
+ * Set by the worker: requests arrive from the coordinator, which is the only
393
+ * thing allowed to say who the user is through `X-Grimoire-Locals`. Without
394
+ * it that header is ignored, so a server reachable by the public cannot be
395
+ * handed forged `locals`.
396
+ */
397
+ _behindCoordinator?: boolean;
398
+ /**
399
+ * Force `dev` off after the plugins' config hooks have run, so a hook cannot
400
+ * turn it back on. Dev mode opens the HMR socket, the dependency-source
401
+ * endpoints and `/__grimoire__/open`, which spawns an editor from a query
402
+ * string, so anything that serves the public sets this.
403
+ */
404
+ _forceProduction?: boolean;
405
+ /**
406
+ * Production cache warming. Route modules are imported before the server
407
+ * takes traffic; `paths` are then requested through the real handler (once
408
+ * per worker, and again every `every` ms) so in-memory caches are full
409
+ * before a visitor arrives.
410
+ */
411
+ warm?: import("./server/warm.ts").WarmConfig;
412
+ /** Set by the worker: headers the server's own warm-up requests carry. */
413
+ _warmHeaders?: Record<string, string>;
414
+ }
415
+
416
+ export function defineConfig(config: GrimoireConfig): GrimoireConfig {
417
+ return config;
418
+ }
419
+
420
+ /** Generic load type for +page.server.ts. For per-route typed params import PageServerLoad from './$types'. */
421
+ export type PageServerLoad<
422
+ P extends Record<string, string> = Record<string, string>,
423
+ > = (
424
+ ctx: TypedLoadContext<P>,
425
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
426
+
427
+ /** Generic load type for +layout.server.ts. For per-route typed params import LayoutServerLoad from './$types'. */
428
+ export type LayoutServerLoad<
429
+ P extends Record<string, string> = Record<string, string>,
430
+ > = (
431
+ ctx: TypedLoadContext<P>,
432
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
433
+
434
+ /** Generic handler type for +server.ts API routes. For per-route typed params import RequestHandler from './$types'. */
435
+ export type RequestHandler<
436
+ P extends Record<string, string> = Record<string, string>,
437
+ > = (ctx: TypedLoadContext<P>) => Response | Promise<Response>;
438
+
439
+ /**
440
+ * Shape of the `websocket` export in a +server.ts file.
441
+ * T is the resolved ws.data shape (params + upgrade() return value).
442
+ * For per-route typing import WebSocketHandler from './$types'.
443
+ */
444
+ export interface WsRouteHandler<T = Record<string, unknown>> {
445
+ open?(ws: ServerWebSocket<T>): void | Promise<void>;
446
+ message?(ws: ServerWebSocket<T>, data: string | Buffer): void | Promise<void>;
447
+ close?(
448
+ ws: ServerWebSocket<T>,
449
+ code: number,
450
+ reason?: string,
451
+ ): void | Promise<void>;
452
+ drain?(ws: ServerWebSocket<T>): void | Promise<void>;
453
+ }
454
+
455
+ // ***BIG ONE***
456
+
457
+ /**
458
+ * Built-in worker modes understood by the coordinator.
459
+ * Plugins may define custom modes via WorkerMode.
460
+ */
461
+ export type BuiltinWorkerMode = "api" | "frontend" | "ws" | "full";
462
+
463
+ /**
464
+ * Open union — (string & {}) preserves autocomplete for built-in
465
+ * values while allowing plugin-defined modes like "db" or "queue".
466
+ */
467
+ export type WorkerMode = BuiltinWorkerMode | (string & {});
468
+
469
+ /**
470
+ * Describes a single worker process managed by the coordinator.
471
+ * Coordinator derives behavior from routes, not mode string —
472
+ * mode is informational and for plugin use only.
473
+ */
474
+ export interface WorkerDescriptor {
475
+ mode: WorkerMode;
476
+ index: number; // index within this mode (api-0, api-1...)
477
+ globalIndex: number; // index across all workers
478
+ internalUrl: string; // coordinator → worker base URL
479
+ name?: string; // set by namepool or onWorkerSpawn
480
+ routes: RouteFile[]; // route slice assigned by coordinator
481
+ pid?: number; // set after Bun.spawn
482
+ }
483
+
484
+ /**
485
+ * Return value of onWorkerSpawn. All plugins are called and results
486
+ * are merged — env from all plugins is combined, last name wins.
487
+ */
488
+ export interface WorkerEnv {
489
+ env?: Record<string, string>;
490
+ name?: string;
491
+ }
492
+
493
+ /**
494
+ * Passed to onCoordinatorStart once the coordinator is fully initialized.
495
+ */
496
+ export interface CoordinatorContext {
497
+ workers: WorkerDescriptor[];
498
+ port: number;
499
+ secret: string; // ephemeral signing secret, generated per-run
500
+ routes: RouteTree;
501
+ }