@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.
- package/README.md +83 -83
- package/index.ts +50 -48
- package/package.json +16 -5
- package/public/__grimoire__/grimoire-client.js +12 -0
- package/public/__grimoire__/runtime.js +1241 -0
- package/server.ts +22 -20
- package/src/adapters/bun.ts +17 -0
- package/src/adapters/static.ts +41 -0
- package/src/adapters/types.ts +36 -0
- package/src/base.ts +91 -0
- package/src/client/csrf.ts +47 -47
- package/src/client/deferred.ts +179 -179
- package/src/client/enhance.ts +160 -160
- package/src/client/router.ts +870 -833
- package/src/dev/compile-module.ts +211 -211
- package/src/dev/loader.ts +141 -141
- package/src/dev/resolve.ts +70 -70
- package/src/dev/runtime-bundle.ts +51 -51
- package/src/env/modules.ts +62 -62
- package/src/env/required.ts +42 -0
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +105 -105
- package/src/logger/transports.ts +117 -117
- package/src/rendering/head.ts +49 -49
- package/src/rendering/hydrate.ts +161 -161
- package/src/rendering/images.ts +43 -43
- package/src/rendering/index.ts +755 -749
- package/src/rendering/preload.ts +101 -101
- package/src/rendering/ssrPlugin.ts +108 -108
- package/src/rendering/timing.ts +40 -40
- package/src/routing/router.ts +186 -186
- package/src/routing/scanner.ts +225 -196
- package/src/routing/transform-routes.ts +102 -102
- package/src/server/after-response.ts +206 -206
- package/src/server/asset-cache.ts +57 -57
- package/src/server/build.ts +262 -262
- package/src/server/cached.ts +114 -114
- package/src/server/client-address.ts +82 -82
- package/src/server/client-dir.ts +57 -57
- package/src/server/client-entry.ts +44 -44
- package/src/server/cookie-utils.ts +80 -80
- package/src/server/coordinator.ts +476 -471
- package/src/server/hooks.ts +122 -122
- package/src/server/index.ts +1138 -1018
- package/src/server/plugins.ts +172 -172
- package/src/server/prerender.ts +444 -0
- package/src/server/reserved.ts +17 -0
- package/src/server/resolver.ts +98 -98
- package/src/server/rewrite.ts +28 -0
- package/src/server/warm.ts +91 -91
- package/src/server/with-headers.ts +27 -27
- package/src/server/worker.ts +74 -72
- package/src/testing/dom.ts +73 -0
- package/src/testing/index.ts +169 -0
- package/src/testing/server.ts +162 -0
- package/src/typegen/index.ts +450 -450
- package/src/types.ts +501 -432
- package/test/after-response.test.ts +132 -132
- package/test/asset-cache-policy.test.ts +96 -96
- package/test/base.test.ts +134 -0
- package/test/cached.test.ts +126 -126
- package/test/client-address.test.ts +78 -78
- package/test/client-csrf.test.ts +61 -61
- package/test/client-dir.test.ts +101 -101
- package/test/client-router.test.ts +789 -734
- package/test/coordinator.test.ts +96 -94
- package/test/deferred.test.ts +256 -256
- package/test/dev-loader.test.ts +30 -30
- package/test/env.test.ts +168 -168
- package/test/force-production.test.ts +44 -0
- package/test/images.test.ts +49 -49
- package/test/locals-header.test.ts +61 -0
- package/test/middleware.test.ts +243 -243
- package/test/parser-plugins.test.ts +92 -92
- package/test/plugin-handle.test.ts +62 -62
- package/test/plugin-services-context.test.ts +97 -97
- package/test/preload.test.ts +48 -48
- package/test/prerender.test.ts +353 -0
- package/test/rendering.test.ts +798 -798
- package/test/required-env.test.ts +32 -0
- package/test/rewrite-html.test.ts +90 -0
- package/test/scanning.test.ts +349 -314
- package/test/server.test.ts +640 -619
- package/test/services.test.ts +90 -90
- package/test/streaming.test.ts +378 -378
- package/test/testing-helpers.test.ts +166 -0
- package/test/typegen.test.ts +805 -799
- package/test/warm.test.ts +96 -96
- package/test/worker-context.test.ts +59 -59
- package/test/workspace-files.test.ts +149 -146
- package/test/workspace-versions.test.ts +131 -131
- package/.grimoire/_routes.ts +0 -4
- package/public/__grimoire__/client.js +0 -55
- package/public/__grimoire__/hydrate.js +0 -63
package/src/typegen/index.ts
CHANGED
|
@@ -1,450 +1,450 @@
|
|
|
1
|
-
import { mkdirSync, readdirSync, rmSync, 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
|
-
/** Import prefix → absolute directory ($lib, GrimoireConfig.alias), for editor `paths`. */
|
|
11
|
-
aliases?: Record<string, string>;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export interface RouteGroup {
|
|
15
|
-
dir: string;
|
|
16
|
-
paramNames: string[];
|
|
17
|
-
optionalParamNames: string[];
|
|
18
|
-
restParamNames: string[];
|
|
19
|
-
page?: RouteFile;
|
|
20
|
-
pageServer?: RouteFile;
|
|
21
|
-
layout?: RouteFile;
|
|
22
|
-
layoutServer?: RouteFile;
|
|
23
|
-
server?: RouteFile;
|
|
24
|
-
error?: RouteFile;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// On Windows, relative() returns the absolute `to` path when src and dest are on
|
|
28
|
-
// different drives. Detect that and fall back to routes-dir-relative so join()
|
|
29
|
-
// doesn't produce an invalid double-rooted path like "D:\out\C:\Users\...".
|
|
30
|
-
function safeRelativeDir(
|
|
31
|
-
projectRoot: string,
|
|
32
|
-
routesDir: string,
|
|
33
|
-
groupDir: string,
|
|
34
|
-
): string {
|
|
35
|
-
const rel = relative(projectRoot, groupDir);
|
|
36
|
-
return isAbsolute(rel) ? relative(routesDir, groupDir) : rel;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export function groupByDirectory(tree: RouteTree): Map<string, RouteGroup> {
|
|
40
|
-
const groups = new Map<string, RouteGroup>();
|
|
41
|
-
|
|
42
|
-
// Only process + convention files — simple files don't get $types
|
|
43
|
-
const files: RouteFile[] = [
|
|
44
|
-
...tree.routes.filter((f) => f.type !== "simple"),
|
|
45
|
-
...tree.layouts,
|
|
46
|
-
...tree.servers,
|
|
47
|
-
...tree.errors,
|
|
48
|
-
];
|
|
49
|
-
|
|
50
|
-
for (const file of files) {
|
|
51
|
-
const dir = dirname(file.filePath);
|
|
52
|
-
if (!groups.has(dir)) {
|
|
53
|
-
groups.set(dir, {
|
|
54
|
-
dir,
|
|
55
|
-
paramNames: file.paramNames,
|
|
56
|
-
optionalParamNames: file.optionalParamNames,
|
|
57
|
-
restParamNames: file.restParamNames,
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
const g = groups.get(dir)!;
|
|
61
|
-
if (file.paramNames.length > g.paramNames.length) {
|
|
62
|
-
g.paramNames = file.paramNames;
|
|
63
|
-
}
|
|
64
|
-
if (file.optionalParamNames.length > g.optionalParamNames.length) {
|
|
65
|
-
g.optionalParamNames = file.optionalParamNames;
|
|
66
|
-
}
|
|
67
|
-
if (file.restParamNames.length > g.restParamNames.length) {
|
|
68
|
-
g.restParamNames = file.restParamNames;
|
|
69
|
-
}
|
|
70
|
-
switch (file.type) {
|
|
71
|
-
case "page":
|
|
72
|
-
g.page = file;
|
|
73
|
-
break;
|
|
74
|
-
case "pageServer":
|
|
75
|
-
g.pageServer = file;
|
|
76
|
-
break;
|
|
77
|
-
case "layout":
|
|
78
|
-
g.layout = file;
|
|
79
|
-
break;
|
|
80
|
-
case "layoutServer":
|
|
81
|
-
g.layoutServer = file;
|
|
82
|
-
break;
|
|
83
|
-
case "server":
|
|
84
|
-
g.server = file;
|
|
85
|
-
break;
|
|
86
|
-
case "error":
|
|
87
|
-
g.error = file;
|
|
88
|
-
break;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
return groups;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
export function toImportPath(from: string, to: string): string {
|
|
96
|
-
return relative(from, to)
|
|
97
|
-
.replace(/\\/g, "/")
|
|
98
|
-
.replace(/\.tsx?$/, ".js");
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
export function buildParams(
|
|
102
|
-
paramNames: string[],
|
|
103
|
-
optionalParamNames: string[] = [],
|
|
104
|
-
restParamNames: string[] = [],
|
|
105
|
-
): string {
|
|
106
|
-
const all = [
|
|
107
|
-
...paramNames.map((p) => ` ${p}: string;`),
|
|
108
|
-
...optionalParamNames.map((p) => ` ${p}: string | undefined;`),
|
|
109
|
-
...restParamNames.map((p) => ` ${p}: string;`),
|
|
110
|
-
];
|
|
111
|
-
if (all.length === 0) return "{}";
|
|
112
|
-
return `{\n${all.join("\n")}\n}`;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
|
|
116
|
-
const lines: string[] = [
|
|
117
|
-
"// Auto-generated by @sigil-dev/grimoire — do not edit",
|
|
118
|
-
"",
|
|
119
|
-
];
|
|
120
|
-
|
|
121
|
-
const paramsType = buildParams(
|
|
122
|
-
group.paramNames,
|
|
123
|
-
group.optionalParamNames,
|
|
124
|
-
group.restParamNames,
|
|
125
|
-
);
|
|
126
|
-
|
|
127
|
-
// --- Params ---
|
|
128
|
-
lines.push(`export type Params = ${paramsType};`, "");
|
|
129
|
-
|
|
130
|
-
// --- PageData from +page.server.ts ---
|
|
131
|
-
if (group.pageServer) {
|
|
132
|
-
const imp = toImportPath(outFileDir, group.pageServer.filePath);
|
|
133
|
-
// Use `typeof import(...)` (not `import type * as NS`) so the module type
|
|
134
|
-
// can be used in `keyof` and indexed access without TS2709.
|
|
135
|
-
lines.push(
|
|
136
|
-
`type _PS = typeof import("${imp}");`,
|
|
137
|
-
`/** A top-level promise streams: undefined until it lands, null if it rejected. */`,
|
|
138
|
-
`type _Streamed<T> = { [K in keyof T]: T[K] extends PromiseLike<infer V> ? V | null | undefined : T[K] };`,
|
|
139
|
-
`export type PageData = _PS extends { load: (...args: any[]) => infer R }`,
|
|
140
|
-
` ? _Streamed<Awaited<R>>`,
|
|
141
|
-
` : Record<string, never>;`,
|
|
142
|
-
"",
|
|
143
|
-
);
|
|
144
|
-
// ActionData: what the route's actions pass to fail(), which comes back
|
|
145
|
-
// to the page as its `form` prop after a failed plain-form submission
|
|
146
|
-
lines.push(
|
|
147
|
-
`type _FailData<R> = R extends { __fail: true; data: infer D } ? D : never;`,
|
|
148
|
-
`export type ActionData = {`,
|
|
149
|
-
` [K in _ActionKeys]: _PS[K] extends (...args: any[]) => infer R ? _FailData<Awaited<R>> : never;`,
|
|
150
|
-
`}[_ActionKeys];`,
|
|
151
|
-
"",
|
|
152
|
-
`export type PageProps = { data: PageData; params: Params; form?: ActionData };`,
|
|
153
|
-
"",
|
|
154
|
-
);
|
|
155
|
-
// PageServerLoad — annotate parameter, NOT return type, to preserve inference
|
|
156
|
-
lines.push(
|
|
157
|
-
`/** What load() receives: \`export async function load({ params }: PageServerLoadEvent)\`. */`,
|
|
158
|
-
`export type PageServerLoadEvent = {`,
|
|
159
|
-
` params: Params;`,
|
|
160
|
-
` request: Request;`,
|
|
161
|
-
` url: URL;`,
|
|
162
|
-
` locals: App.Locals;`,
|
|
163
|
-
` fetch: typeof fetch;`,
|
|
164
|
-
` getClientAddress: () => string;`,
|
|
165
|
-
` parent: () => Promise<Record<string, unknown>>;`,
|
|
166
|
-
`};`,
|
|
167
|
-
`/** Annotate the load() parameter only — not the return type — or PageData loses its concrete keys. */`,
|
|
168
|
-
`export type PageServerLoad = (event: PageServerLoadEvent) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
|
|
169
|
-
"",
|
|
170
|
-
);
|
|
171
|
-
// Actions — all exports except load and default
|
|
172
|
-
lines.push(
|
|
173
|
-
`type ActionCookies = {`,
|
|
174
|
-
` get(name: string): string | undefined;`,
|
|
175
|
-
` set(name: string, value: string, options?: {`,
|
|
176
|
-
` path?: string;`,
|
|
177
|
-
` domain?: string;`,
|
|
178
|
-
` maxAge?: number;`,
|
|
179
|
-
` expires?: Date;`,
|
|
180
|
-
` httpOnly?: boolean;`,
|
|
181
|
-
` secure?: boolean;`,
|
|
182
|
-
` sameSite?: "strict" | "lax" | "none";`,
|
|
183
|
-
` }): void;`,
|
|
184
|
-
` delete(name: string, options?: { path?: string; domain?: string }): void;`,
|
|
185
|
-
`};`,
|
|
186
|
-
`type _ActionKeys = Exclude<keyof _PS, "load" | "default" | "canMatch" | "csrf" | "loading">;`,
|
|
187
|
-
`/** What a form action receives: \`export async function add({ request }: ActionEvent)\`. */`,
|
|
188
|
-
`export type ActionEvent = {`,
|
|
189
|
-
` params: Params;`,
|
|
190
|
-
` request: Request;`,
|
|
191
|
-
` url: URL;`,
|
|
192
|
-
` locals: App.Locals;`,
|
|
193
|
-
` fetch: typeof fetch;`,
|
|
194
|
-
` getClientAddress: () => string;`,
|
|
195
|
-
` cookies: ActionCookies;`,
|
|
196
|
-
`};`,
|
|
197
|
-
`export type Actions = {`,
|
|
198
|
-
` [K in _ActionKeys]: (event: ActionEvent) => unknown | Promise<unknown>;`,
|
|
199
|
-
`};`,
|
|
200
|
-
"",
|
|
201
|
-
);
|
|
202
|
-
} else {
|
|
203
|
-
lines.push(
|
|
204
|
-
`export type PageData = Record<string, never>;`,
|
|
205
|
-
`export type ActionData = never;`,
|
|
206
|
-
`export type PageProps = { data: PageData; params: Params; form?: ActionData };`,
|
|
207
|
-
`export type PageServerLoad = never;`,
|
|
208
|
-
`export type Actions = Record<string, never>;`,
|
|
209
|
-
"",
|
|
210
|
-
);
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
// --- LayoutData from +layout.server.ts ---
|
|
214
|
-
if (group.layoutServer) {
|
|
215
|
-
const imp = toImportPath(outFileDir, group.layoutServer.filePath);
|
|
216
|
-
lines.push(
|
|
217
|
-
`type _LS = typeof import("${imp}");`,
|
|
218
|
-
`export type LayoutData = _LS extends { load: (...args: any[]) => infer R }`,
|
|
219
|
-
` ? Awaited<R>`,
|
|
220
|
-
` : Record<string, never>;`,
|
|
221
|
-
"",
|
|
222
|
-
);
|
|
223
|
-
} else {
|
|
224
|
-
lines.push(`export type LayoutData = Record<string, never>;`);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
lines.push(
|
|
228
|
-
`export type LayoutProps = { data: LayoutData; params: Params; children?: unknown };`,
|
|
229
|
-
`/** What a layout's load() receives. */`,
|
|
230
|
-
`export type LayoutServerLoadEvent = {`,
|
|
231
|
-
` params: Params;`,
|
|
232
|
-
` request: Request;`,
|
|
233
|
-
` url: URL;`,
|
|
234
|
-
` locals: App.Locals;`,
|
|
235
|
-
` fetch: typeof fetch;`,
|
|
236
|
-
` getClientAddress: () => string;`,
|
|
237
|
-
` parent: () => Promise<Record<string, unknown>>;`,
|
|
238
|
-
`};`,
|
|
239
|
-
`export type LayoutServerLoad = (event: LayoutServerLoadEvent) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
|
|
240
|
-
"",
|
|
241
|
-
);
|
|
242
|
-
|
|
243
|
-
// --- +server.ts API route handlers ---
|
|
244
|
-
if (group.server) {
|
|
245
|
-
const imp = toImportPath(outFileDir, group.server.filePath);
|
|
246
|
-
lines.push(
|
|
247
|
-
`type _SRV = typeof import("${imp}");`,
|
|
248
|
-
`type _HttpMethods = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";`,
|
|
249
|
-
`type _ServerKeys = Extract<keyof _SRV, _HttpMethods>;`,
|
|
250
|
-
`export type ServerHandlers = {`,
|
|
251
|
-
` [K in _ServerKeys]: (ctx: {`,
|
|
252
|
-
` params: Params;`,
|
|
253
|
-
` request: Request;`,
|
|
254
|
-
` url: URL;`,
|
|
255
|
-
` locals: App.Locals;`,
|
|
256
|
-
` }) => Response | Promise<Response>;`,
|
|
257
|
-
`};`,
|
|
258
|
-
``,
|
|
259
|
-
`export type UpgradeContext = {`,
|
|
260
|
-
` request: Request;`,
|
|
261
|
-
` params: Params;`,
|
|
262
|
-
` url: URL;`,
|
|
263
|
-
` locals: App.Locals;`,
|
|
264
|
-
`};`,
|
|
265
|
-
``,
|
|
266
|
-
`type _UpgradeReturn = _SRV extends { upgrade: (...args: any[]) => infer R }`,
|
|
267
|
-
` ? Awaited<R>`,
|
|
268
|
-
` : {};`,
|
|
269
|
-
`export type WsData = { params: Params } & Omit<_UpgradeReturn, "__handler">;`,
|
|
270
|
-
``,
|
|
271
|
-
`/** The parts of Bun's ServerWebSocket a handler uses, so this file needs no Bun types installed. */`,
|
|
272
|
-
`export type SocketOf<D> = {`,
|
|
273
|
-
` readonly data: D;`,
|
|
274
|
-
` readonly readyState: number;`,
|
|
275
|
-
` readonly remoteAddress: string;`,
|
|
276
|
-
` send(data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`,
|
|
277
|
-
` close(code?: number, reason?: string): void;`,
|
|
278
|
-
` subscribe(topic: string): void;`,
|
|
279
|
-
` unsubscribe(topic: string): void;`,
|
|
280
|
-
` isSubscribed(topic: string): boolean;`,
|
|
281
|
-
` publish(topic: string, data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`,
|
|
282
|
-
`};`,
|
|
283
|
-
`export type WebSocketHandler = {`,
|
|
284
|
-
` open?(ws: SocketOf<WsData>): void | Promise<void>;`,
|
|
285
|
-
` message?(ws: SocketOf<WsData>, data: string | Uint8Array): void | Promise<void>;`,
|
|
286
|
-
` close?(ws: SocketOf<WsData>, code: number, reason?: string): void | Promise<void>;`,
|
|
287
|
-
` drain?(ws: SocketOf<WsData>): void | Promise<void>;`,
|
|
288
|
-
`};`,
|
|
289
|
-
"",
|
|
290
|
-
);
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
// --- +error.tsx ---
|
|
294
|
-
if (group.error) {
|
|
295
|
-
lines.push(
|
|
296
|
-
`export type ErrorProps = { status: number; message: string; error: unknown; route: string };`,
|
|
297
|
-
"",
|
|
298
|
-
);
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
return lines.join("\n");
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
function generateAmbient(): string {
|
|
305
|
-
return [
|
|
306
|
-
"// Auto-generated by @sigil-dev/grimoire — do not edit",
|
|
307
|
-
"",
|
|
308
|
-
"declare namespace App {",
|
|
309
|
-
" // Extend this interface in your app's src/app.d.ts to add typed locals",
|
|
310
|
-
" interface Locals extends Record<string, unknown> {}",
|
|
311
|
-
"}",
|
|
312
|
-
"",
|
|
313
|
-
"// Available in all route files without import.",
|
|
314
|
-
"// Params default to Record<string,string>; for per-route typed params import from './$types'.",
|
|
315
|
-
"// Note: using these globals widens return types — PageData loses concrete keys.",
|
|
316
|
-
"// For precise data inference annotate load() with PageServerLoad from './$types'.",
|
|
317
|
-
"",
|
|
318
|
-
"type PageServerLoad<",
|
|
319
|
-
" P extends Record<string, string> = Record<string, string>",
|
|
320
|
-
"> = (ctx: {",
|
|
321
|
-
" params: P;",
|
|
322
|
-
" request: Request;",
|
|
323
|
-
" url: URL;",
|
|
324
|
-
" locals: App.Locals;",
|
|
325
|
-
" fetch: typeof fetch;",
|
|
326
|
-
" parent: () => Promise<Record<string, unknown>>;",
|
|
327
|
-
"}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
|
|
328
|
-
"",
|
|
329
|
-
"type LayoutServerLoad<",
|
|
330
|
-
" P extends Record<string, string> = Record<string, string>",
|
|
331
|
-
"> = (ctx: {",
|
|
332
|
-
" params: P;",
|
|
333
|
-
" request: Request;",
|
|
334
|
-
" url: URL;",
|
|
335
|
-
" locals: App.Locals;",
|
|
336
|
-
" fetch: typeof fetch;",
|
|
337
|
-
" parent: () => Promise<Record<string, unknown>>;",
|
|
338
|
-
"}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
|
|
339
|
-
"",
|
|
340
|
-
"type RequestHandler<",
|
|
341
|
-
" P extends Record<string, string> = Record<string, string>",
|
|
342
|
-
"> = (ctx: {",
|
|
343
|
-
" params: P;",
|
|
344
|
-
" request: Request;",
|
|
345
|
-
" url: URL;",
|
|
346
|
-
" locals: App.Locals;",
|
|
347
|
-
"}) => Response | Promise<Response>;",
|
|
348
|
-
"",
|
|
349
|
-
"type PageProps<",
|
|
350
|
-
" D extends Record<string, unknown> = Record<string, unknown>,",
|
|
351
|
-
" P extends Record<string, string> = Record<string, string>",
|
|
352
|
-
"> = { data: D; params: P };",
|
|
353
|
-
"",
|
|
354
|
-
"type LayoutProps<",
|
|
355
|
-
" D extends Record<string, unknown> = Record<string, unknown>,",
|
|
356
|
-
" P extends Record<string, string> = Record<string, string>",
|
|
357
|
-
"> = { data: D; params: P; children?: unknown };",
|
|
358
|
-
"",
|
|
359
|
-
"type ErrorProps = { status: number; message: string; error: unknown; route: string };",
|
|
360
|
-
"",
|
|
361
|
-
"type UpgradeContext<",
|
|
362
|
-
" P extends Record<string, string> = Record<string, string>",
|
|
363
|
-
"> = {",
|
|
364
|
-
" params: P;",
|
|
365
|
-
" request: Request;",
|
|
366
|
-
" url: URL;",
|
|
367
|
-
" locals: App.Locals;",
|
|
368
|
-
"};",
|
|
369
|
-
"",
|
|
370
|
-
].join("\n");
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
function generateTsConfig(
|
|
374
|
-
aliases: Record<string, string>,
|
|
375
|
-
grimoireDir: string,
|
|
376
|
-
): string {
|
|
377
|
-
// paths without a baseUrl resolve against this file's directory
|
|
378
|
-
const paths: Record<string, string[]> = {};
|
|
379
|
-
for (const [prefix, dir] of Object.entries(aliases)) {
|
|
380
|
-
const rel = relative(grimoireDir, dir).replace(/\\/g, "/");
|
|
381
|
-
paths[prefix] = [rel];
|
|
382
|
-
paths[`${prefix}/*`] = [`${rel}/*`];
|
|
383
|
-
}
|
|
384
|
-
return JSON.stringify(
|
|
385
|
-
{
|
|
386
|
-
compilerOptions: {
|
|
387
|
-
// Merges ".." (project root) and "./types" (.grimoire/types) into one
|
|
388
|
-
// virtual root so `import from './$types'` resolves without path aliases.
|
|
389
|
-
rootDirs: ["..", "./types"],
|
|
390
|
-
...(Object.keys(paths).length > 0 ? { paths } : {}),
|
|
391
|
-
},
|
|
392
|
-
include: ["types/**/*.d.ts"],
|
|
393
|
-
},
|
|
394
|
-
null,
|
|
395
|
-
2,
|
|
396
|
-
);
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
export async function generateTypes(
|
|
400
|
-
tree: RouteTree,
|
|
401
|
-
config: TypegenConfig,
|
|
402
|
-
): Promise<void> {
|
|
403
|
-
const { projectRoot, outDir } = config;
|
|
404
|
-
|
|
405
|
-
// Skip rm of the whole dir — on Windows, rm+mkdir in quick succession can
|
|
406
|
-
// race and leave dirs in an unusable state. Files this run does not write
|
|
407
|
-
// are removed one by one afterwards instead.
|
|
408
|
-
await mkdir(outDir, { recursive: true }).catch(() => {});
|
|
409
|
-
|
|
410
|
-
const groups = groupByDirectory(tree);
|
|
411
|
-
const written = new Set<string>();
|
|
412
|
-
|
|
413
|
-
for (const group of groups.values()) {
|
|
414
|
-
const routeRelDir = safeRelativeDir(
|
|
415
|
-
projectRoot,
|
|
416
|
-
config.routesDir,
|
|
417
|
-
group.dir,
|
|
418
|
-
);
|
|
419
|
-
const outFileDir = join(outDir, routeRelDir);
|
|
420
|
-
// Use mkdirSync — async mkdir on Windows/Bun can report success before
|
|
421
|
-
// the directory is actually visible to subsequent fs calls
|
|
422
|
-
mkdirSync(outFileDir, { recursive: true });
|
|
423
|
-
|
|
424
|
-
const content = generateTypesForGroup(group, outFileDir);
|
|
425
|
-
const file = join(outFileDir, "$types.d.ts");
|
|
426
|
-
writeFileSync(file, content, "utf-8");
|
|
427
|
-
written.add(file);
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
// A deleted route leaves its $types.d.ts behind, still importing the
|
|
431
|
-
// deleted file, and tsc fails on it until .grimoire is cleared by hand.
|
|
432
|
-
for (const entry of readdirSync(outDir, {
|
|
433
|
-
recursive: true,
|
|
434
|
-
withFileTypes: true,
|
|
435
|
-
})) {
|
|
436
|
-
const file = join(entry.parentPath, entry.name);
|
|
437
|
-
if (entry.isFile() && entry.name === "$types.d.ts" && !written.has(file)) {
|
|
438
|
-
rmSync(file, { force: true });
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
writeFileSync(join(outDir, "ambient.d.ts"), generateAmbient(), "utf-8");
|
|
443
|
-
|
|
444
|
-
const grimoireDir = dirname(outDir);
|
|
445
|
-
writeFileSync(
|
|
446
|
-
join(grimoireDir, "tsconfig.generated.json"),
|
|
447
|
-
generateTsConfig(config.aliases ?? {}, grimoireDir),
|
|
448
|
-
"utf-8",
|
|
449
|
-
);
|
|
450
|
-
}
|
|
1
|
+
import { mkdirSync, readdirSync, rmSync, 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
|
+
/** Import prefix → absolute directory ($lib, GrimoireConfig.alias), for editor `paths`. */
|
|
11
|
+
aliases?: Record<string, string>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface RouteGroup {
|
|
15
|
+
dir: string;
|
|
16
|
+
paramNames: string[];
|
|
17
|
+
optionalParamNames: string[];
|
|
18
|
+
restParamNames: string[];
|
|
19
|
+
page?: RouteFile;
|
|
20
|
+
pageServer?: RouteFile;
|
|
21
|
+
layout?: RouteFile;
|
|
22
|
+
layoutServer?: RouteFile;
|
|
23
|
+
server?: RouteFile;
|
|
24
|
+
error?: RouteFile;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// On Windows, relative() returns the absolute `to` path when src and dest are on
|
|
28
|
+
// different drives. Detect that and fall back to routes-dir-relative so join()
|
|
29
|
+
// doesn't produce an invalid double-rooted path like "D:\out\C:\Users\...".
|
|
30
|
+
function safeRelativeDir(
|
|
31
|
+
projectRoot: string,
|
|
32
|
+
routesDir: string,
|
|
33
|
+
groupDir: string,
|
|
34
|
+
): string {
|
|
35
|
+
const rel = relative(projectRoot, groupDir);
|
|
36
|
+
return isAbsolute(rel) ? relative(routesDir, groupDir) : rel;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function groupByDirectory(tree: RouteTree): Map<string, RouteGroup> {
|
|
40
|
+
const groups = new Map<string, RouteGroup>();
|
|
41
|
+
|
|
42
|
+
// Only process + convention files — simple files don't get $types
|
|
43
|
+
const files: RouteFile[] = [
|
|
44
|
+
...tree.routes.filter((f) => f.type !== "simple"),
|
|
45
|
+
...tree.layouts,
|
|
46
|
+
...tree.servers,
|
|
47
|
+
...tree.errors,
|
|
48
|
+
];
|
|
49
|
+
|
|
50
|
+
for (const file of files) {
|
|
51
|
+
const dir = dirname(file.filePath);
|
|
52
|
+
if (!groups.has(dir)) {
|
|
53
|
+
groups.set(dir, {
|
|
54
|
+
dir,
|
|
55
|
+
paramNames: file.paramNames,
|
|
56
|
+
optionalParamNames: file.optionalParamNames,
|
|
57
|
+
restParamNames: file.restParamNames,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
const g = groups.get(dir)!;
|
|
61
|
+
if (file.paramNames.length > g.paramNames.length) {
|
|
62
|
+
g.paramNames = file.paramNames;
|
|
63
|
+
}
|
|
64
|
+
if (file.optionalParamNames.length > g.optionalParamNames.length) {
|
|
65
|
+
g.optionalParamNames = file.optionalParamNames;
|
|
66
|
+
}
|
|
67
|
+
if (file.restParamNames.length > g.restParamNames.length) {
|
|
68
|
+
g.restParamNames = file.restParamNames;
|
|
69
|
+
}
|
|
70
|
+
switch (file.type) {
|
|
71
|
+
case "page":
|
|
72
|
+
g.page = file;
|
|
73
|
+
break;
|
|
74
|
+
case "pageServer":
|
|
75
|
+
g.pageServer = file;
|
|
76
|
+
break;
|
|
77
|
+
case "layout":
|
|
78
|
+
g.layout = file;
|
|
79
|
+
break;
|
|
80
|
+
case "layoutServer":
|
|
81
|
+
g.layoutServer = file;
|
|
82
|
+
break;
|
|
83
|
+
case "server":
|
|
84
|
+
g.server = file;
|
|
85
|
+
break;
|
|
86
|
+
case "error":
|
|
87
|
+
g.error = file;
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return groups;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function toImportPath(from: string, to: string): string {
|
|
96
|
+
return relative(from, to)
|
|
97
|
+
.replace(/\\/g, "/")
|
|
98
|
+
.replace(/\.tsx?$/, ".js");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function buildParams(
|
|
102
|
+
paramNames: string[],
|
|
103
|
+
optionalParamNames: string[] = [],
|
|
104
|
+
restParamNames: string[] = [],
|
|
105
|
+
): string {
|
|
106
|
+
const all = [
|
|
107
|
+
...paramNames.map((p) => ` ${p}: string;`),
|
|
108
|
+
...optionalParamNames.map((p) => ` ${p}: string | undefined;`),
|
|
109
|
+
...restParamNames.map((p) => ` ${p}: string;`),
|
|
110
|
+
];
|
|
111
|
+
if (all.length === 0) return "{}";
|
|
112
|
+
return `{\n${all.join("\n")}\n}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
|
|
116
|
+
const lines: string[] = [
|
|
117
|
+
"// Auto-generated by @sigil-dev/grimoire — do not edit",
|
|
118
|
+
"",
|
|
119
|
+
];
|
|
120
|
+
|
|
121
|
+
const paramsType = buildParams(
|
|
122
|
+
group.paramNames,
|
|
123
|
+
group.optionalParamNames,
|
|
124
|
+
group.restParamNames,
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
// --- Params ---
|
|
128
|
+
lines.push(`export type Params = ${paramsType};`, "");
|
|
129
|
+
|
|
130
|
+
// --- PageData from +page.server.ts ---
|
|
131
|
+
if (group.pageServer) {
|
|
132
|
+
const imp = toImportPath(outFileDir, group.pageServer.filePath);
|
|
133
|
+
// Use `typeof import(...)` (not `import type * as NS`) so the module type
|
|
134
|
+
// can be used in `keyof` and indexed access without TS2709.
|
|
135
|
+
lines.push(
|
|
136
|
+
`type _PS = typeof import("${imp}");`,
|
|
137
|
+
`/** A top-level promise streams: undefined until it lands, null if it rejected. */`,
|
|
138
|
+
`type _Streamed<T> = { [K in keyof T]: T[K] extends PromiseLike<infer V> ? V | null | undefined : T[K] };`,
|
|
139
|
+
`export type PageData = _PS extends { load: (...args: any[]) => infer R }`,
|
|
140
|
+
` ? _Streamed<Awaited<R>>`,
|
|
141
|
+
` : Record<string, never>;`,
|
|
142
|
+
"",
|
|
143
|
+
);
|
|
144
|
+
// ActionData: what the route's actions pass to fail(), which comes back
|
|
145
|
+
// to the page as its `form` prop after a failed plain-form submission
|
|
146
|
+
lines.push(
|
|
147
|
+
`type _FailData<R> = R extends { __fail: true; data: infer D } ? D : never;`,
|
|
148
|
+
`export type ActionData = {`,
|
|
149
|
+
` [K in _ActionKeys]: _PS[K] extends (...args: any[]) => infer R ? _FailData<Awaited<R>> : never;`,
|
|
150
|
+
`}[_ActionKeys];`,
|
|
151
|
+
"",
|
|
152
|
+
`export type PageProps = { data: PageData; params: Params; form?: ActionData };`,
|
|
153
|
+
"",
|
|
154
|
+
);
|
|
155
|
+
// PageServerLoad — annotate parameter, NOT return type, to preserve inference
|
|
156
|
+
lines.push(
|
|
157
|
+
`/** What load() receives: \`export async function load({ params }: PageServerLoadEvent)\`. */`,
|
|
158
|
+
`export type PageServerLoadEvent = {`,
|
|
159
|
+
` params: Params;`,
|
|
160
|
+
` request: Request;`,
|
|
161
|
+
` url: URL;`,
|
|
162
|
+
` locals: App.Locals;`,
|
|
163
|
+
` fetch: typeof fetch;`,
|
|
164
|
+
` getClientAddress: () => string;`,
|
|
165
|
+
` parent: () => Promise<Record<string, unknown>>;`,
|
|
166
|
+
`};`,
|
|
167
|
+
`/** Annotate the load() parameter only — not the return type — or PageData loses its concrete keys. */`,
|
|
168
|
+
`export type PageServerLoad = (event: PageServerLoadEvent) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
|
|
169
|
+
"",
|
|
170
|
+
);
|
|
171
|
+
// Actions — all exports except load and default
|
|
172
|
+
lines.push(
|
|
173
|
+
`type ActionCookies = {`,
|
|
174
|
+
` get(name: string): string | undefined;`,
|
|
175
|
+
` set(name: string, value: string, options?: {`,
|
|
176
|
+
` path?: string;`,
|
|
177
|
+
` domain?: string;`,
|
|
178
|
+
` maxAge?: number;`,
|
|
179
|
+
` expires?: Date;`,
|
|
180
|
+
` httpOnly?: boolean;`,
|
|
181
|
+
` secure?: boolean;`,
|
|
182
|
+
` sameSite?: "strict" | "lax" | "none";`,
|
|
183
|
+
` }): void;`,
|
|
184
|
+
` delete(name: string, options?: { path?: string; domain?: string }): void;`,
|
|
185
|
+
`};`,
|
|
186
|
+
`type _ActionKeys = Exclude<keyof _PS, "load" | "default" | "canMatch" | "csrf" | "loading">;`,
|
|
187
|
+
`/** What a form action receives: \`export async function add({ request }: ActionEvent)\`. */`,
|
|
188
|
+
`export type ActionEvent = {`,
|
|
189
|
+
` params: Params;`,
|
|
190
|
+
` request: Request;`,
|
|
191
|
+
` url: URL;`,
|
|
192
|
+
` locals: App.Locals;`,
|
|
193
|
+
` fetch: typeof fetch;`,
|
|
194
|
+
` getClientAddress: () => string;`,
|
|
195
|
+
` cookies: ActionCookies;`,
|
|
196
|
+
`};`,
|
|
197
|
+
`export type Actions = {`,
|
|
198
|
+
` [K in _ActionKeys]: (event: ActionEvent) => unknown | Promise<unknown>;`,
|
|
199
|
+
`};`,
|
|
200
|
+
"",
|
|
201
|
+
);
|
|
202
|
+
} else {
|
|
203
|
+
lines.push(
|
|
204
|
+
`export type PageData = Record<string, never>;`,
|
|
205
|
+
`export type ActionData = never;`,
|
|
206
|
+
`export type PageProps = { data: PageData; params: Params; form?: ActionData };`,
|
|
207
|
+
`export type PageServerLoad = never;`,
|
|
208
|
+
`export type Actions = Record<string, never>;`,
|
|
209
|
+
"",
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// --- LayoutData from +layout.server.ts ---
|
|
214
|
+
if (group.layoutServer) {
|
|
215
|
+
const imp = toImportPath(outFileDir, group.layoutServer.filePath);
|
|
216
|
+
lines.push(
|
|
217
|
+
`type _LS = typeof import("${imp}");`,
|
|
218
|
+
`export type LayoutData = _LS extends { load: (...args: any[]) => infer R }`,
|
|
219
|
+
` ? Awaited<R>`,
|
|
220
|
+
` : Record<string, never>;`,
|
|
221
|
+
"",
|
|
222
|
+
);
|
|
223
|
+
} else {
|
|
224
|
+
lines.push(`export type LayoutData = Record<string, never>;`);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
lines.push(
|
|
228
|
+
`export type LayoutProps = { data: LayoutData; params: Params; children?: unknown };`,
|
|
229
|
+
`/** What a layout's load() receives. */`,
|
|
230
|
+
`export type LayoutServerLoadEvent = {`,
|
|
231
|
+
` params: Params;`,
|
|
232
|
+
` request: Request;`,
|
|
233
|
+
` url: URL;`,
|
|
234
|
+
` locals: App.Locals;`,
|
|
235
|
+
` fetch: typeof fetch;`,
|
|
236
|
+
` getClientAddress: () => string;`,
|
|
237
|
+
` parent: () => Promise<Record<string, unknown>>;`,
|
|
238
|
+
`};`,
|
|
239
|
+
`export type LayoutServerLoad = (event: LayoutServerLoadEvent) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
|
|
240
|
+
"",
|
|
241
|
+
);
|
|
242
|
+
|
|
243
|
+
// --- +server.ts API route handlers ---
|
|
244
|
+
if (group.server) {
|
|
245
|
+
const imp = toImportPath(outFileDir, group.server.filePath);
|
|
246
|
+
lines.push(
|
|
247
|
+
`type _SRV = typeof import("${imp}");`,
|
|
248
|
+
`type _HttpMethods = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";`,
|
|
249
|
+
`type _ServerKeys = Extract<keyof _SRV, _HttpMethods>;`,
|
|
250
|
+
`export type ServerHandlers = {`,
|
|
251
|
+
` [K in _ServerKeys]: (ctx: {`,
|
|
252
|
+
` params: Params;`,
|
|
253
|
+
` request: Request;`,
|
|
254
|
+
` url: URL;`,
|
|
255
|
+
` locals: App.Locals;`,
|
|
256
|
+
` }) => Response | Promise<Response>;`,
|
|
257
|
+
`};`,
|
|
258
|
+
``,
|
|
259
|
+
`export type UpgradeContext = {`,
|
|
260
|
+
` request: Request;`,
|
|
261
|
+
` params: Params;`,
|
|
262
|
+
` url: URL;`,
|
|
263
|
+
` locals: App.Locals;`,
|
|
264
|
+
`};`,
|
|
265
|
+
``,
|
|
266
|
+
`type _UpgradeReturn = _SRV extends { upgrade: (...args: any[]) => infer R }`,
|
|
267
|
+
` ? Awaited<R>`,
|
|
268
|
+
` : {};`,
|
|
269
|
+
`export type WsData = { params: Params } & Omit<_UpgradeReturn, "__handler">;`,
|
|
270
|
+
``,
|
|
271
|
+
`/** The parts of Bun's ServerWebSocket a handler uses, so this file needs no Bun types installed. */`,
|
|
272
|
+
`export type SocketOf<D> = {`,
|
|
273
|
+
` readonly data: D;`,
|
|
274
|
+
` readonly readyState: number;`,
|
|
275
|
+
` readonly remoteAddress: string;`,
|
|
276
|
+
` send(data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`,
|
|
277
|
+
` close(code?: number, reason?: string): void;`,
|
|
278
|
+
` subscribe(topic: string): void;`,
|
|
279
|
+
` unsubscribe(topic: string): void;`,
|
|
280
|
+
` isSubscribed(topic: string): boolean;`,
|
|
281
|
+
` publish(topic: string, data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`,
|
|
282
|
+
`};`,
|
|
283
|
+
`export type WebSocketHandler = {`,
|
|
284
|
+
` open?(ws: SocketOf<WsData>): void | Promise<void>;`,
|
|
285
|
+
` message?(ws: SocketOf<WsData>, data: string | Uint8Array): void | Promise<void>;`,
|
|
286
|
+
` close?(ws: SocketOf<WsData>, code: number, reason?: string): void | Promise<void>;`,
|
|
287
|
+
` drain?(ws: SocketOf<WsData>): void | Promise<void>;`,
|
|
288
|
+
`};`,
|
|
289
|
+
"",
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// --- +error.tsx ---
|
|
294
|
+
if (group.error) {
|
|
295
|
+
lines.push(
|
|
296
|
+
`export type ErrorProps = { status: number; message: string; error: unknown; route: string };`,
|
|
297
|
+
"",
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return lines.join("\n");
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function generateAmbient(): string {
|
|
305
|
+
return [
|
|
306
|
+
"// Auto-generated by @sigil-dev/grimoire — do not edit",
|
|
307
|
+
"",
|
|
308
|
+
"declare namespace App {",
|
|
309
|
+
" // Extend this interface in your app's src/app.d.ts to add typed locals",
|
|
310
|
+
" interface Locals extends Record<string, unknown> {}",
|
|
311
|
+
"}",
|
|
312
|
+
"",
|
|
313
|
+
"// Available in all route files without import.",
|
|
314
|
+
"// Params default to Record<string,string>; for per-route typed params import from './$types'.",
|
|
315
|
+
"// Note: using these globals widens return types — PageData loses concrete keys.",
|
|
316
|
+
"// For precise data inference annotate load() with PageServerLoad from './$types'.",
|
|
317
|
+
"",
|
|
318
|
+
"type PageServerLoad<",
|
|
319
|
+
" P extends Record<string, string> = Record<string, string>",
|
|
320
|
+
"> = (ctx: {",
|
|
321
|
+
" params: P;",
|
|
322
|
+
" request: Request;",
|
|
323
|
+
" url: URL;",
|
|
324
|
+
" locals: App.Locals;",
|
|
325
|
+
" fetch: typeof fetch;",
|
|
326
|
+
" parent: () => Promise<Record<string, unknown>>;",
|
|
327
|
+
"}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
|
|
328
|
+
"",
|
|
329
|
+
"type LayoutServerLoad<",
|
|
330
|
+
" P extends Record<string, string> = Record<string, string>",
|
|
331
|
+
"> = (ctx: {",
|
|
332
|
+
" params: P;",
|
|
333
|
+
" request: Request;",
|
|
334
|
+
" url: URL;",
|
|
335
|
+
" locals: App.Locals;",
|
|
336
|
+
" fetch: typeof fetch;",
|
|
337
|
+
" parent: () => Promise<Record<string, unknown>>;",
|
|
338
|
+
"}) => Record<string, unknown> | Promise<Record<string, unknown>>;",
|
|
339
|
+
"",
|
|
340
|
+
"type RequestHandler<",
|
|
341
|
+
" P extends Record<string, string> = Record<string, string>",
|
|
342
|
+
"> = (ctx: {",
|
|
343
|
+
" params: P;",
|
|
344
|
+
" request: Request;",
|
|
345
|
+
" url: URL;",
|
|
346
|
+
" locals: App.Locals;",
|
|
347
|
+
"}) => Response | Promise<Response>;",
|
|
348
|
+
"",
|
|
349
|
+
"type PageProps<",
|
|
350
|
+
" D extends Record<string, unknown> = Record<string, unknown>,",
|
|
351
|
+
" P extends Record<string, string> = Record<string, string>",
|
|
352
|
+
"> = { data: D; params: P };",
|
|
353
|
+
"",
|
|
354
|
+
"type LayoutProps<",
|
|
355
|
+
" D extends Record<string, unknown> = Record<string, unknown>,",
|
|
356
|
+
" P extends Record<string, string> = Record<string, string>",
|
|
357
|
+
"> = { data: D; params: P; children?: unknown };",
|
|
358
|
+
"",
|
|
359
|
+
"type ErrorProps = { status: number; message: string; error: unknown; route: string };",
|
|
360
|
+
"",
|
|
361
|
+
"type UpgradeContext<",
|
|
362
|
+
" P extends Record<string, string> = Record<string, string>",
|
|
363
|
+
"> = {",
|
|
364
|
+
" params: P;",
|
|
365
|
+
" request: Request;",
|
|
366
|
+
" url: URL;",
|
|
367
|
+
" locals: App.Locals;",
|
|
368
|
+
"};",
|
|
369
|
+
"",
|
|
370
|
+
].join("\n");
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function generateTsConfig(
|
|
374
|
+
aliases: Record<string, string>,
|
|
375
|
+
grimoireDir: string,
|
|
376
|
+
): string {
|
|
377
|
+
// paths without a baseUrl resolve against this file's directory
|
|
378
|
+
const paths: Record<string, string[]> = {};
|
|
379
|
+
for (const [prefix, dir] of Object.entries(aliases)) {
|
|
380
|
+
const rel = relative(grimoireDir, dir).replace(/\\/g, "/");
|
|
381
|
+
paths[prefix] = [rel];
|
|
382
|
+
paths[`${prefix}/*`] = [`${rel}/*`];
|
|
383
|
+
}
|
|
384
|
+
return JSON.stringify(
|
|
385
|
+
{
|
|
386
|
+
compilerOptions: {
|
|
387
|
+
// Merges ".." (project root) and "./types" (.grimoire/types) into one
|
|
388
|
+
// virtual root so `import from './$types'` resolves without path aliases.
|
|
389
|
+
rootDirs: ["..", "./types"],
|
|
390
|
+
...(Object.keys(paths).length > 0 ? { paths } : {}),
|
|
391
|
+
},
|
|
392
|
+
include: ["types/**/*.d.ts"],
|
|
393
|
+
},
|
|
394
|
+
null,
|
|
395
|
+
2,
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export async function generateTypes(
|
|
400
|
+
tree: RouteTree,
|
|
401
|
+
config: TypegenConfig,
|
|
402
|
+
): Promise<void> {
|
|
403
|
+
const { projectRoot, outDir } = config;
|
|
404
|
+
|
|
405
|
+
// Skip rm of the whole dir — on Windows, rm+mkdir in quick succession can
|
|
406
|
+
// race and leave dirs in an unusable state. Files this run does not write
|
|
407
|
+
// are removed one by one afterwards instead.
|
|
408
|
+
await mkdir(outDir, { recursive: true }).catch(() => {});
|
|
409
|
+
|
|
410
|
+
const groups = groupByDirectory(tree);
|
|
411
|
+
const written = new Set<string>();
|
|
412
|
+
|
|
413
|
+
for (const group of groups.values()) {
|
|
414
|
+
const routeRelDir = safeRelativeDir(
|
|
415
|
+
projectRoot,
|
|
416
|
+
config.routesDir,
|
|
417
|
+
group.dir,
|
|
418
|
+
);
|
|
419
|
+
const outFileDir = join(outDir, routeRelDir);
|
|
420
|
+
// Use mkdirSync — async mkdir on Windows/Bun can report success before
|
|
421
|
+
// the directory is actually visible to subsequent fs calls
|
|
422
|
+
mkdirSync(outFileDir, { recursive: true });
|
|
423
|
+
|
|
424
|
+
const content = generateTypesForGroup(group, outFileDir);
|
|
425
|
+
const file = join(outFileDir, "$types.d.ts");
|
|
426
|
+
writeFileSync(file, content, "utf-8");
|
|
427
|
+
written.add(file);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// A deleted route leaves its $types.d.ts behind, still importing the
|
|
431
|
+
// deleted file, and tsc fails on it until .grimoire is cleared by hand.
|
|
432
|
+
for (const entry of readdirSync(outDir, {
|
|
433
|
+
recursive: true,
|
|
434
|
+
withFileTypes: true,
|
|
435
|
+
})) {
|
|
436
|
+
const file = join(entry.parentPath, entry.name);
|
|
437
|
+
if (entry.isFile() && entry.name === "$types.d.ts" && !written.has(file)) {
|
|
438
|
+
rmSync(file, { force: true });
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
writeFileSync(join(outDir, "ambient.d.ts"), generateAmbient(), "utf-8");
|
|
443
|
+
|
|
444
|
+
const grimoireDir = dirname(outDir);
|
|
445
|
+
writeFileSync(
|
|
446
|
+
join(grimoireDir, "tsconfig.generated.json"),
|
|
447
|
+
generateTsConfig(config.aliases ?? {}, grimoireDir),
|
|
448
|
+
"utf-8",
|
|
449
|
+
);
|
|
450
|
+
}
|