@sigil-dev/grimoire 0.9.4 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/index.ts +37 -37
  2. package/package.json +3 -3
  3. package/preload.js +3 -3
  4. package/server.ts +19 -19
  5. package/src/client/deps.ts +36 -36
  6. package/src/client/enhance.ts +102 -102
  7. package/src/client/head.ts +30 -30
  8. package/src/client/index.ts +5 -5
  9. package/src/client/router.ts +42 -20
  10. package/src/client/scope.ts +22 -22
  11. package/src/dev/compile-module.ts +215 -163
  12. package/src/dev/effect-registry.ts +23 -23
  13. package/src/dev/graph.ts +109 -114
  14. package/src/dev/hmr-client.ts +202 -185
  15. package/src/dev/hmr-server.ts +261 -187
  16. package/src/dev/loader.ts +120 -47
  17. package/src/dev/paths.ts +14 -14
  18. package/src/dev/resolve.ts +70 -0
  19. package/src/dev/runtime-bundle.ts +52 -52
  20. package/src/dev/scan.ts +78 -0
  21. package/src/dev/watcher.ts +69 -47
  22. package/src/env/dynamic-private.ts +19 -19
  23. package/src/env/dynamic-public.ts +22 -22
  24. package/src/env/index.ts +25 -25
  25. package/src/env/plugin.ts +19 -19
  26. package/src/env/private.ts +5 -5
  27. package/src/env/public.ts +7 -7
  28. package/src/env/typegen.ts +61 -61
  29. package/src/headers.ts +114 -114
  30. package/src/integrations/vite.ts +73 -73
  31. package/src/logger/index.ts +4 -4
  32. package/src/logger/instance.ts +6 -6
  33. package/src/logger/logger.ts +113 -113
  34. package/src/logger/request-middleware.ts +24 -24
  35. package/src/logger/transports.ts +117 -117
  36. package/src/logger/types.ts +39 -39
  37. package/src/rendering/head.ts +52 -47
  38. package/src/rendering/hydrate.ts +16 -3
  39. package/src/rendering/index.ts +10 -6
  40. package/src/rendering/ssrPlugin.ts +78 -69
  41. package/src/routing/manifest-gen.ts +55 -55
  42. package/src/routing/router.ts +135 -135
  43. package/src/routing/scanner.ts +196 -187
  44. package/src/routing/transform-routes.ts +102 -102
  45. package/src/sentinels/error.ts +52 -52
  46. package/src/sentinels/fail.ts +41 -41
  47. package/src/sentinels/redirect.ts +35 -35
  48. package/src/server/build.ts +250 -255
  49. package/src/server/context.ts +10 -10
  50. package/src/server/cookie-utils.ts +66 -66
  51. package/src/server/coordinator.ts +364 -364
  52. package/src/server/hooks.ts +114 -114
  53. package/src/server/index.ts +711 -677
  54. package/src/server/interactive.ts +56 -56
  55. package/src/server/plugins.ts +121 -121
  56. package/src/server/worker.ts +58 -58
  57. package/src/typegen/index.ts +389 -389
  58. package/src/types.ts +286 -286
  59. package/test/client-router.test.ts +295 -298
  60. package/test/context.test.ts +52 -52
  61. package/test/env.test.ts +90 -90
  62. package/test/exports.test.ts +37 -37
  63. package/test/fail.test.ts +46 -46
  64. package/test/headers.test.ts +100 -100
  65. package/test/hmr.test.ts +426 -0
  66. package/test/hydration.test.ts +119 -119
  67. package/test/middleware.test.ts +223 -223
  68. package/test/preload.ts +5 -5
  69. package/test/redirect-error.test.ts +112 -112
  70. package/test/rendering.test.ts +719 -728
  71. package/test/routing.test.ts +197 -194
  72. package/test/scanning.test.ts +314 -254
  73. package/test/scope.test.ts +195 -195
  74. package/test/server.test.ts +360 -354
  75. package/test/streaming.test.ts +242 -242
  76. package/test/transform-routes.test.ts +87 -87
  77. package/test/typegen.test.ts +697 -697
  78. package/tsconfig.json +10 -10
@@ -1,389 +1,389 @@
1
- import { mkdirSync, writeFileSync } from "node:fs";
2
- import { mkdir } from "node:fs/promises";
3
- import { dirname, isAbsolute, join, relative } from "node:path";
4
- import type { RouteFile, RouteTree } from "../routing/scanner.ts";
5
-
6
- export interface TypegenConfig {
7
- projectRoot: string;
8
- routesDir: string;
9
- outDir: string; // absolute path to .grimoire/types
10
- }
11
-
12
- export interface RouteGroup {
13
- dir: string;
14
- paramNames: string[];
15
- optionalParamNames: string[];
16
- restParamNames: string[];
17
- page?: RouteFile;
18
- pageServer?: RouteFile;
19
- layout?: RouteFile;
20
- layoutServer?: RouteFile;
21
- server?: RouteFile;
22
- error?: RouteFile;
23
- }
24
-
25
- // On Windows, relative() returns the absolute `to` path when src and dest are on
26
- // different drives. Detect that and fall back to routes-dir-relative so join()
27
- // doesn't produce an invalid double-rooted path like "D:\out\C:\Users\...".
28
- function safeRelativeDir(
29
- projectRoot: string,
30
- routesDir: string,
31
- groupDir: string,
32
- ): string {
33
- const rel = relative(projectRoot, groupDir);
34
- return isAbsolute(rel) ? relative(routesDir, groupDir) : rel;
35
- }
36
-
37
- export function groupByDirectory(tree: RouteTree): Map<string, RouteGroup> {
38
- const groups = new Map<string, RouteGroup>();
39
-
40
- // Only process + convention files — simple files don't get $types
41
- const files: RouteFile[] = [
42
- ...tree.routes.filter((f) => f.type !== "simple"),
43
- ...tree.layouts,
44
- ...tree.servers,
45
- ...tree.errors,
46
- ];
47
-
48
- for (const file of files) {
49
- const dir = dirname(file.filePath);
50
- if (!groups.has(dir)) {
51
- groups.set(dir, {
52
- dir,
53
- paramNames: file.paramNames,
54
- optionalParamNames: file.optionalParamNames,
55
- restParamNames: file.restParamNames,
56
- });
57
- }
58
- const g = groups.get(dir)!;
59
- if (file.paramNames.length > g.paramNames.length) {
60
- g.paramNames = file.paramNames;
61
- }
62
- if (file.optionalParamNames.length > g.optionalParamNames.length) {
63
- g.optionalParamNames = file.optionalParamNames;
64
- }
65
- if (file.restParamNames.length > g.restParamNames.length) {
66
- g.restParamNames = file.restParamNames;
67
- }
68
- switch (file.type) {
69
- case "page":
70
- g.page = file;
71
- break;
72
- case "pageServer":
73
- g.pageServer = file;
74
- break;
75
- case "layout":
76
- g.layout = file;
77
- break;
78
- case "layoutServer":
79
- g.layoutServer = file;
80
- break;
81
- case "server":
82
- g.server = file;
83
- break;
84
- case "error":
85
- g.error = file;
86
- break;
87
- }
88
- }
89
-
90
- return groups;
91
- }
92
-
93
- export function toImportPath(from: string, to: string): string {
94
- return relative(from, to)
95
- .replace(/\\/g, "/")
96
- .replace(/\.tsx?$/, ".js");
97
- }
98
-
99
- export function buildParams(
100
- paramNames: string[],
101
- optionalParamNames: string[] = [],
102
- restParamNames: string[] = [],
103
- ): string {
104
- const all = [
105
- ...paramNames.map((p) => ` ${p}: string;`),
106
- ...optionalParamNames.map((p) => ` ${p}: string | undefined;`),
107
- ...restParamNames.map((p) => ` ${p}: string;`),
108
- ];
109
- if (all.length === 0) return "{}";
110
- return `{\n${all.join("\n")}\n}`;
111
- }
112
-
113
- function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
114
- const lines: string[] = [
115
- "// Auto-generated by @sigil-dev/grimoire — do not edit",
116
- "",
117
- ];
118
-
119
- const paramsType = buildParams(
120
- group.paramNames,
121
- group.optionalParamNames,
122
- group.restParamNames,
123
- );
124
-
125
- // --- Params ---
126
- lines.push(`export type Params = ${paramsType};`, "");
127
-
128
- // --- PageData from +page.server.ts ---
129
- if (group.pageServer) {
130
- const imp = toImportPath(outFileDir, group.pageServer.filePath);
131
- // Use `typeof import(...)` (not `import type * as NS`) so the module type
132
- // can be used in `keyof` and indexed access without TS2709.
133
- lines.push(
134
- `type _PS = typeof import("${imp}");`,
135
- `export type PageData = "load" extends keyof _PS`,
136
- ` ? Awaited<ReturnType<_PS["load"]>>`,
137
- ` : Record<string, never>;`,
138
- "",
139
- );
140
- lines.push(
141
- `export type PageProps = { data: PageData; params: Params };`,
142
- "",
143
- );
144
- // PageServerLoad — annotate parameter, NOT return type, to preserve inference
145
- lines.push(
146
- `/** Annotate the load() parameter only — not the return type — or PageData loses its concrete keys. */`,
147
- `export type PageServerLoad = (ctx: {`,
148
- ` params: Params;`,
149
- ` request: Request;`,
150
- ` url: URL;`,
151
- ` locals: App.Locals;`,
152
- ` parent: () => Promise<Record<string, unknown>>;`,
153
- `}) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
154
- "",
155
- );
156
- // Actions — all exports except load and default
157
- lines.push(
158
- `type ActionCookies = {`,
159
- ` get(name: string): string | undefined;`,
160
- ` set(name: string, value: string, options?: {`,
161
- ` path?: string;`,
162
- ` domain?: string;`,
163
- ` maxAge?: number;`,
164
- ` expires?: Date;`,
165
- ` httpOnly?: boolean;`,
166
- ` secure?: boolean;`,
167
- ` sameSite?: "strict" | "lax" | "none";`,
168
- ` }): void;`,
169
- ` delete(name: string): void;`,
170
- `};`,
171
- `type _ActionKeys = Exclude<keyof _PS, "load" | "default">;`,
172
- `export type Actions = {`,
173
- ` [K in _ActionKeys]: (ctx: {`,
174
- ` params: Params;`,
175
- ` request: Request;`,
176
- ` url: URL;`,
177
- ` locals: App.Locals;`,
178
- ` cookies: ActionCookies;`,
179
- ` }) => unknown | Promise<unknown>;`,
180
- `};`,
181
- "",
182
- );
183
- } else {
184
- lines.push(
185
- `export type PageData = Record<string, never>;`,
186
- `export type PageProps = { data: PageData; params: Params };`,
187
- `export type PageServerLoad = never;`,
188
- `export type Actions = Record<string, never>;`,
189
- "",
190
- );
191
- }
192
-
193
- // --- LayoutData from +layout.server.ts ---
194
- if (group.layoutServer) {
195
- const imp = toImportPath(outFileDir, group.layoutServer.filePath);
196
- lines.push(
197
- `type _LS = typeof import("${imp}");`,
198
- `export type LayoutData = "load" extends keyof _LS`,
199
- ` ? Awaited<ReturnType<_LS["load"]>>`,
200
- ` : Record<string, never>;`,
201
- "",
202
- );
203
- } else {
204
- lines.push(`export type LayoutData = Record<string, never>;`);
205
- }
206
-
207
- lines.push(
208
- `export type LayoutProps = { data: LayoutData; params: Params; children?: unknown };`,
209
- `export type LayoutServerLoad = (ctx: {`,
210
- ` params: Params;`,
211
- ` request: Request;`,
212
- ` url: URL;`,
213
- ` locals: App.Locals;`,
214
- ` parent: () => Promise<Record<string, unknown>>;`,
215
- `}) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
216
- "",
217
- );
218
-
219
- // --- +server.ts API route handlers ---
220
- if (group.server) {
221
- const imp = toImportPath(outFileDir, group.server.filePath);
222
- lines.push(
223
- `type _SRV = typeof import("${imp}");`,
224
- `type _HttpMethods = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";`,
225
- `type _ServerKeys = Extract<keyof _SRV, _HttpMethods>;`,
226
- `export type ServerHandlers = {`,
227
- ` [K in _ServerKeys]: (ctx: {`,
228
- ` params: Params;`,
229
- ` request: Request;`,
230
- ` url: URL;`,
231
- ` locals: App.Locals;`,
232
- ` }) => Response | Promise<Response>;`,
233
- `};`,
234
- ``,
235
- `export type UpgradeContext = {`,
236
- ` request: Request;`,
237
- ` params: Params;`,
238
- ` url: URL;`,
239
- ` locals: App.Locals;`,
240
- `};`,
241
- ``,
242
- `type _UpgradeReturn = "upgrade" extends keyof _SRV`,
243
- ` ? _SRV["upgrade"] extends (...args: any[]) => any`,
244
- ` ? Awaited<ReturnType<_SRV["upgrade"]>>`,
245
- ` : {}`,
246
- ` : {};`,
247
- `export type WsData = { params: Params } & Omit<_UpgradeReturn, "__handler">;`,
248
- ``,
249
- `export type WebSocketHandler = {`,
250
- ` open?(ws: ServerWebSocket<WsData>): void | Promise<void>;`,
251
- ` message?(ws: ServerWebSocket<WsData>, data: string | Buffer): void | Promise<void>;`,
252
- ` close?(ws: ServerWebSocket<WsData>, code: number, reason?: string): void | Promise<void>;`,
253
- ` drain?(ws: ServerWebSocket<WsData>): void | Promise<void>;`,
254
- `};`,
255
- "",
256
- );
257
- }
258
-
259
- // --- +error.tsx ---
260
- if (group.error) {
261
- lines.push(
262
- `export type ErrorProps = { status: number; message: string; error: unknown; route: string };`,
263
- "",
264
- );
265
- }
266
-
267
- return lines.join("\n");
268
- }
269
-
270
- function generateAmbient(): string {
271
- return [
272
- "// Auto-generated by @sigil-dev/grimoire — do not edit",
273
- "",
274
- "declare namespace App {",
275
- " // Extend this interface in your app's src/app.d.ts to add typed locals",
276
- " interface Locals extends Record<string, unknown> {}",
277
- "}",
278
- "",
279
- "// Available in all route files without import.",
280
- "// Params default to Record<string,string>; for per-route typed params import from './$types'.",
281
- "// Note: using these globals widens return types — PageData loses concrete keys.",
282
- "// For precise data inference annotate load() with PageServerLoad from './$types'.",
283
- "",
284
- "type PageServerLoad<",
285
- " P extends Record<string, string> = Record<string, string>",
286
- "> = (ctx: {",
287
- " params: P;",
288
- " request: Request;",
289
- " url: URL;",
290
- " locals: App.Locals;",
291
- " fetch: typeof fetch;",
292
- " parent: () => Promise<Record<string, unknown>>;",
293
- "}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
294
- "",
295
- "type LayoutServerLoad<",
296
- " P extends Record<string, string> = Record<string, string>",
297
- "> = (ctx: {",
298
- " params: P;",
299
- " request: Request;",
300
- " url: URL;",
301
- " locals: App.Locals;",
302
- " fetch: typeof fetch;",
303
- " parent: () => Promise<Record<string, unknown>>;",
304
- "}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
305
- "",
306
- "type RequestHandler<",
307
- " P extends Record<string, string> = Record<string, string>",
308
- "> = (ctx: {",
309
- " params: P;",
310
- " request: Request;",
311
- " url: URL;",
312
- " locals: App.Locals;",
313
- "}) => Response | Promise<Response>;",
314
- "",
315
- "type PageProps<",
316
- " D extends Record<string, unknown> = Record<string, unknown>,",
317
- " P extends Record<string, string> = Record<string, string>",
318
- "> = { data: D; params: P };",
319
- "",
320
- "type LayoutProps<",
321
- " D extends Record<string, unknown> = Record<string, unknown>,",
322
- " P extends Record<string, string> = Record<string, string>",
323
- "> = { data: D; params: P; children?: unknown };",
324
- "",
325
- "type ErrorProps = { status: number; message: string; error: unknown; route: string };",
326
- "",
327
- "type UpgradeContext<",
328
- " P extends Record<string, string> = Record<string, string>",
329
- "> = {",
330
- " params: P;",
331
- " request: Request;",
332
- " url: URL;",
333
- " locals: App.Locals;",
334
- "};",
335
- "",
336
- ].join("\n");
337
- }
338
-
339
- function generateTsConfig(): string {
340
- return JSON.stringify(
341
- {
342
- compilerOptions: {
343
- // Merges ".." (project root) and "./types" (.grimoire/types) into one
344
- // virtual root so `import from './$types'` resolves without path aliases.
345
- rootDirs: ["..", "./types"],
346
- },
347
- include: ["types/**/*.d.ts"],
348
- },
349
- null,
350
- 2,
351
- );
352
- }
353
-
354
- export async function generateTypes(
355
- tree: RouteTree,
356
- config: TypegenConfig,
357
- ): Promise<void> {
358
- const { projectRoot, outDir } = config;
359
-
360
- // Skip rm — on Windows, rm+mkdir in quick succession can race and leave dirs
361
- // in an unusable state. Stale type files are harmless; we overwrite what we need.
362
- await mkdir(outDir, { recursive: true }).catch(() => {});
363
-
364
- const groups = groupByDirectory(tree);
365
-
366
- for (const group of groups.values()) {
367
- const routeRelDir = safeRelativeDir(
368
- projectRoot,
369
- config.routesDir,
370
- group.dir,
371
- );
372
- const outFileDir = join(outDir, routeRelDir);
373
- // Use mkdirSync — async mkdir on Windows/Bun can report success before
374
- // the directory is actually visible to subsequent fs calls
375
- mkdirSync(outFileDir, { recursive: true });
376
-
377
- const content = generateTypesForGroup(group, outFileDir);
378
- writeFileSync(join(outFileDir, "$types.d.ts"), content, "utf-8");
379
- }
380
-
381
- writeFileSync(join(outDir, "ambient.d.ts"), generateAmbient(), "utf-8");
382
-
383
- const grimoireDir = dirname(outDir);
384
- writeFileSync(
385
- join(grimoireDir, "tsconfig.generated.json"),
386
- generateTsConfig(),
387
- "utf-8",
388
- );
389
- }
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { mkdir } from "node:fs/promises";
3
+ import { dirname, isAbsolute, join, relative } from "node:path";
4
+ import type { RouteFile, RouteTree } from "../routing/scanner.ts";
5
+
6
+ export interface TypegenConfig {
7
+ projectRoot: string;
8
+ routesDir: string;
9
+ outDir: string; // absolute path to .grimoire/types
10
+ }
11
+
12
+ export interface RouteGroup {
13
+ dir: string;
14
+ paramNames: string[];
15
+ optionalParamNames: string[];
16
+ restParamNames: string[];
17
+ page?: RouteFile;
18
+ pageServer?: RouteFile;
19
+ layout?: RouteFile;
20
+ layoutServer?: RouteFile;
21
+ server?: RouteFile;
22
+ error?: RouteFile;
23
+ }
24
+
25
+ // On Windows, relative() returns the absolute `to` path when src and dest are on
26
+ // different drives. Detect that and fall back to routes-dir-relative so join()
27
+ // doesn't produce an invalid double-rooted path like "D:\out\C:\Users\...".
28
+ function safeRelativeDir(
29
+ projectRoot: string,
30
+ routesDir: string,
31
+ groupDir: string,
32
+ ): string {
33
+ const rel = relative(projectRoot, groupDir);
34
+ return isAbsolute(rel) ? relative(routesDir, groupDir) : rel;
35
+ }
36
+
37
+ export function groupByDirectory(tree: RouteTree): Map<string, RouteGroup> {
38
+ const groups = new Map<string, RouteGroup>();
39
+
40
+ // Only process + convention files — simple files don't get $types
41
+ const files: RouteFile[] = [
42
+ ...tree.routes.filter((f) => f.type !== "simple"),
43
+ ...tree.layouts,
44
+ ...tree.servers,
45
+ ...tree.errors,
46
+ ];
47
+
48
+ for (const file of files) {
49
+ const dir = dirname(file.filePath);
50
+ if (!groups.has(dir)) {
51
+ groups.set(dir, {
52
+ dir,
53
+ paramNames: file.paramNames,
54
+ optionalParamNames: file.optionalParamNames,
55
+ restParamNames: file.restParamNames,
56
+ });
57
+ }
58
+ const g = groups.get(dir)!;
59
+ if (file.paramNames.length > g.paramNames.length) {
60
+ g.paramNames = file.paramNames;
61
+ }
62
+ if (file.optionalParamNames.length > g.optionalParamNames.length) {
63
+ g.optionalParamNames = file.optionalParamNames;
64
+ }
65
+ if (file.restParamNames.length > g.restParamNames.length) {
66
+ g.restParamNames = file.restParamNames;
67
+ }
68
+ switch (file.type) {
69
+ case "page":
70
+ g.page = file;
71
+ break;
72
+ case "pageServer":
73
+ g.pageServer = file;
74
+ break;
75
+ case "layout":
76
+ g.layout = file;
77
+ break;
78
+ case "layoutServer":
79
+ g.layoutServer = file;
80
+ break;
81
+ case "server":
82
+ g.server = file;
83
+ break;
84
+ case "error":
85
+ g.error = file;
86
+ break;
87
+ }
88
+ }
89
+
90
+ return groups;
91
+ }
92
+
93
+ export function toImportPath(from: string, to: string): string {
94
+ return relative(from, to)
95
+ .replace(/\\/g, "/")
96
+ .replace(/\.tsx?$/, ".js");
97
+ }
98
+
99
+ export function buildParams(
100
+ paramNames: string[],
101
+ optionalParamNames: string[] = [],
102
+ restParamNames: string[] = [],
103
+ ): string {
104
+ const all = [
105
+ ...paramNames.map((p) => ` ${p}: string;`),
106
+ ...optionalParamNames.map((p) => ` ${p}: string | undefined;`),
107
+ ...restParamNames.map((p) => ` ${p}: string;`),
108
+ ];
109
+ if (all.length === 0) return "{}";
110
+ return `{\n${all.join("\n")}\n}`;
111
+ }
112
+
113
+ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
114
+ const lines: string[] = [
115
+ "// Auto-generated by @sigil-dev/grimoire — do not edit",
116
+ "",
117
+ ];
118
+
119
+ const paramsType = buildParams(
120
+ group.paramNames,
121
+ group.optionalParamNames,
122
+ group.restParamNames,
123
+ );
124
+
125
+ // --- Params ---
126
+ lines.push(`export type Params = ${paramsType};`, "");
127
+
128
+ // --- PageData from +page.server.ts ---
129
+ if (group.pageServer) {
130
+ const imp = toImportPath(outFileDir, group.pageServer.filePath);
131
+ // Use `typeof import(...)` (not `import type * as NS`) so the module type
132
+ // can be used in `keyof` and indexed access without TS2709.
133
+ lines.push(
134
+ `type _PS = typeof import("${imp}");`,
135
+ `export type PageData = "load" extends keyof _PS`,
136
+ ` ? Awaited<ReturnType<_PS["load"]>>`,
137
+ ` : Record<string, never>;`,
138
+ "",
139
+ );
140
+ lines.push(
141
+ `export type PageProps = { data: PageData; params: Params };`,
142
+ "",
143
+ );
144
+ // PageServerLoad — annotate parameter, NOT return type, to preserve inference
145
+ lines.push(
146
+ `/** Annotate the load() parameter only — not the return type — or PageData loses its concrete keys. */`,
147
+ `export type PageServerLoad = (ctx: {`,
148
+ ` params: Params;`,
149
+ ` request: Request;`,
150
+ ` url: URL;`,
151
+ ` locals: App.Locals;`,
152
+ ` parent: () => Promise<Record<string, unknown>>;`,
153
+ `}) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
154
+ "",
155
+ );
156
+ // Actions — all exports except load and default
157
+ lines.push(
158
+ `type ActionCookies = {`,
159
+ ` get(name: string): string | undefined;`,
160
+ ` set(name: string, value: string, options?: {`,
161
+ ` path?: string;`,
162
+ ` domain?: string;`,
163
+ ` maxAge?: number;`,
164
+ ` expires?: Date;`,
165
+ ` httpOnly?: boolean;`,
166
+ ` secure?: boolean;`,
167
+ ` sameSite?: "strict" | "lax" | "none";`,
168
+ ` }): void;`,
169
+ ` delete(name: string): void;`,
170
+ `};`,
171
+ `type _ActionKeys = Exclude<keyof _PS, "load" | "default">;`,
172
+ `export type Actions = {`,
173
+ ` [K in _ActionKeys]: (ctx: {`,
174
+ ` params: Params;`,
175
+ ` request: Request;`,
176
+ ` url: URL;`,
177
+ ` locals: App.Locals;`,
178
+ ` cookies: ActionCookies;`,
179
+ ` }) => unknown | Promise<unknown>;`,
180
+ `};`,
181
+ "",
182
+ );
183
+ } else {
184
+ lines.push(
185
+ `export type PageData = Record<string, never>;`,
186
+ `export type PageProps = { data: PageData; params: Params };`,
187
+ `export type PageServerLoad = never;`,
188
+ `export type Actions = Record<string, never>;`,
189
+ "",
190
+ );
191
+ }
192
+
193
+ // --- LayoutData from +layout.server.ts ---
194
+ if (group.layoutServer) {
195
+ const imp = toImportPath(outFileDir, group.layoutServer.filePath);
196
+ lines.push(
197
+ `type _LS = typeof import("${imp}");`,
198
+ `export type LayoutData = "load" extends keyof _LS`,
199
+ ` ? Awaited<ReturnType<_LS["load"]>>`,
200
+ ` : Record<string, never>;`,
201
+ "",
202
+ );
203
+ } else {
204
+ lines.push(`export type LayoutData = Record<string, never>;`);
205
+ }
206
+
207
+ lines.push(
208
+ `export type LayoutProps = { data: LayoutData; params: Params; children?: unknown };`,
209
+ `export type LayoutServerLoad = (ctx: {`,
210
+ ` params: Params;`,
211
+ ` request: Request;`,
212
+ ` url: URL;`,
213
+ ` locals: App.Locals;`,
214
+ ` parent: () => Promise<Record<string, unknown>>;`,
215
+ `}) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
216
+ "",
217
+ );
218
+
219
+ // --- +server.ts API route handlers ---
220
+ if (group.server) {
221
+ const imp = toImportPath(outFileDir, group.server.filePath);
222
+ lines.push(
223
+ `type _SRV = typeof import("${imp}");`,
224
+ `type _HttpMethods = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";`,
225
+ `type _ServerKeys = Extract<keyof _SRV, _HttpMethods>;`,
226
+ `export type ServerHandlers = {`,
227
+ ` [K in _ServerKeys]: (ctx: {`,
228
+ ` params: Params;`,
229
+ ` request: Request;`,
230
+ ` url: URL;`,
231
+ ` locals: App.Locals;`,
232
+ ` }) => Response | Promise<Response>;`,
233
+ `};`,
234
+ ``,
235
+ `export type UpgradeContext = {`,
236
+ ` request: Request;`,
237
+ ` params: Params;`,
238
+ ` url: URL;`,
239
+ ` locals: App.Locals;`,
240
+ `};`,
241
+ ``,
242
+ `type _UpgradeReturn = "upgrade" extends keyof _SRV`,
243
+ ` ? _SRV["upgrade"] extends (...args: any[]) => any`,
244
+ ` ? Awaited<ReturnType<_SRV["upgrade"]>>`,
245
+ ` : {}`,
246
+ ` : {};`,
247
+ `export type WsData = { params: Params } & Omit<_UpgradeReturn, "__handler">;`,
248
+ ``,
249
+ `export type WebSocketHandler = {`,
250
+ ` open?(ws: ServerWebSocket<WsData>): void | Promise<void>;`,
251
+ ` message?(ws: ServerWebSocket<WsData>, data: string | Buffer): void | Promise<void>;`,
252
+ ` close?(ws: ServerWebSocket<WsData>, code: number, reason?: string): void | Promise<void>;`,
253
+ ` drain?(ws: ServerWebSocket<WsData>): void | Promise<void>;`,
254
+ `};`,
255
+ "",
256
+ );
257
+ }
258
+
259
+ // --- +error.tsx ---
260
+ if (group.error) {
261
+ lines.push(
262
+ `export type ErrorProps = { status: number; message: string; error: unknown; route: string };`,
263
+ "",
264
+ );
265
+ }
266
+
267
+ return lines.join("\n");
268
+ }
269
+
270
+ function generateAmbient(): string {
271
+ return [
272
+ "// Auto-generated by @sigil-dev/grimoire — do not edit",
273
+ "",
274
+ "declare namespace App {",
275
+ " // Extend this interface in your app's src/app.d.ts to add typed locals",
276
+ " interface Locals extends Record<string, unknown> {}",
277
+ "}",
278
+ "",
279
+ "// Available in all route files without import.",
280
+ "// Params default to Record<string,string>; for per-route typed params import from './$types'.",
281
+ "// Note: using these globals widens return types — PageData loses concrete keys.",
282
+ "// For precise data inference annotate load() with PageServerLoad from './$types'.",
283
+ "",
284
+ "type PageServerLoad<",
285
+ " P extends Record<string, string> = Record<string, string>",
286
+ "> = (ctx: {",
287
+ " params: P;",
288
+ " request: Request;",
289
+ " url: URL;",
290
+ " locals: App.Locals;",
291
+ " fetch: typeof fetch;",
292
+ " parent: () => Promise<Record<string, unknown>>;",
293
+ "}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
294
+ "",
295
+ "type LayoutServerLoad<",
296
+ " P extends Record<string, string> = Record<string, string>",
297
+ "> = (ctx: {",
298
+ " params: P;",
299
+ " request: Request;",
300
+ " url: URL;",
301
+ " locals: App.Locals;",
302
+ " fetch: typeof fetch;",
303
+ " parent: () => Promise<Record<string, unknown>>;",
304
+ "}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
305
+ "",
306
+ "type RequestHandler<",
307
+ " P extends Record<string, string> = Record<string, string>",
308
+ "> = (ctx: {",
309
+ " params: P;",
310
+ " request: Request;",
311
+ " url: URL;",
312
+ " locals: App.Locals;",
313
+ "}) => Response | Promise<Response>;",
314
+ "",
315
+ "type PageProps<",
316
+ " D extends Record<string, unknown> = Record<string, unknown>,",
317
+ " P extends Record<string, string> = Record<string, string>",
318
+ "> = { data: D; params: P };",
319
+ "",
320
+ "type LayoutProps<",
321
+ " D extends Record<string, unknown> = Record<string, unknown>,",
322
+ " P extends Record<string, string> = Record<string, string>",
323
+ "> = { data: D; params: P; children?: unknown };",
324
+ "",
325
+ "type ErrorProps = { status: number; message: string; error: unknown; route: string };",
326
+ "",
327
+ "type UpgradeContext<",
328
+ " P extends Record<string, string> = Record<string, string>",
329
+ "> = {",
330
+ " params: P;",
331
+ " request: Request;",
332
+ " url: URL;",
333
+ " locals: App.Locals;",
334
+ "};",
335
+ "",
336
+ ].join("\n");
337
+ }
338
+
339
+ function generateTsConfig(): string {
340
+ return JSON.stringify(
341
+ {
342
+ compilerOptions: {
343
+ // Merges ".." (project root) and "./types" (.grimoire/types) into one
344
+ // virtual root so `import from './$types'` resolves without path aliases.
345
+ rootDirs: ["..", "./types"],
346
+ },
347
+ include: ["types/**/*.d.ts"],
348
+ },
349
+ null,
350
+ 2,
351
+ );
352
+ }
353
+
354
+ export async function generateTypes(
355
+ tree: RouteTree,
356
+ config: TypegenConfig,
357
+ ): Promise<void> {
358
+ const { projectRoot, outDir } = config;
359
+
360
+ // Skip rm — on Windows, rm+mkdir in quick succession can race and leave dirs
361
+ // in an unusable state. Stale type files are harmless; we overwrite what we need.
362
+ await mkdir(outDir, { recursive: true }).catch(() => {});
363
+
364
+ const groups = groupByDirectory(tree);
365
+
366
+ for (const group of groups.values()) {
367
+ const routeRelDir = safeRelativeDir(
368
+ projectRoot,
369
+ config.routesDir,
370
+ group.dir,
371
+ );
372
+ const outFileDir = join(outDir, routeRelDir);
373
+ // Use mkdirSync — async mkdir on Windows/Bun can report success before
374
+ // the directory is actually visible to subsequent fs calls
375
+ mkdirSync(outFileDir, { recursive: true });
376
+
377
+ const content = generateTypesForGroup(group, outFileDir);
378
+ writeFileSync(join(outFileDir, "$types.d.ts"), content, "utf-8");
379
+ }
380
+
381
+ writeFileSync(join(outDir, "ambient.d.ts"), generateAmbient(), "utf-8");
382
+
383
+ const grimoireDir = dirname(outDir);
384
+ writeFileSync(
385
+ join(grimoireDir, "tsconfig.generated.json"),
386
+ generateTsConfig(),
387
+ "utf-8",
388
+ );
389
+ }