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