@sigil-dev/grimoire 0.8.5 → 0.9.0

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.
package/src/types.ts CHANGED
@@ -1,270 +1,282 @@
1
- import type { ServerWebSocket } from "bun";
2
- import type { RouteFile, RouteTree } from "./routing/scanner";
3
-
4
- /// <reference types="bun-types">
5
- declare global {
6
- namespace App {
7
- // augment in your own project via src/app.d.ts
8
- interface Locals {}
9
- interface Error {
10
- message: string;
11
- status?: number;
12
- }
13
- interface PageData {}
14
- interface Platform {}
15
- }
16
- }
17
-
18
- export interface Route {
19
- path: string; // /blog/:slug
20
- params: Record<string, string>;
21
- filePath: string; // absolute path to +page.tsx
22
- loadPath?: string; // absolute path to +page.ts
23
- serverPath?: string; // absolute path to +server.ts
24
- layoutPath?: string; // absolute path to +layout.tsx
25
- }
26
-
27
- export interface RouteInfo {
28
- path: string; // /blog/:slug
29
- filePath: string; // absolute path
30
- type: string; // page, layout etc
31
- }
32
-
33
- export interface LoadContext {
34
- request: Request;
35
- params: Record<string, string>;
36
- url: URL;
37
- locals: Record<string, unknown>; // set by plugins/hooks
38
- }
39
-
40
- export interface TypedLoadContext<
41
- P extends Record<string, string> = Record<string, string>,
42
- > {
43
- request: Request;
44
- params: P;
45
- url: URL;
46
- locals: App.Locals;
47
- }
48
-
49
- export interface RenderContext {
50
- route: RouteInfo;
51
- request: Request;
52
- params: Record<string, string>;
53
- data: unknown; // return value of load()
54
- }
55
-
56
- export interface BuildResult {
57
- success: boolean;
58
- outputs: string[];
59
- errors: string[];
60
- }
61
- export type Server = { port: number; hostname: string; stop(): void };
62
-
63
- export interface GrimoirePlugin {
64
- name: string;
65
-
66
- // server lifecycle
67
- onStart?(server: Server): void | Promise<void>;
68
- onStop?(reason: "shutdown" | "restart"): void | Promise<void>;
69
-
70
- // request pipeline
71
- onRequest?(
72
- req: Request,
73
- next: () => Promise<Response>,
74
- ): Response | Promise<Response>;
75
-
76
- // route lifecycle
77
- onRouteLoad?(route: Route, context: LoadContext): void | Promise<void>;
78
- /**
79
- * Called after the page HTML is fully rendered.
80
- * NOTE: When any plugin implements this hook, the streaming response is
81
- * buffered into a single string. Streaming is preserved for routes where
82
- * no plugin uses this hook. To avoid buffering, use onRequest to intercept
83
- * at the Response level.
84
- */
85
- onRouteRender?(
86
- html: string,
87
- context: RenderContext,
88
- ): string | Promise<string>;
89
-
90
- // build
91
- onBuildStart?(): void | Promise<void>;
92
- onBuildEnd?(result: BuildResult): void | Promise<void>;
93
-
94
- // config
95
- config?: (config: GrimoireConfig) => GrimoireConfig | undefined;
96
-
97
- // process lifecycle
98
-
99
- /**
100
- * Runs AFTER Sigil/Babel compilation. Receives compiled JS, not source TSX.
101
- * Suitable for string-level transforms (import rewriting, comment injection, etc.).
102
- * Return null/undefined to pass through unchanged.
103
- */
104
- transform?(
105
- code: string,
106
- id: string,
107
- ): string | null | undefined | Promise<string | null | undefined>;
108
-
109
- /**
110
- * Fires once after all workers are spawned and ready.
111
- * Use for coordinator-level setup (e.g. opening a shared store).
112
- */
113
- onCoordinatorStart?(ctx: CoordinatorContext): void | Promise<void>;
114
-
115
- /**
116
- * Fires for each worker before Bun.spawn is called.
117
- * Return WorkerEnv to inject env vars or set the worker name.
118
- * ALL plugins are called and results are merged.
119
- */
120
- onWorkerSpawn?(
121
- worker: WorkerDescriptor,
122
- // biome-ignore lint/suspicious/noConfusingVoidType: doesn't have to return a thing.
123
- ): WorkerEnv | void | Promise<WorkerEnv | void>;
124
-
125
- /**
126
- * Fires when a worker process is up and accepting requests.
127
- */
128
- onWorkerReady?(worker: WorkerDescriptor): void | Promise<void>;
129
-
130
- /**
131
- * Fires when a worker process exits.
132
- * reason "crash" = unexpected exit, "intentional" = coordinator stopped it.
133
- * Use for cleanup or respawn logic (see plugin-scale).
134
- */
135
- onWorkerDeath?(
136
- worker: WorkerDescriptor,
137
- reason: "crash" | "intentional",
138
- ): void | Promise<void>;
139
-
140
- // ── Locals boundary ────────────────────────────────────────
141
-
142
- /**
143
- * Called by coordinator before forwarding a request to a worker.
144
- * Return a serialized string representation of locals.
145
- * First plugin to return non-null wins. Default: signed JSON header.
146
- */
147
- serializeLocals?(locals: App.Locals): string | Promise<string>;
148
-
149
- /**
150
- * Called by worker on receiving a forwarded request.
151
- * Return the deserialized locals object.
152
- * First plugin to return non-null wins. Default: verify + JSON.parse.
153
- */
154
- deserializeLocals?(raw: string): App.Locals | Promise<App.Locals>;
155
-
156
- // ── Routing policy ─────────────────────────────────────────
157
-
158
- /**
159
- * Called by coordinator to decide which worker handles a request.
160
- * First plugin to return non-null wins.
161
- * Default: ws routes → consistent hash, everything else → round robin.
162
- * routes is the full RouteTree so plugins can make route-aware decisions.
163
- */
164
- routeRequest?(
165
- req: Request,
166
- workers: WorkerDescriptor[],
167
- routes: RouteTree,
168
- ): WorkerDescriptor | Promise<WorkerDescriptor>;
169
- }
170
-
171
- export interface GrimoireConfig {
172
- port?: number;
173
- host?: string;
174
- plugins?: GrimoirePlugin[];
175
- routes?: string; // glob, default 'src/routes/**';
176
- dev?: boolean;
177
- devEditor?: boolean;
178
- vitePort?: number;
179
- alias?: Record<string, string>; // e.g. { "$lib": "src/lib" } — resolved relative to cwd
180
- cspNonce?: string; // CSP nonce for <script>/<style> tags
181
- bundleStrategy?: "split" | "single"; // 'split' (default) or 'single' bundle
182
- _skipBuild?: boolean;
183
- }
184
-
185
- export function defineConfig(config: GrimoireConfig): GrimoireConfig {
186
- return config;
187
- }
188
-
189
- /** Generic load type for +page.server.ts. For per-route typed params import PageServerLoad from './$types'. */
190
- export type PageServerLoad<
191
- P extends Record<string, string> = Record<string, string>,
192
- > = (
193
- ctx: TypedLoadContext<P>,
194
- ) => Record<string, unknown> | Promise<Record<string, unknown>>;
195
-
196
- /** Generic load type for +layout.server.ts. For per-route typed params import LayoutServerLoad from './$types'. */
197
- export type LayoutServerLoad<
198
- P extends Record<string, string> = Record<string, string>,
199
- > = (
200
- ctx: TypedLoadContext<P>,
201
- ) => Record<string, unknown> | Promise<Record<string, unknown>>;
202
-
203
- /** Generic handler type for +server.ts API routes. For per-route typed params import RequestHandler from './$types'. */
204
- export type RequestHandler<
205
- P extends Record<string, string> = Record<string, string>,
206
- > = (ctx: TypedLoadContext<P>) => Response | Promise<Response>;
207
-
208
- /**
209
- * Shape of the `websocket` export in a +server.ts file.
210
- * T is the resolved ws.data shape (params + upgrade() return value).
211
- * For per-route typing import WebSocketHandler from './$types'.
212
- */
213
- export interface WsRouteHandler<T = Record<string, unknown>> {
214
- open?(ws: ServerWebSocket<T>): void | Promise<void>;
215
- message?(ws: ServerWebSocket<T>, data: string | Buffer): void | Promise<void>;
216
- close?(
217
- ws: ServerWebSocket<T>,
218
- code: number,
219
- reason?: string,
220
- ): void | Promise<void>;
221
- drain?(ws: ServerWebSocket<T>): void | Promise<void>;
222
- }
223
-
224
- // ***BIG ONE***
225
-
226
- /**
227
- * Built-in worker modes understood by the coordinator.
228
- * Plugins may define custom modes via WorkerMode.
229
- */
230
- export type BuiltinWorkerMode = "api" | "frontend" | "ws" | "full";
231
-
232
- /**
233
- * Open union — (string & {}) preserves autocomplete for built-in
234
- * values while allowing plugin-defined modes like "db" or "queue".
235
- */
236
- export type WorkerMode = BuiltinWorkerMode | (string & {});
237
-
238
- /**
239
- * Describes a single worker process managed by the coordinator.
240
- * Coordinator derives behavior from routes, not mode string —
241
- * mode is informational and for plugin use only.
242
- */
243
- export interface WorkerDescriptor {
244
- mode: WorkerMode;
245
- index: number; // index within this mode (api-0, api-1...)
246
- globalIndex: number; // index across all workers
247
- internalUrl: string; // coordinator → worker base URL
248
- name?: string; // set by namepool or onWorkerSpawn
249
- routes: RouteFile[]; // route slice assigned by coordinator
250
- pid?: number; // set after Bun.spawn
251
- }
252
-
253
- /**
254
- * Return value of onWorkerSpawn. All plugins are called and results
255
- * are merged — env from all plugins is combined, last name wins.
256
- */
257
- export interface WorkerEnv {
258
- env?: Record<string, string>;
259
- name?: string;
260
- }
261
-
262
- /**
263
- * Passed to onCoordinatorStart once the coordinator is fully initialized.
264
- */
265
- export interface CoordinatorContext {
266
- workers: WorkerDescriptor[];
267
- port: number;
268
- secret: string; // ephemeral signing secret, generated per-run
269
- routes: RouteTree;
270
- }
1
+ import type { ServerWebSocket } from "bun";
2
+ import type { RouteFile, RouteTree } from "./routing/scanner";
3
+ import type { ScopedLogger } from "./logger";
4
+
5
+ /// <reference types="bun-types">
6
+ declare global {
7
+ namespace App {
8
+ // augment in your own project via src/app.d.ts
9
+ interface Locals {}
10
+ interface Error {
11
+ message: string;
12
+ status?: number;
13
+ }
14
+ interface PageData {}
15
+ interface Platform {}
16
+ }
17
+ }
18
+
19
+ export interface Route {
20
+ path: string; // /blog/:slug
21
+ params: Record<string, string>;
22
+ filePath: string; // absolute path to +page.tsx
23
+ loadPath?: string; // absolute path to +page.ts
24
+ serverPath?: string; // absolute path to +server.ts
25
+ layoutPath?: string; // absolute path to +layout.tsx
26
+ }
27
+
28
+ export interface RouteInfo {
29
+ path: string; // /blog/:slug
30
+ filePath: string; // absolute path
31
+ type: string; // page, layout etc
32
+ }
33
+
34
+ export interface LoadContext {
35
+ request: Request;
36
+ params: Record<string, string>;
37
+ url: URL;
38
+ locals: Record<string, unknown>; // set by plugins/hooks
39
+ fetch: typeof globalThis.fetch; // ← add
40
+ }
41
+
42
+ export interface TypedLoadContext<
43
+ P extends Record<string, string> = Record<string, string>,
44
+ > {
45
+ request: Request;
46
+ params: P;
47
+ url: URL;
48
+ locals: App.Locals;
49
+ fetch: typeof fetch;
50
+ }
51
+
52
+ export interface RenderContext {
53
+ route: RouteInfo;
54
+ request: Request;
55
+ params: Record<string, string>;
56
+ data: unknown; // return value of load()
57
+ }
58
+
59
+ export interface PluginContext {
60
+ mode: "development" | "production";
61
+ plugins: ReadonlyMap<string, GrimoirePlugin>;
62
+ logger: ScopedLogger;
63
+ }
64
+
65
+ export interface BuildResult {
66
+ success: boolean;
67
+ outputs: string[];
68
+ errors: string[];
69
+ }
70
+ export type Server = { port: number; hostname: string; stop(): void };
71
+
72
+ export interface GrimoirePlugin {
73
+ name: string;
74
+
75
+ // plugin lifecycle
76
+ onPluginsResolved?(ctx: PluginContext): void | Promise<void>;
77
+
78
+ // server lifecycle
79
+ onStart?(server: Server): void | Promise<void>;
80
+ onStop?(reason: "shutdown" | "restart"): void | Promise<void>;
81
+
82
+ // request pipeline
83
+ onRequest?(
84
+ req: Request,
85
+ next: () => Promise<Response>,
86
+ ): Response | Promise<Response>;
87
+
88
+ // route lifecycle
89
+ onRouteLoad?(route: Route, context: LoadContext): void | Promise<void>;
90
+ /**
91
+ * Called after the page HTML is fully rendered.
92
+ * NOTE: When any plugin implements this hook, the streaming response is
93
+ * buffered into a single string. Streaming is preserved for routes where
94
+ * no plugin uses this hook. To avoid buffering, use onRequest to intercept
95
+ * at the Response level.
96
+ */
97
+ onRouteRender?(
98
+ html: string,
99
+ context: RenderContext,
100
+ ): string | Promise<string>;
101
+
102
+ // build
103
+ onBuildStart?(): void | Promise<void>;
104
+ onBuildEnd?(result: BuildResult): void | Promise<void>;
105
+
106
+ // config
107
+ config?: (config: GrimoireConfig) => GrimoireConfig | undefined;
108
+
109
+ // process lifecycle
110
+
111
+ /**
112
+ * Runs AFTER Sigil/Babel compilation. Receives compiled JS, not source TSX.
113
+ * Suitable for string-level transforms (import rewriting, comment injection, etc.).
114
+ * Return null/undefined to pass through unchanged.
115
+ */
116
+ transform?(
117
+ code: string,
118
+ id: string,
119
+ ): string | null | undefined | Promise<string | null | undefined>;
120
+
121
+ /**
122
+ * Fires once after all workers are spawned and ready.
123
+ * Use for coordinator-level setup (e.g. opening a shared store).
124
+ */
125
+ onCoordinatorStart?(ctx: CoordinatorContext): void | Promise<void>;
126
+
127
+ /**
128
+ * Fires for each worker before Bun.spawn is called.
129
+ * Return WorkerEnv to inject env vars or set the worker name.
130
+ * ALL plugins are called and results are merged.
131
+ */
132
+ onWorkerSpawn?(
133
+ worker: WorkerDescriptor,
134
+ // biome-ignore lint/suspicious/noConfusingVoidType: doesn't have to return a thing.
135
+ ): WorkerEnv | void | Promise<WorkerEnv | void>;
136
+
137
+ /**
138
+ * Fires when a worker process is up and accepting requests.
139
+ */
140
+ onWorkerReady?(worker: WorkerDescriptor): void | Promise<void>;
141
+
142
+ /**
143
+ * Fires when a worker process exits.
144
+ * reason "crash" = unexpected exit, "intentional" = coordinator stopped it.
145
+ * Use for cleanup or respawn logic (see plugin-scale).
146
+ */
147
+ onWorkerDeath?(
148
+ worker: WorkerDescriptor,
149
+ reason: "crash" | "intentional",
150
+ ): void | Promise<void>;
151
+
152
+ // ── Locals boundary ────────────────────────────────────────
153
+
154
+ /**
155
+ * Called by coordinator before forwarding a request to a worker.
156
+ * Return a serialized string representation of locals.
157
+ * First plugin to return non-null wins. Default: signed JSON header.
158
+ */
159
+ serializeLocals?(locals: App.Locals): string | Promise<string>;
160
+
161
+ /**
162
+ * Called by worker on receiving a forwarded request.
163
+ * Return the deserialized locals object.
164
+ * First plugin to return non-null wins. Default: verify + JSON.parse.
165
+ */
166
+ deserializeLocals?(raw: string): App.Locals | Promise<App.Locals>;
167
+
168
+ // ── Routing policy ─────────────────────────────────────────
169
+
170
+ /**
171
+ * Called by coordinator to decide which worker handles a request.
172
+ * First plugin to return non-null wins.
173
+ * Default: ws routes → consistent hash, everything else → round robin.
174
+ * routes is the full RouteTree so plugins can make route-aware decisions.
175
+ */
176
+ routeRequest?(
177
+ req: Request,
178
+ workers: WorkerDescriptor[],
179
+ routes: RouteTree,
180
+ ): WorkerDescriptor | Promise<WorkerDescriptor>;
181
+ }
182
+
183
+ export interface GrimoireConfig {
184
+ port?: number;
185
+ host?: string;
186
+ plugins?: GrimoirePlugin[];
187
+ routes?: string; // glob, default 'src/routes/**';
188
+ dev?: boolean;
189
+ devEditor?: boolean;
190
+ vitePort?: number;
191
+ alias?: Record<string, string>; // e.g. { "$lib": "src/lib" } — resolved relative to cwd
192
+ cspNonce?: string; // CSP nonce for <script>/<style> tags
193
+ bundleStrategy?: "split" | "single"; // 'split' (default) or 'single' bundle
194
+ _skipBuild?: boolean;
195
+ }
196
+
197
+ export function defineConfig(config: GrimoireConfig): GrimoireConfig {
198
+ return config;
199
+ }
200
+
201
+ /** Generic load type for +page.server.ts. For per-route typed params import PageServerLoad from './$types'. */
202
+ export type PageServerLoad<
203
+ P extends Record<string, string> = Record<string, string>,
204
+ > = (
205
+ ctx: TypedLoadContext<P>,
206
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
207
+
208
+ /** Generic load type for +layout.server.ts. For per-route typed params import LayoutServerLoad from './$types'. */
209
+ export type LayoutServerLoad<
210
+ P extends Record<string, string> = Record<string, string>,
211
+ > = (
212
+ ctx: TypedLoadContext<P>,
213
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
214
+
215
+ /** Generic handler type for +server.ts API routes. For per-route typed params import RequestHandler from './$types'. */
216
+ export type RequestHandler<
217
+ P extends Record<string, string> = Record<string, string>,
218
+ > = (ctx: TypedLoadContext<P>) => Response | Promise<Response>;
219
+
220
+ /**
221
+ * Shape of the `websocket` export in a +server.ts file.
222
+ * T is the resolved ws.data shape (params + upgrade() return value).
223
+ * For per-route typing import WebSocketHandler from './$types'.
224
+ */
225
+ export interface WsRouteHandler<T = Record<string, unknown>> {
226
+ open?(ws: ServerWebSocket<T>): void | Promise<void>;
227
+ message?(ws: ServerWebSocket<T>, data: string | Buffer): void | Promise<void>;
228
+ close?(
229
+ ws: ServerWebSocket<T>,
230
+ code: number,
231
+ reason?: string,
232
+ ): void | Promise<void>;
233
+ drain?(ws: ServerWebSocket<T>): void | Promise<void>;
234
+ }
235
+
236
+ // ***BIG ONE***
237
+
238
+ /**
239
+ * Built-in worker modes understood by the coordinator.
240
+ * Plugins may define custom modes via WorkerMode.
241
+ */
242
+ export type BuiltinWorkerMode = "api" | "frontend" | "ws" | "full";
243
+
244
+ /**
245
+ * Open union — (string & {}) preserves autocomplete for built-in
246
+ * values while allowing plugin-defined modes like "db" or "queue".
247
+ */
248
+ export type WorkerMode = BuiltinWorkerMode | (string & {});
249
+
250
+ /**
251
+ * Describes a single worker process managed by the coordinator.
252
+ * Coordinator derives behavior from routes, not mode string —
253
+ * mode is informational and for plugin use only.
254
+ */
255
+ export interface WorkerDescriptor {
256
+ mode: WorkerMode;
257
+ index: number; // index within this mode (api-0, api-1...)
258
+ globalIndex: number; // index across all workers
259
+ internalUrl: string; // coordinator → worker base URL
260
+ name?: string; // set by namepool or onWorkerSpawn
261
+ routes: RouteFile[]; // route slice assigned by coordinator
262
+ pid?: number; // set after Bun.spawn
263
+ }
264
+
265
+ /**
266
+ * Return value of onWorkerSpawn. All plugins are called and results
267
+ * are merged — env from all plugins is combined, last name wins.
268
+ */
269
+ export interface WorkerEnv {
270
+ env?: Record<string, string>;
271
+ name?: string;
272
+ }
273
+
274
+ /**
275
+ * Passed to onCoordinatorStart once the coordinator is fully initialized.
276
+ */
277
+ export interface CoordinatorContext {
278
+ workers: WorkerDescriptor[];
279
+ port: number;
280
+ secret: string; // ephemeral signing secret, generated per-run
281
+ routes: RouteTree;
282
+ }
@@ -0,0 +1,38 @@
1
+ import { describe, test, expect, beforeEach } from "bun:test";
2
+ import { depends, hasDep, startCollecting, stopCollecting, clearDeps } from "../src/client/deps.ts";
3
+
4
+ beforeEach(() => clearDeps("/"));
5
+
6
+ describe("depends", () => {
7
+ test("no-op outside collection", () => {
8
+ depends("posts");
9
+ expect(hasDep("/", "posts")).toBe(false);
10
+ });
11
+
12
+ test("registers key during collection", () => {
13
+ startCollecting();
14
+ depends("posts");
15
+ stopCollecting("/");
16
+ expect(hasDep("/", "posts")).toBe(true);
17
+ });
18
+
19
+ test("multiple keys", () => {
20
+ startCollecting();
21
+ depends("posts");
22
+ depends("tags");
23
+ stopCollecting("/");
24
+ expect(hasDep("/", "posts")).toBe(true);
25
+ expect(hasDep("/", "tags")).toBe(true);
26
+ });
27
+
28
+ test("cleared on next collection", () => {
29
+ startCollecting();
30
+ depends("posts");
31
+ stopCollecting("/");
32
+ startCollecting();
33
+ depends("comments");
34
+ stopCollecting("/");
35
+ expect(hasDep("/", "posts")).toBe(false);
36
+ expect(hasDep("/", "comments")).toBe(true);
37
+ });
38
+ });