@warlock.js/core 5.26.0 → 5.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/esm/cli/commands/openapi-generator.action.mjs +43 -0
- package/esm/cli/commands/openapi-generator.action.mjs.map +1 -0
- package/esm/cli/commands/openapi-generator.command.mjs +44 -0
- package/esm/cli/commands/openapi-generator.command.mjs.map +1 -0
- package/esm/cli/framework-cli-commands.mjs +2 -0
- package/esm/cli/framework-cli-commands.mjs.map +1 -1
- package/esm/dev-server/build-development-openapi-document.mjs +36 -0
- package/esm/dev-server/build-development-openapi-document.mjs.map +1 -0
- package/esm/dev-server/collect-development-api-routes.mjs +27 -0
- package/esm/dev-server/collect-development-api-routes.mjs.map +1 -0
- package/esm/dev-server/dev-logger.mjs +9 -1
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs +6 -3
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs +17 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/model-resource-typings.mjs +246 -0
- package/esm/dev-server/model-resource-typings.mjs.map +1 -0
- package/esm/dev-server/type-generator.mjs +46 -2
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/http/index.d.mts +2 -1
- package/esm/http/request.d.mts +2 -2
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/serialized.d.mts +114 -0
- package/esm/http/serialized.d.mts.map +1 -0
- package/esm/index.d.mts +8 -3
- package/esm/index.mjs +4 -1
- package/esm/openapi/build-openapi-document.d.mts +17 -0
- package/esm/openapi/build-openapi-document.d.mts.map +1 -0
- package/esm/openapi/build-openapi-document.mjs +124 -0
- package/esm/openapi/build-openapi-document.mjs.map +1 -0
- package/esm/openapi/cast-schema.mjs +89 -0
- package/esm/openapi/cast-schema.mjs.map +1 -0
- package/esm/openapi/collect-openapi-document.mjs +40 -0
- package/esm/openapi/collect-openapi-document.mjs.map +1 -0
- package/esm/openapi/development-openapi-provider.d.mts +17 -0
- package/esm/openapi/development-openapi-provider.d.mts.map +1 -0
- package/esm/openapi/development-openapi-provider.mjs +21 -0
- package/esm/openapi/development-openapi-provider.mjs.map +1 -0
- package/esm/openapi/error-responses.mjs +67 -0
- package/esm/openapi/error-responses.mjs.map +1 -0
- package/esm/openapi/index.d.mts +3 -0
- package/esm/openapi/index.mjs +4 -0
- package/esm/openapi/openapi-child-output.mjs +57 -0
- package/esm/openapi/openapi-child-output.mjs.map +1 -0
- package/esm/openapi/openapi-protocol.mjs +30 -0
- package/esm/openapi/openapi-protocol.mjs.map +1 -0
- package/esm/openapi/paths.mjs +63 -0
- package/esm/openapi/paths.mjs.map +1 -0
- package/esm/openapi/request-schemas.mjs +138 -0
- package/esm/openapi/request-schemas.mjs.map +1 -0
- package/esm/openapi/response-schemas.mjs +85 -0
- package/esm/openapi/response-schemas.mjs.map +1 -0
- package/esm/openapi/schema-registry.mjs +143 -0
- package/esm/openapi/schema-registry.mjs.map +1 -0
- package/esm/openapi/security.mjs +98 -0
- package/esm/openapi/security.mjs.map +1 -0
- package/esm/openapi/types.d.mts +119 -0
- package/esm/openapi/types.d.mts.map +1 -0
- package/esm/production/registration-child-runner.mjs +139 -0
- package/esm/production/registration-child-runner.mjs.map +1 -0
- package/esm/production/route-registration-child.mjs +30 -2
- package/esm/production/route-registration-child.mjs.map +1 -1
- package/esm/production/route-registration-snapshot.mjs +22 -119
- package/esm/production/route-registration-snapshot.mjs.map +1 -1
- package/esm/resource/define-resource.d.mts +44 -14
- package/esm/resource/define-resource.d.mts.map +1 -1
- package/esm/resource/define-resource.mjs +0 -40
- package/esm/resource/define-resource.mjs.map +1 -1
- package/esm/resource/index.d.mts +1 -1
- package/esm/resource/resource.d.mts +4 -4
- package/esm/resource/resource.d.mts.map +1 -1
- package/esm/resource/resource.mjs.map +1 -1
- package/esm/resource/types.d.mts +89 -4
- package/esm/resource/types.d.mts.map +1 -1
- package/esm/restful/restful.d.mts +5 -5
- package/esm/restful/restful.d.mts.map +1 -1
- package/esm/router/index.d.mts +1 -1
- package/esm/router/named-api-routes-with-responses.mjs +59 -0
- package/esm/router/named-api-routes-with-responses.mjs.map +1 -0
- package/esm/router/response-schema-types.mjs +100 -0
- package/esm/router/response-schema-types.mjs.map +1 -0
- package/esm/router/router.d.mts +2 -2
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +38 -11
- package/esm/router/router.mjs.map +1 -1
- package/esm/router/types.d.mts +16 -1
- package/esm/router/types.d.mts.map +1 -1
- package/llms-full.txt +265 -5
- package/llms.txt +3 -2
- package/package.json +13 -13
- package/skills/README.md +3 -2
- package/skills/create-controller/SKILL.md +39 -2
- package/skills/define-resource/SKILL.md +100 -1
- package/skills/generate-openapi/SKILL.md +120 -0
- package/skills/index.md +3 -3
- package/skills/validate-input/SKILL.md +2 -2
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { dirname, isAbsolute, relative } from "node:path";
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
|
|
5
|
+
//#region ../core/src/dev-server/model-resource-typings.ts
|
|
6
|
+
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
7
|
+
function hasModifier(node, kind) {
|
|
8
|
+
return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((m) => m.kind === kind) ?? false);
|
|
9
|
+
}
|
|
10
|
+
function unwrapParentheses(expression) {
|
|
11
|
+
let current = expression;
|
|
12
|
+
while (ts.isParenthesizedExpression(current)) current = current.expression;
|
|
13
|
+
return current;
|
|
14
|
+
}
|
|
15
|
+
/** Top-level names this file declares, and the names each is exported under. */
|
|
16
|
+
function readLocalDeclarations(sourceFile) {
|
|
17
|
+
const declared = /* @__PURE__ */ new Set();
|
|
18
|
+
const exportNames = /* @__PURE__ */ new Map();
|
|
19
|
+
const addExport = (local, exported) => {
|
|
20
|
+
const names = exportNames.get(local) ?? [];
|
|
21
|
+
names.push(exported);
|
|
22
|
+
exportNames.set(local, names);
|
|
23
|
+
};
|
|
24
|
+
for (const statement of sourceFile.statements) {
|
|
25
|
+
const exported = hasModifier(statement, ts.SyntaxKind.ExportKeyword);
|
|
26
|
+
const isDefault = hasModifier(statement, ts.SyntaxKind.DefaultKeyword);
|
|
27
|
+
if ((ts.isClassDeclaration(statement) || ts.isFunctionDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name) {
|
|
28
|
+
declared.add(statement.name.text);
|
|
29
|
+
if (exported) addExport(statement.name.text, isDefault ? "default" : statement.name.text);
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (ts.isVariableStatement(statement)) {
|
|
33
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
34
|
+
if (!ts.isIdentifier(declaration.name)) continue;
|
|
35
|
+
declared.add(declaration.name.text);
|
|
36
|
+
if (exported) addExport(declaration.name.text, declaration.name.text);
|
|
37
|
+
}
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (ts.isExportDeclaration(statement) && !statement.moduleSpecifier && !statement.isTypeOnly && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
|
|
41
|
+
for (const element of statement.exportClause.elements) {
|
|
42
|
+
if (element.isTypeOnly) continue;
|
|
43
|
+
addExport((element.propertyName ?? element.name).text, element.name.text);
|
|
44
|
+
}
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (ts.isExportAssignment(statement) && !statement.isExportEquals && ts.isIdentifier(statement.expression)) addExport(statement.expression.text, "default");
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
declared,
|
|
51
|
+
exportNames
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** Prefer a named export over `default`; among named exports, the first sorted. */
|
|
55
|
+
function pickExportName(names) {
|
|
56
|
+
if (!names || names.length === 0) return void 0;
|
|
57
|
+
return names.filter((name) => name !== "default").sort()[0] ?? "default";
|
|
58
|
+
}
|
|
59
|
+
function readImportBindings(sourceFile) {
|
|
60
|
+
const bindings = /* @__PURE__ */ new Map();
|
|
61
|
+
for (const statement of sourceFile.statements) {
|
|
62
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
|
|
63
|
+
const clause = statement.importClause;
|
|
64
|
+
const specifier = statement.moduleSpecifier.text;
|
|
65
|
+
if (!clause) continue;
|
|
66
|
+
if (clause.name) bindings.set(clause.name.text, {
|
|
67
|
+
specifier,
|
|
68
|
+
exportName: "default"
|
|
69
|
+
});
|
|
70
|
+
if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) for (const element of clause.namedBindings.elements) bindings.set(element.name.text, {
|
|
71
|
+
specifier,
|
|
72
|
+
exportName: (element.propertyName ?? element.name).text
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return bindings;
|
|
76
|
+
}
|
|
77
|
+
/** The identifier a class assigns to `static resource`, when it is a bare identifier. */
|
|
78
|
+
function readStaticResourceReference(member) {
|
|
79
|
+
if (!ts.isPropertyDeclaration(member)) return void 0;
|
|
80
|
+
if (!hasModifier(member, ts.SyntaxKind.StaticKeyword)) return void 0;
|
|
81
|
+
if (hasModifier(member, ts.SyntaxKind.DeclareKeyword)) return void 0;
|
|
82
|
+
if (!((ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) && member.name.text === "resource")) return void 0;
|
|
83
|
+
if (!member.initializer) return void 0;
|
|
84
|
+
const initializer = unwrapParentheses(member.initializer);
|
|
85
|
+
return ts.isIdentifier(initializer) ? { name: initializer.text } : "computed";
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Read every model class of one file that declares `static resource = <Identifier>`
|
|
89
|
+
* and resolve it to a model export plus a resource export. Pure: the only
|
|
90
|
+
* outside knowledge is the injected {@link ExtractModelResourcesInput.resolveImport}.
|
|
91
|
+
*/
|
|
92
|
+
function extractModelResourceEntries(input) {
|
|
93
|
+
const result = {
|
|
94
|
+
entries: [],
|
|
95
|
+
skipped: []
|
|
96
|
+
};
|
|
97
|
+
if (!input.source.includes("resource")) return result;
|
|
98
|
+
const sourceFile = ts.createSourceFile(input.absolutePath, input.source, ts.ScriptTarget.ESNext, false, input.absolutePath.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
99
|
+
const { declared, exportNames } = readLocalDeclarations(sourceFile);
|
|
100
|
+
const imports = readImportBindings(sourceFile);
|
|
101
|
+
for (const statement of sourceFile.statements) {
|
|
102
|
+
if (!ts.isClassDeclaration(statement) || !statement.name) continue;
|
|
103
|
+
const className = statement.name.text;
|
|
104
|
+
let reference;
|
|
105
|
+
for (const member of statement.members) reference = readStaticResourceReference(member) ?? reference;
|
|
106
|
+
if (reference === void 0) continue;
|
|
107
|
+
const skip = (reason) => {
|
|
108
|
+
result.skipped.push({
|
|
109
|
+
className,
|
|
110
|
+
modelFile: input.absolutePath,
|
|
111
|
+
reason
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
if (reference === "computed") {
|
|
115
|
+
skip("`static resource` is not a plain identifier");
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (statement.typeParameters?.some((parameter) => parameter.default === void 0)) {
|
|
119
|
+
skip("the model class is generic");
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const modelExport = pickExportName(exportNames.get(className));
|
|
123
|
+
if (modelExport === void 0) {
|
|
124
|
+
skip("the model class is not exported");
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (modelExport !== "default" && !IDENTIFIER.test(modelExport)) {
|
|
128
|
+
skip("the model export name is not an identifier");
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const binding = imports.get(reference.name);
|
|
132
|
+
let resourceFile;
|
|
133
|
+
let resourceExport;
|
|
134
|
+
if (binding) {
|
|
135
|
+
resourceFile = input.resolveImport(binding.specifier);
|
|
136
|
+
resourceExport = binding.exportName;
|
|
137
|
+
} else if (declared.has(reference.name)) {
|
|
138
|
+
resourceFile = input.absolutePath;
|
|
139
|
+
resourceExport = pickExportName(exportNames.get(reference.name));
|
|
140
|
+
}
|
|
141
|
+
if (resourceFile === void 0 || resourceExport === void 0) {
|
|
142
|
+
skip(`\`${reference.name}\` cannot be resolved to an exported module member`);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (resourceExport !== "default" && !IDENTIFIER.test(resourceExport)) {
|
|
146
|
+
skip("the resource export name is not an identifier");
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
result.entries.push({
|
|
150
|
+
className,
|
|
151
|
+
modelFile: input.absolutePath,
|
|
152
|
+
modelExport,
|
|
153
|
+
resourceFile,
|
|
154
|
+
resourceExport
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
/** Module specifier, relative to the typings directory, without a TypeScript extension. */
|
|
160
|
+
function toTypeImportSpecifier(typingsDirectory, absoluteFile) {
|
|
161
|
+
const path = relative(typingsDirectory, absoluteFile).replaceAll("\\", "/");
|
|
162
|
+
if (isAbsolute(path)) return void 0;
|
|
163
|
+
const withoutExtension = path.replace(/\.(?:d\.)?(?:ts|tsx|mts|cts)$/, "");
|
|
164
|
+
return withoutExtension.startsWith(".") ? withoutExtension : `./${withoutExtension}`;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Registry keys: the class name, suffixed `_2`, `_3`, ... when several model
|
|
168
|
+
* files declare the same class name. Order is by class name, then by file path,
|
|
169
|
+
* so the same set of models always yields the same keys and the same text.
|
|
170
|
+
*/
|
|
171
|
+
function assignRegistryKeys(entries) {
|
|
172
|
+
const sorted = [...entries].sort((a, b) => a.className.localeCompare(b.className, "en") || a.modelFile.localeCompare(b.modelFile, "en") || a.modelExport.localeCompare(b.modelExport, "en"));
|
|
173
|
+
const taken = /* @__PURE__ */ new Set();
|
|
174
|
+
const counts = /* @__PURE__ */ new Map();
|
|
175
|
+
return sorted.map((entry) => {
|
|
176
|
+
let count = (counts.get(entry.className) ?? 0) + 1;
|
|
177
|
+
let key = count === 1 ? entry.className : `${entry.className}_${count}`;
|
|
178
|
+
while (taken.has(key)) {
|
|
179
|
+
count += 1;
|
|
180
|
+
key = `${entry.className}_${count}`;
|
|
181
|
+
}
|
|
182
|
+
counts.set(entry.className, count);
|
|
183
|
+
taken.add(key);
|
|
184
|
+
return {
|
|
185
|
+
key,
|
|
186
|
+
entry
|
|
187
|
+
};
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Text of the generated declaration file.
|
|
192
|
+
*
|
|
193
|
+
* @param entries Every resolved model, in any order.
|
|
194
|
+
* @param typingsDirectory Absolute directory the file is written to; import
|
|
195
|
+
* specifiers are relative to it.
|
|
196
|
+
*/
|
|
197
|
+
function renderModelResourceRegistry(entries, typingsDirectory) {
|
|
198
|
+
const lines = [];
|
|
199
|
+
for (const { key, entry } of assignRegistryKeys(entries)) {
|
|
200
|
+
const modelPath = toTypeImportSpecifier(typingsDirectory, entry.modelFile);
|
|
201
|
+
const resourcePath = toTypeImportSpecifier(typingsDirectory, entry.resourceFile);
|
|
202
|
+
if (modelPath === void 0 || resourcePath === void 0) continue;
|
|
203
|
+
const model = `import(${JSON.stringify(modelPath)}).${entry.modelExport}`;
|
|
204
|
+
const resource = `typeof import(${JSON.stringify(resourcePath)}).${entry.resourceExport}`;
|
|
205
|
+
lines.push(` ${JSON.stringify(key)}: { model: ${model}; resource: ${resource} };`);
|
|
206
|
+
}
|
|
207
|
+
return `// Auto-generated by Warlock.js - DO NOT EDIT
|
|
208
|
+
// One entry per model class that declares \`static resource = <Resource>\`, so
|
|
209
|
+
// \`Serialized<Model>\` resolves to the resource output. Models whose resource
|
|
210
|
+
// cannot be resolved statically are left out.
|
|
211
|
+
|
|
212
|
+
import "@warlock.js/core";
|
|
213
|
+
|
|
214
|
+
declare module "@warlock.js/core" {
|
|
215
|
+
interface ModelResourceRegistry {
|
|
216
|
+
${lines.join("\n")}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
`;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Write `content` to `filePath` through a temporary sibling and a rename, so a
|
|
223
|
+
* reader (the editor's TypeScript server) never sees a half-written file, and
|
|
224
|
+
* skip the write entirely when the file already holds exactly this text.
|
|
225
|
+
*
|
|
226
|
+
* @returns `true` when the file was written.
|
|
227
|
+
*/
|
|
228
|
+
async function writeFileIfChanged(filePath, content) {
|
|
229
|
+
try {
|
|
230
|
+
if (await readFile(filePath, "utf-8") === content) return false;
|
|
231
|
+
} catch {}
|
|
232
|
+
await mkdir(dirname(filePath), { recursive: true });
|
|
233
|
+
const temporaryPath = `${filePath}.${process.pid}.tmp`;
|
|
234
|
+
try {
|
|
235
|
+
await writeFile(temporaryPath, content, "utf-8");
|
|
236
|
+
await rename(temporaryPath, filePath);
|
|
237
|
+
} catch (error) {
|
|
238
|
+
await rm(temporaryPath, { force: true });
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
//#endregion
|
|
245
|
+
export { extractModelResourceEntries, renderModelResourceRegistry, writeFileIfChanged };
|
|
246
|
+
//# sourceMappingURL=model-resource-typings.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-resource-typings.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/model-resource-typings.ts"],"sourcesContent":["import { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, relative } from \"node:path\";\nimport ts from \"typescript\";\n\n/**\n * Static `ModelResourceRegistry` generation.\n *\n * `Serialized<User>` can only resolve a model to its resource output through an\n * entry in the augmentable `ModelResourceRegistry` (see `http/serialized.ts`).\n * This module derives those entries from source: a model class that declares\n * `static resource = UserResource` produces\n *\n * ```ts\n * \"User\": { model: import(\"<model file>\").User; resource: typeof import(\"<resource file>\").UserResource };\n * ```\n *\n * Everything here is syntactic. It reads one `ts.createSourceFile` AST per model\n * file, follows the identifier through that file's own imports, and never\n * imports or executes application code (`read-config-ast.ts` explains why a\n * type checker is not an option). Anything it cannot prove from the AST alone\n * (a computed expression, `lazy(...)`, a namespace import, a class that is not\n * exported) is skipped, and nothing is recorded for it: a guessed entry would\n * make `Serialized` lie, which is worse than the raw-data type it falls back to.\n */\n\n/** One model class whose resource could be resolved statically. */\nexport type ModelResourceEntry = {\n /** The model class name (the registry key before de-duplication). */\n className: string;\n /** Absolute path of the model file. */\n modelFile: string;\n /** How the model file exports the class: its export name, or `\"default\"`. */\n modelExport: string;\n /** Absolute path of the module that exports the resource. */\n resourceFile: string;\n /** How that module exports the resource: its export name, or `\"default\"`. */\n resourceExport: string;\n};\n\n/** A model that declares `static resource` but could not be resolved. */\nexport type SkippedModelResource = {\n className: string;\n modelFile: string;\n reason: string;\n};\n\nexport type ModelResourceExtraction = {\n entries: ModelResourceEntry[];\n skipped: SkippedModelResource[];\n};\n\nexport type ExtractModelResourcesInput = {\n /** Source text of the model file. */\n source: string;\n /** Absolute path of the model file. */\n absolutePath: string;\n /**\n * Resolve an import specifier of the model file (relative or tsconfig alias) to\n * an absolute file path, or `undefined` when it does not point at app source.\n */\n resolveImport: (specifier: string) => string | undefined;\n};\n\ntype ImportBinding = { specifier: string; exportName: string };\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\nfunction hasModifier(node: ts.Node, kind: ts.SyntaxKind): boolean {\n return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((m) => m.kind === kind) ?? false);\n}\n\nfunction unwrapParentheses(expression: ts.Expression): ts.Expression {\n let current = expression;\n\n while (ts.isParenthesizedExpression(current)) {\n current = current.expression;\n }\n\n return current;\n}\n\n/** Top-level names this file declares, and the names each is exported under. */\nfunction readLocalDeclarations(sourceFile: ts.SourceFile): {\n declared: Set<string>;\n exportNames: Map<string, string[]>;\n} {\n const declared = new Set<string>();\n const exportNames = new Map<string, string[]>();\n\n const addExport = (local: string, exported: string): void => {\n const names = exportNames.get(local) ?? [];\n\n names.push(exported);\n exportNames.set(local, names);\n };\n\n for (const statement of sourceFile.statements) {\n const exported = hasModifier(statement, ts.SyntaxKind.ExportKeyword);\n const isDefault = hasModifier(statement, ts.SyntaxKind.DefaultKeyword);\n\n if (\n (ts.isClassDeclaration(statement) ||\n ts.isFunctionDeclaration(statement) ||\n ts.isEnumDeclaration(statement)) &&\n statement.name\n ) {\n declared.add(statement.name.text);\n\n if (exported) {\n addExport(statement.name.text, isDefault ? \"default\" : statement.name.text);\n }\n\n continue;\n }\n\n if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name)) continue;\n\n declared.add(declaration.name.text);\n\n if (exported) {\n addExport(declaration.name.text, declaration.name.text);\n }\n }\n\n continue;\n }\n\n // `export { A, B as C }` (local form only; a `from` clause re-exports a foreign name).\n if (\n ts.isExportDeclaration(statement) &&\n !statement.moduleSpecifier &&\n !statement.isTypeOnly &&\n statement.exportClause &&\n ts.isNamedExports(statement.exportClause)\n ) {\n for (const element of statement.exportClause.elements) {\n if (element.isTypeOnly) continue;\n\n addExport((element.propertyName ?? element.name).text, element.name.text);\n }\n\n continue;\n }\n\n // `export default UserResource;`\n if (\n ts.isExportAssignment(statement) &&\n !statement.isExportEquals &&\n ts.isIdentifier(statement.expression)\n ) {\n addExport(statement.expression.text, \"default\");\n }\n }\n\n return { declared, exportNames };\n}\n\n/** Prefer a named export over `default`; among named exports, the first sorted. */\nfunction pickExportName(names: readonly string[] | undefined): string | undefined {\n if (!names || names.length === 0) return undefined;\n\n const named = names.filter((name) => name !== \"default\").sort();\n\n return named[0] ?? \"default\";\n}\n\nfunction readImportBindings(sourceFile: ts.SourceFile): Map<string, ImportBinding> {\n const bindings = new Map<string, ImportBinding>();\n\n for (const statement of sourceFile.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) {\n continue;\n }\n\n const clause = statement.importClause;\n const specifier = statement.moduleSpecifier.text;\n\n if (!clause) continue;\n\n if (clause.name) {\n bindings.set(clause.name.text, { specifier, exportName: \"default\" });\n }\n\n // A namespace import (`import * as ns`) cannot be the bare identifier a\n // `static resource = X` reads, so it never becomes a binding.\n if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {\n for (const element of clause.namedBindings.elements) {\n bindings.set(element.name.text, {\n specifier,\n exportName: (element.propertyName ?? element.name).text,\n });\n }\n }\n }\n\n return bindings;\n}\n\n/** The identifier a class assigns to `static resource`, when it is a bare identifier. */\nfunction readStaticResourceReference(\n member: ts.ClassElement,\n): { name: string } | \"computed\" | undefined {\n if (!ts.isPropertyDeclaration(member)) return undefined;\n if (!hasModifier(member, ts.SyntaxKind.StaticKeyword)) return undefined;\n if (hasModifier(member, ts.SyntaxKind.DeclareKeyword)) return undefined;\n\n const isResourceName =\n (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) &&\n member.name.text === \"resource\";\n\n if (!isResourceName) return undefined;\n if (!member.initializer) return undefined;\n\n const initializer = unwrapParentheses(member.initializer);\n\n return ts.isIdentifier(initializer) ? { name: initializer.text } : \"computed\";\n}\n\n/**\n * Read every model class of one file that declares `static resource = <Identifier>`\n * and resolve it to a model export plus a resource export. Pure: the only\n * outside knowledge is the injected {@link ExtractModelResourcesInput.resolveImport}.\n */\nexport function extractModelResourceEntries(\n input: ExtractModelResourcesInput,\n): ModelResourceExtraction {\n const result: ModelResourceExtraction = { entries: [], skipped: [] };\n\n // Cheap exit: most model files declare no resource.\n if (!input.source.includes(\"resource\")) return result;\n\n const sourceFile = ts.createSourceFile(\n input.absolutePath,\n input.source,\n ts.ScriptTarget.ESNext,\n /* setParentNodes */ false,\n input.absolutePath.endsWith(\"x\") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,\n );\n\n const { declared, exportNames } = readLocalDeclarations(sourceFile);\n const imports = readImportBindings(sourceFile);\n\n for (const statement of sourceFile.statements) {\n if (!ts.isClassDeclaration(statement) || !statement.name) continue;\n\n const className = statement.name.text;\n\n let reference: { name: string } | \"computed\" | undefined;\n\n for (const member of statement.members) {\n reference = readStaticResourceReference(member) ?? reference;\n }\n\n if (reference === undefined) continue;\n\n const skip = (reason: string): void => {\n result.skipped.push({ className, modelFile: input.absolutePath, reason });\n };\n\n if (reference === \"computed\") {\n skip(\"`static resource` is not a plain identifier\");\n continue;\n }\n\n const requiresTypeArguments = statement.typeParameters?.some(\n (parameter) => parameter.default === undefined,\n );\n\n if (requiresTypeArguments) {\n skip(\"the model class is generic\");\n continue;\n }\n\n const modelExport = pickExportName(exportNames.get(className));\n\n if (modelExport === undefined) {\n skip(\"the model class is not exported\");\n continue;\n }\n\n if (modelExport !== \"default\" && !IDENTIFIER.test(modelExport)) {\n skip(\"the model export name is not an identifier\");\n continue;\n }\n\n const binding = imports.get(reference.name);\n\n let resourceFile: string | undefined;\n let resourceExport: string | undefined;\n\n if (binding) {\n resourceFile = input.resolveImport(binding.specifier);\n resourceExport = binding.exportName;\n } else if (declared.has(reference.name)) {\n resourceFile = input.absolutePath;\n resourceExport = pickExportName(exportNames.get(reference.name));\n }\n\n if (resourceFile === undefined || resourceExport === undefined) {\n skip(`\\`${reference.name}\\` cannot be resolved to an exported module member`);\n continue;\n }\n\n if (resourceExport !== \"default\" && !IDENTIFIER.test(resourceExport)) {\n skip(\"the resource export name is not an identifier\");\n continue;\n }\n\n result.entries.push({\n className,\n modelFile: input.absolutePath,\n modelExport,\n resourceFile,\n resourceExport,\n });\n }\n\n return result;\n}\n\n/** Module specifier, relative to the typings directory, without a TypeScript extension. */\nfunction toTypeImportSpecifier(typingsDirectory: string, absoluteFile: string): string | undefined {\n const path = relative(typingsDirectory, absoluteFile).replaceAll(\"\\\\\", \"/\");\n\n // A different drive (Windows) has no relative form; do not emit a guess.\n if (isAbsolute(path)) return undefined;\n\n const withoutExtension = path.replace(/\\.(?:d\\.)?(?:ts|tsx|mts|cts)$/, \"\");\n\n return withoutExtension.startsWith(\".\") ? withoutExtension : `./${withoutExtension}`;\n}\n\n/**\n * Registry keys: the class name, suffixed `_2`, `_3`, ... when several model\n * files declare the same class name. Order is by class name, then by file path,\n * so the same set of models always yields the same keys and the same text.\n */\nexport function assignRegistryKeys(\n entries: readonly ModelResourceEntry[],\n): Array<{ key: string; entry: ModelResourceEntry }> {\n const sorted = [...entries].sort(\n (a, b) =>\n a.className.localeCompare(b.className, \"en\") ||\n a.modelFile.localeCompare(b.modelFile, \"en\") ||\n a.modelExport.localeCompare(b.modelExport, \"en\"),\n );\n\n const taken = new Set<string>();\n const counts = new Map<string, number>();\n\n return sorted.map((entry) => {\n let count = (counts.get(entry.className) ?? 0) + 1;\n let key = count === 1 ? entry.className : `${entry.className}_${count}`;\n\n while (taken.has(key)) {\n count += 1;\n key = `${entry.className}_${count}`;\n }\n\n counts.set(entry.className, count);\n taken.add(key);\n\n return { key, entry };\n });\n}\n\n/**\n * Text of the generated declaration file.\n *\n * @param entries Every resolved model, in any order.\n * @param typingsDirectory Absolute directory the file is written to; import\n * specifiers are relative to it.\n */\nexport function renderModelResourceRegistry(\n entries: readonly ModelResourceEntry[],\n typingsDirectory: string,\n): string {\n const lines: string[] = [];\n\n for (const { key, entry } of assignRegistryKeys(entries)) {\n const modelPath = toTypeImportSpecifier(typingsDirectory, entry.modelFile);\n const resourcePath = toTypeImportSpecifier(typingsDirectory, entry.resourceFile);\n\n if (modelPath === undefined || resourcePath === undefined) continue;\n\n const model = `import(${JSON.stringify(modelPath)}).${entry.modelExport}`;\n const resource = `typeof import(${JSON.stringify(resourcePath)}).${entry.resourceExport}`;\n\n lines.push(` ${JSON.stringify(key)}: { model: ${model}; resource: ${resource} };`);\n }\n\n return `// Auto-generated by Warlock.js - DO NOT EDIT\n// One entry per model class that declares \\`static resource = <Resource>\\`, so\n// \\`Serialized<Model>\\` resolves to the resource output. Models whose resource\n// cannot be resolved statically are left out.\n\nimport \"@warlock.js/core\";\n\ndeclare module \"@warlock.js/core\" {\n interface ModelResourceRegistry {\n${lines.join(\"\\n\")}\n }\n}\n`;\n}\n\n/**\n * Write `content` to `filePath` through a temporary sibling and a rename, so a\n * reader (the editor's TypeScript server) never sees a half-written file, and\n * skip the write entirely when the file already holds exactly this text.\n *\n * @returns `true` when the file was written.\n */\nexport async function writeFileIfChanged(filePath: string, content: string): Promise<boolean> {\n try {\n if ((await readFile(filePath, \"utf-8\")) === content) return false;\n } catch {\n // Missing file: write it.\n }\n\n await mkdir(dirname(filePath), { recursive: true });\n\n const temporaryPath = `${filePath}.${process.pid}.tmp`;\n\n try {\n await writeFile(temporaryPath, content, \"utf-8\");\n await rename(temporaryPath, filePath);\n } catch (error) {\n await rm(temporaryPath, { force: true });\n\n throw error;\n }\n\n return true;\n}\n"],"mappings":";;;;;AAiEA,MAAM,aAAa;AAEnB,SAAS,YAAY,MAAe,MAA8B;CAChE,OAAO,GAAG,iBAAiB,IAAI,MAAM,GAAG,aAAa,IAAI,CAAC,EAAE,MAAM,MAAM,EAAE,SAAS,IAAI,KAAK;AAC9F;AAEA,SAAS,kBAAkB,YAA0C;CACnE,IAAI,UAAU;CAEd,OAAO,GAAG,0BAA0B,OAAO,GACzC,UAAU,QAAQ;CAGpB,OAAO;AACT;;AAGA,SAAS,sBAAsB,YAG7B;CACA,MAAM,2BAAW,IAAI,IAAY;CACjC,MAAM,8BAAc,IAAI,IAAsB;CAE9C,MAAM,aAAa,OAAe,aAA2B;EAC3D,MAAM,QAAQ,YAAY,IAAI,KAAK,KAAK,CAAC;EAEzC,MAAM,KAAK,QAAQ;EACnB,YAAY,IAAI,OAAO,KAAK;CAC9B;CAEA,KAAK,MAAM,aAAa,WAAW,YAAY;EAC7C,MAAM,WAAW,YAAY,WAAW,GAAG,WAAW,aAAa;EACnE,MAAM,YAAY,YAAY,WAAW,GAAG,WAAW,cAAc;EAErE,KACG,GAAG,mBAAmB,SAAS,KAC9B,GAAG,sBAAs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,OAAO,KAAK,UAAU,GAAG,EAAE,aAAa,MAAM,cAAc,SAAS,IAAI;CACtF;CAEA,OAAO;;;;;;;;;EASP,MAAM,KAAK,IAAI,EAAE;;;;AAInB;;;;;;;;AASA,eAAsB,mBAAmB,UAAkB,SAAmC;CAC5F,IAAI;EACF,IAAK,MAAM,SAAS,UAAU,OAAO,MAAO,SAAS,OAAO;CAC9D,QAAQ,CAER;CAEA,MAAM,MAAM,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;CAElD,MAAM,gBAAgB,GAAG,SAAS,GAAG,QAAQ,IAAI;CAEjD,IAAI;EACF,MAAM,UAAU,eAAe,SAAS,OAAO;EAC/C,MAAM,OAAO,eAAe,QAAQ;CACtC,SAAS,OAAO;EACd,MAAM,GAAG,eAAe,EAAE,OAAO,KAAK,CAAC;EAEvC,MAAM;CACR;CAEA,OAAO;AACT"}
|
|
@@ -3,13 +3,15 @@ import { warlockPath } from "../utils/paths.mjs";
|
|
|
3
3
|
import "../utils/index.mjs";
|
|
4
4
|
import { parseLocaleDictionary } from "../localization/parse-locale-dictionary.mjs";
|
|
5
5
|
import "../localization/index.mjs";
|
|
6
|
-
import { devLogError, devLogInfo, devLogSuccess, devServeLog } from "./dev-logger.mjs";
|
|
6
|
+
import { devLogDim, devLogError, devLogInfo, devLogSuccess, devServeLog } from "./dev-logger.mjs";
|
|
7
|
+
import { parseImports } from "./parse-imports.mjs";
|
|
7
8
|
import { getFilesFromDirectory } from "./utils.mjs";
|
|
8
9
|
import { extractTranslationKeys } from "./extract-translation-keys.mjs";
|
|
9
10
|
import { filesOrchestrator } from "./files-orchestrator.mjs";
|
|
10
11
|
import { readConfigAst } from "./read-config-ast.mjs";
|
|
11
12
|
import { runTypingsGeneration } from "./run-typings-generation.mjs";
|
|
12
13
|
import { isModuleLocaleDictionaryPath, isTranslationRegisteringSource } from "./translation-keys-sources.mjs";
|
|
14
|
+
import { extractModelResourceEntries, renderModelResourceRegistry, writeFileIfChanged } from "./model-resource-typings.mjs";
|
|
13
15
|
import { join, resolve } from "path";
|
|
14
16
|
import { ensureDirectoryAsync } from "@warlock.js/fs";
|
|
15
17
|
import { constants } from "fs";
|
|
@@ -58,6 +60,7 @@ var TypeGenerator = class {
|
|
|
58
60
|
this.manifest = null;
|
|
59
61
|
this.configCache = /* @__PURE__ */ new Map();
|
|
60
62
|
this.translationSourceFiles = /* @__PURE__ */ new Set();
|
|
63
|
+
this.modelResourceSourceFiles = /* @__PURE__ */ new Set();
|
|
61
64
|
}
|
|
62
65
|
/**
|
|
63
66
|
* Generate all framework type definitions
|
|
@@ -83,6 +86,7 @@ var TypeGenerator = class {
|
|
|
83
86
|
await this.reconcile();
|
|
84
87
|
}
|
|
85
88
|
await this.generateTranslationTypes();
|
|
89
|
+
await this.generateModelResourceTypes();
|
|
86
90
|
await this.saveManifest();
|
|
87
91
|
}
|
|
88
92
|
/**
|
|
@@ -278,6 +282,42 @@ ${Array.from(keys).sort().map((key) => ` ${JSON.stringify(key)}: true;`).join
|
|
|
278
282
|
await writeFile(join(this.outputDir, "translations.d.ts"), content, "utf-8");
|
|
279
283
|
devLogSuccess(`Generated translation types: ${keys.size} keys`);
|
|
280
284
|
}
|
|
285
|
+
/**
|
|
286
|
+
* Generate `model-resources.d.ts`: the `ModelResourceRegistry` augmentation
|
|
287
|
+
* behind `Serialized<Model>`.
|
|
288
|
+
*
|
|
289
|
+
* Reads every discovered model file (`*.model.ts`) and records the ones that
|
|
290
|
+
* declare `static resource = <Identifier>`. Static AST read only, no app
|
|
291
|
+
* module is imported; see `model-resource-typings.ts` for what is skipped.
|
|
292
|
+
* The file is rewritten only when its text changes.
|
|
293
|
+
*/
|
|
294
|
+
async generateModelResourceTypes() {
|
|
295
|
+
try {
|
|
296
|
+
const entries = [];
|
|
297
|
+
const sourceFiles = /* @__PURE__ */ new Set();
|
|
298
|
+
const skippedModels = [];
|
|
299
|
+
for (const [path, fileManager] of filesOrchestrator.getFiles()) {
|
|
300
|
+
if (fileManager.type !== "model" || !fileManager.source.includes("resource")) continue;
|
|
301
|
+
const imports = await parseImports(fileManager.source, fileManager.absolutePath);
|
|
302
|
+
const extraction = extractModelResourceEntries({
|
|
303
|
+
source: fileManager.source,
|
|
304
|
+
absolutePath: fileManager.absolutePath,
|
|
305
|
+
resolveImport: (specifier) => imports.get(specifier)?.absolutePath
|
|
306
|
+
});
|
|
307
|
+
if (extraction.entries.length > 0) sourceFiles.add(path);
|
|
308
|
+
for (const entry of extraction.entries) {
|
|
309
|
+
entries.push(entry);
|
|
310
|
+
sourceFiles.add(Path.toRelative(entry.resourceFile));
|
|
311
|
+
}
|
|
312
|
+
for (const skipped of extraction.skipped) skippedModels.push(`${skipped.className} (${skipped.reason})`);
|
|
313
|
+
}
|
|
314
|
+
this.modelResourceSourceFiles = sourceFiles;
|
|
315
|
+
if (await writeFileIfChanged(join(this.outputDir, "model-resources.d.ts"), renderModelResourceRegistry(entries, this.outputDir))) devLogSuccess(`Generated model resource types: ${entries.length} models`);
|
|
316
|
+
if (skippedModels.length > 0) devLogDim(`Model resources not typed (not statically resolvable): ${skippedModels.join(", ")}`);
|
|
317
|
+
} catch (error) {
|
|
318
|
+
devServeLog(`⚠️ Failed to generate model resource types: ${error}`);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
281
321
|
isLocalesFile(path) {
|
|
282
322
|
return Path.normalize(path).includes("/utils/locales.");
|
|
283
323
|
}
|
|
@@ -535,12 +575,16 @@ ${allKeys.map((key) => ` "${key}": true;`).join("\n")}
|
|
|
535
575
|
*/
|
|
536
576
|
async executeTypingsGenerator(upcomingFiles) {
|
|
537
577
|
const files = filesOrchestrator.getFiles();
|
|
538
|
-
|
|
578
|
+
const aKnownTranslationSourceVanished = Array.from(this.translationSourceFiles).some((path) => !files.has(path));
|
|
579
|
+
const aKnownModelResourceSourceVanished = Array.from(this.modelResourceSourceFiles).some((path) => !files.has(path));
|
|
580
|
+
if (!(aKnownTranslationSourceVanished || aKnownModelResourceSourceVanished || Array.from(new Set(upcomingFiles)).some((file) => {
|
|
539
581
|
const normalizedPath = Path.normalize(file);
|
|
540
582
|
if (normalizedPath.includes("src/config/")) return true;
|
|
541
583
|
if (isRouteLocalesJsonPath(normalizedPath)) return true;
|
|
542
584
|
if (isModuleLocaleDictionaryPath(normalizedPath)) return true;
|
|
543
585
|
if (this.translationSourceFiles.has(normalizedPath)) return true;
|
|
586
|
+
if (this.modelResourceSourceFiles.has(normalizedPath)) return true;
|
|
587
|
+
if (files.get(normalizedPath)?.type === "model") return true;
|
|
544
588
|
const fileManager = files.get(normalizedPath);
|
|
545
589
|
return fileManager !== void 0 && isTranslationRegisteringSource(normalizedPath, fileManager.source);
|
|
546
590
|
}))) return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type-generator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/type-generator.ts"],"sourcesContent":["import { ensureDirectoryAsync } from \"@warlock.js/fs\";\nimport { constants } from \"fs\";\nimport { access, readFile, writeFile } from \"fs/promises\";\nimport { moduleResolve } from \"import-meta-resolve\";\nimport { join, resolve } from \"path\";\nimport { pathToFileURL } from \"node:url\";\nimport ts from \"typescript\";\nimport { warlockPath } from \"../utils\";\nimport { devLogError, devLogInfo, devLogSuccess, devServeLog } from \"./dev-logger\";\nimport { readConfigAst } from \"./read-config-ast\";\nimport { runTypingsGeneration, type TypingsGenerationPorts } from \"./run-typings-generation\";\nimport { filesOrchestrator } from \"./files-orchestrator\";\nimport { Path } from \"../utils/normalized-path\";\nimport { extractTranslationKeys } from \"./extract-translation-keys\";\nimport {\n isModuleLocaleDictionaryPath,\n isTranslationRegisteringSource,\n} from \"./translation-keys-sources\";\nimport { parseLocaleDictionary } from \"../localization\";\nimport { getFilesFromDirectory } from \"./utils\";\n\ntype RouteLocaleBuildModule = {\n listRouteLocaleKeys?: (options: {\n appRoot?: string;\n }) => readonly string[] | Promise<readonly string[]>;\n};\n\nconst WEB_PACKAGE = \"@warlock.js/web\";\nconst WEB_BUILD_PACKAGE = \"@warlock.js/web/build\";\n\nfunction isAbsentOptionalWebPackage(thrown: unknown): boolean {\n return (\n typeof thrown === \"object\" &&\n thrown !== null &&\n \"code\" in thrown &&\n (thrown as { code?: unknown }).code === \"ERR_MODULE_NOT_FOUND\" &&\n thrown instanceof Error &&\n thrown.message.includes(`Cannot find package '${WEB_PACKAGE}'`)\n );\n}\n\n/** Load the build-only web key lister without creating a core-to-web static edge. */\nexport async function listRouteLocaleKeysForTypeGeneration(\n appRoot = process.cwd(),\n): Promise<readonly string[]> {\n // Published web entries are import-only. Resolve with ESM conditions from\n // the consuming project; require.resolve rejects those installed exports.\n const projectUrl = pathToFileURL(resolve(appRoot, \"package.json\"));\n\n try {\n moduleResolve(WEB_PACKAGE, projectUrl);\n } catch (thrown) {\n if (isAbsentOptionalWebPackage(thrown)) return [];\n throw thrown;\n }\n\n const buildModuleUrl = moduleResolve(WEB_BUILD_PACKAGE, projectUrl);\n const buildModule = (await import(buildModuleUrl.href)) as RouteLocaleBuildModule;\n\n if (typeof buildModule.listRouteLocaleKeys !== \"function\") {\n throw new Error(\n `${WEB_BUILD_PACKAGE} does not export listRouteLocaleKeys. Upgrade @warlock.js/web to a compatible version.`,\n );\n }\n\n return buildModule.listRouteLocaleKeys({ appRoot });\n}\n\n/** True only for the route-locales convention under the canonical web root. */\nexport function isRouteLocalesJsonPath(path: string): boolean {\n const normalized = Path.normalize(path);\n const relativePath = normalized.startsWith(\"src/\") ? normalized : Path.toRelative(normalized);\n return /^src\\/web(?:\\/.*)?\\/locales\\.json$/.test(relativePath);\n}\n\n/**\n * Typings manifest structure for tracking file hashes\n */\ntype TypingsManifest = {\n version: string;\n lastBuildTime: number;\n storage: {\n sourceHash: string;\n drivers: string[];\n } | null;\n config: Record<\n string,\n {\n sourceHash: string;\n typeName: string | null;\n importSource: string | null;\n keys: string[];\n }\n >;\n};\n\n/**\n * TypeGenerator - Generates TypeScript type definitions from config files\n *\n * Parses source config files using the TypeScript Compiler API to extract\n * keys and generate module augmentation types for IDE autocomplete.\n *\n * Uses manifest-based reconciliation to only regenerate when source files change.\n */\nexport class TypeGenerator {\n /**\n * Output directory for generated typings\n */\n private outputDir = warlockPath(\"typings\");\n\n /**\n * Path to typings manifest file\n */\n private manifestPath = join(this.outputDir, \"typings-manifest.json\");\n\n /**\n * Cached manifest data\n */\n private manifest: TypingsManifest | null = null;\n\n /**\n * Cache for config type info and keys\n */\n private configCache = new Map<\n string,\n {\n sourceHash: string;\n typeName: string | null;\n importSource: string | null;\n keys: string[];\n }\n >();\n\n /**\n * Generate all framework type definitions\n *\n * Uses manifest-based reconciliation:\n * - If output files don't exist: full regeneration\n * - If files exist: only regenerate changed configs\n */\n public async generateAll(): Promise<void> {\n await this.ensureOutputDir();\n\n const storageFile = join(this.outputDir, \"storage.d.ts\");\n const configFile = join(this.outputDir, \"config.d.ts\");\n const translationsFile = join(this.outputDir, \"translations.d.ts\");\n\n const [manifestExists, storageExists, configExists, translationsExist] = await Promise.all([\n this.exists(this.manifestPath),\n this.exists(storageFile),\n this.exists(configFile),\n this.exists(translationsFile),\n ]);\n\n if (!manifestExists || !storageExists || !configExists || !translationsExist) {\n // Full regeneration (first run or files deleted)\n await this.fullGeneration();\n } else {\n // Load manifest for hash comparison\n await this.loadManifest();\n // Reconciliation: only regenerate changed files\n await this.reconcile();\n }\n\n await this.generateTranslationTypes();\n\n await this.saveManifest();\n }\n\n /**\n * Full regeneration of all type files\n */\n private async fullGeneration(): Promise<void> {\n // Generate storage types\n const storageConfigPath = await this.findConfigFile(\"storage\");\n if (storageConfigPath) {\n this.generateStorageTypes(storageConfigPath);\n }\n\n // Generate config types\n await this.generateConfigTypes();\n }\n\n /**\n * Reconcile: only regenerate changed files\n */\n private async reconcile(): Promise<void> {\n const files = filesOrchestrator.getFiles();\n let storageChanged = false;\n let configChanged = false;\n let unchangedCount = 0;\n\n this.configCache.clear();\n\n // Check storage config\n for (const [path, fileManager] of files) {\n if (path.startsWith(\"src/config/storage\")) {\n const manifestEntry = this.manifest?.storage;\n if (!manifestEntry || manifestEntry.sourceHash !== fileManager.hash) {\n storageChanged = true;\n await this.generateStorageTypes(path);\n }\n break;\n }\n }\n\n // Check config files\n for (const [path, fileManager] of files) {\n if (!path.startsWith(\"src/config/\")) continue;\n if (\n path\n .split(\"/\")\n .pop()\n ?.replace(/[.][^.]+$/, \"\") === \"index\"\n )\n continue;\n\n // Extract config name (remove dir prefix and extension)\n const configName = path.replace(\"src/config/\", \"\").replace(/\\.[^.]+$/, \"\");\n\n const manifestEntry = this.manifest?.config[configName];\n\n if (!manifestEntry || manifestEntry.sourceHash !== fileManager.hash) {\n // File changed or new - regenerate\n configChanged = true;\n const info = await this.extractConfigInfo(fileManager.absolutePath, configName);\n\n this.configCache.set(configName, {\n sourceHash: fileManager.hash,\n typeName: info.typeName,\n importSource: info.importSource,\n keys: info.keys,\n });\n } else {\n // Unchanged - load from manifest\n unchangedCount++;\n this.configCache.set(configName, manifestEntry);\n }\n }\n\n if (configChanged) {\n await this.writeConfigTypesFromCache();\n } else {\n devLogInfo(`Config types unchanged (${unchangedCount} configs cached)`);\n }\n }\n\n /**\n * Generate storage driver name types\n */\n public async generateStorageTypes(configPath: string): Promise<void> {\n try {\n const driverKeys = await this.extractStorageDriverKeys(configPath);\n\n if (driverKeys.length === 0) {\n devServeLog(\"⚠️ No storage drivers found in config\");\n return;\n }\n\n // Get file hash from filesOrchestrator\n const fileManager = filesOrchestrator.getFiles().get(configPath);\n const sourceHash = fileManager?.hash || \"\";\n\n // Update manifest\n if (!this.manifest) {\n this.manifest = this.createEmptyManifest();\n }\n this.manifest.storage = {\n sourceHash,\n drivers: driverKeys,\n };\n\n const interfaceContent = driverKeys\n .map((k) => ` ${this.toInterfaceKey(k)}: true;`)\n .join(\"\\n\");\n\n const content = `// Auto-generated by Warlock.js - DO NOT EDIT\n// Generated from: ${configPath}\n// Regenerates on dev-server start and when storage config changes\n\nimport \"@warlock.js/core\";\n\ndeclare module \"@warlock.js/core\" {\n interface StorageDriverRegistry {\n${interfaceContent}\n }\n}\n`;\n\n const outputPath = join(this.outputDir, \"storage.d.ts\");\n await writeFile(outputPath, content, \"utf-8\");\n\n devLogSuccess(`Generated storage types: ${driverKeys.join(\", \")}`);\n } catch (error) {\n devServeLog(`⚠️ Failed to generate storage types: ${error}`);\n }\n }\n\n /**\n * Check if a file change should trigger type regeneration\n */\n public shouldRegenerateTypes(changedPath: string): boolean {\n return (\n changedPath.includes(\"src/config/\") ||\n changedPath.includes(\"config/\") ||\n this.isLocalesFile(changedPath) ||\n isRouteLocalesJsonPath(changedPath)\n );\n }\n\n /**\n * Handle file change - uses incremental update via cache\n */\n public async handleFileChange(changedPath: string): Promise<void> {\n if (!this.shouldRegenerateTypes(changedPath)) {\n return;\n }\n\n // Regenerate storage types if storage config changed\n if (changedPath.includes(\"config/storage\")) {\n await this.generateStorageTypes(changedPath);\n await this.saveManifest();\n return;\n }\n\n if (this.isLocalesFile(changedPath) || isRouteLocalesJsonPath(changedPath)) {\n await this.generateTranslationTypes();\n return;\n }\n\n // Extract config name from path\n const match = changedPath.match(/config\\/([^/]+)\\.[^.]+$/);\n if (!match) {\n return;\n }\n\n const configName = match[1];\n if (!configName || configName === \"index\") return;\n\n devLogInfo(`Config changed: ${configName}, updating...`);\n\n // Get file manager for hash\n const fileManager = filesOrchestrator.getFiles().get(changedPath);\n const sourceHash = fileManager?.hash || Date.now().toString();\n\n // Update only the changed config in cache (use optimized combined extraction)\n const configDir = join(process.cwd(), \"src/config\");\n const configPath = join(configDir, `${configName}.ts`);\n\n const info = await this.extractConfigInfo(configPath, configName);\n\n this.configCache.set(configName, {\n sourceHash,\n typeName: info.typeName,\n importSource: info.importSource,\n keys: info.keys,\n });\n\n // Regenerate config.d.ts from cache\n await this.writeConfigTypesFromCache();\n await this.saveManifest();\n }\n\n /**\n * Generate config types - populates cache and writes file\n */\n public async generateConfigTypes(): Promise<void> {\n try {\n const files = filesOrchestrator.getFiles();\n\n // Clear and repopulate cache\n this.configCache.clear();\n\n for (const [path, fileManager] of files) {\n if (!path.startsWith(\"src/config/\")) continue;\n if (\n path\n .split(\"/\")\n .pop()\n ?.replace(/[.][^.]+$/, \"\") === \"index\"\n )\n continue;\n\n // Extract config name\n const configName = path.replace(\"src/config/\", \"\").replace(/\\.[^.]+$/, \"\");\n\n // One parse per config, both extractions off it — see `read-config-ast.ts`.\n const info = await this.extractConfigInfo(fileManager.absolutePath, configName);\n\n this.configCache.set(configName, {\n sourceHash: fileManager.hash,\n typeName: info.typeName,\n importSource: info.importSource,\n keys: info.keys,\n });\n }\n\n await this.writeConfigTypesFromCache();\n } catch (error) {\n devServeLog(`⚠️ Failed to generate config types: ${error}`);\n }\n }\n\n /**\n * Files (relative paths) that contributed to the last generated registry —\n * used to notice a registering file being deleted, since by the time a\n * delete event reaches {@link executeTypingsGenerator} the file is already\n * gone from `filesOrchestrator`'s map and its content can no longer be\n * inspected.\n */\n private translationSourceFiles = new Set<string>();\n\n /**\n * Generate web's app-augmented translation-key registry.\n *\n * Scans every discovered app source file — not only dedicated\n * `utils/locales.*` files — for `groupedTranslations` calls, both the\n * named-group and object forms, at any nesting depth. Dynamic group names,\n * dictionaries, or keys cannot be resolved statically and are skipped; an\n * app relying on those must document them itself.\n */\n private async generateTranslationTypes(): Promise<void> {\n const keys = new Set<string>();\n const sourceFiles = new Set<string>();\n\n for (const [path, fileManager] of filesOrchestrator.getFiles()) {\n if (!isTranslationRegisteringSource(path, fileManager.source)) {\n continue;\n }\n\n sourceFiles.add(path);\n\n if (isModuleLocaleDictionaryPath(path)) {\n const dictionary = parseLocaleDictionary({\n sourceFile: path,\n source: fileManager.source,\n defaultNamespace: path.split(\"/\")[2]!,\n });\n for (const key of Object.keys(dictionary.entries)) {\n keys.add(key);\n }\n continue;\n }\n\n const sourceFile = await readConfigAst(fileManager.absolutePath);\n if (sourceFile) {\n for (const key of extractTranslationKeys(sourceFile)) {\n keys.add(key);\n }\n }\n }\n\n // The dev source map intentionally tracks executable TypeScript only. Module\n // dictionaries are JSON data, so discover them directly without loading app\n // code; use the runtime parser to keep `$group` and flattening identical.\n for (const absolutePath of await getFilesFromDirectory(\n join(process.cwd(), \"src\", \"app\"),\n \"**/utils/locales.json\",\n )) {\n const path = Path.toRelative(absolutePath);\n sourceFiles.add(path);\n const dictionary = parseLocaleDictionary({\n sourceFile: path,\n source: await readFile(absolutePath, \"utf-8\"),\n defaultNamespace: path.split(\"/\")[2]!,\n });\n for (const key of Object.keys(dictionary.entries)) {\n keys.add(key);\n }\n }\n\n for (const key of await listRouteLocaleKeysForTypeGeneration()) {\n keys.add(key);\n }\n\n this.translationSourceFiles = sourceFiles;\n\n const entries = Array.from(keys)\n .sort()\n .map((key) => ` ${JSON.stringify(key)}: true;`)\n .join(\"\\n\");\n const content = `// Auto-generated by Warlock.js - DO NOT EDIT\n// Generated from groupedTranslations calls and route-locales JSON in discovered\n// app source. Dynamic group names/keys cannot be resolved statically and are\n// not included here — document those yourself.\n\nimport \"@warlock.js/web\";\n\ndeclare module \"@warlock.js/web\" {\n interface TranslationKeyRegistry {\n${entries}\n }\n}\n`;\n\n await writeFile(join(this.outputDir, \"translations.d.ts\"), content, \"utf-8\");\n devLogSuccess(`Generated translation types: ${keys.size} keys`);\n }\n\n private isLocalesFile(path: string): boolean {\n return Path.normalize(path).includes(\"/utils/locales.\");\n }\n\n /**\n * Quote an interface key that isn't a valid JS identifier (e.g. a config\n * named `use-cases` or a storage driver `do-spaces`) so the generated\n * `.d.ts` stays syntactically valid. Identifier-safe names are left bare\n * to keep the output clean.\n */\n private toInterfaceKey(name: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);\n }\n\n /**\n * Write config.d.ts from cached data\n */\n private async writeConfigTypesFromCache(): Promise<void> {\n const configTypeInfos: Array<{\n name: string;\n typeName: string | null;\n importSource: string | null;\n }> = [];\n const allKeys: string[] = [];\n\n // Update manifest config section\n if (!this.manifest) {\n this.manifest = this.createEmptyManifest();\n }\n this.manifest.config = {};\n\n for (const [name, data] of this.configCache) {\n configTypeInfos.push({\n name,\n typeName: data.typeName,\n importSource: data.importSource,\n });\n allKeys.push(...data.keys);\n\n // Store in manifest\n this.manifest.config[name] = data;\n }\n\n // Group imports by source\n const imports = new Map<string, Set<string>>();\n for (const info of configTypeInfos) {\n if (info.typeName && info.importSource) {\n if (!imports.has(info.importSource)) {\n imports.set(info.importSource, new Set());\n }\n imports.get(info.importSource)!.add(info.typeName);\n }\n }\n\n const importStatements = Array.from(imports.entries())\n .map(([source, types]) => `import type { ${Array.from(types).join(\", \")} } from \"${source}\";`)\n .join(\"\\n\");\n\n const configEntries = configTypeInfos\n .map((info) => ` ${this.toInterfaceKey(info.name)}: ${info.typeName || \"unknown\"};`)\n .join(\"\\n\");\n\n const keyEntries = allKeys.map((key) => ` \"${key}\": true;`).join(\"\\n\");\n\n const content = `// Auto-generated by Warlock.js - DO NOT EDIT\n// Regenerates on dev-server start and when config files change\n\n${importStatements}\nimport \"@warlock.js/core\";\n\ndeclare module \"@warlock.js/core\" {\n interface ConfigRegistry {\n${configEntries}\n }\n\n interface ConfigKeyRegistry {\n${keyEntries}\n }\n}\n`;\n\n const outputPath = join(this.outputDir, \"config.d.ts\");\n await writeFile(outputPath, content, \"utf-8\");\n\n devLogSuccess(\n `Generated config types: ${this.configCache.size} configs, ${allKeys.length} keys`,\n );\n }\n\n // ============================================================\n // Manifest Management\n // ============================================================\n\n /**\n * Load manifest from disk\n */\n private async loadManifest(): Promise<boolean> {\n try {\n if (await this.exists(this.manifestPath)) {\n const content = await readFile(this.manifestPath, \"utf-8\");\n this.manifest = JSON.parse(content);\n return true;\n }\n } catch {\n // Manifest corrupted or missing\n }\n this.manifest = null;\n return false;\n }\n\n /**\n * Save manifest to disk\n */\n private async saveManifest(): Promise<void> {\n if (!this.manifest) {\n this.manifest = this.createEmptyManifest();\n }\n this.manifest.lastBuildTime = Date.now();\n\n await writeFile(this.manifestPath, JSON.stringify(this.manifest, null, 2), \"utf-8\");\n }\n\n /**\n * Create empty manifest structure\n */\n private createEmptyManifest(): TypingsManifest {\n return {\n version: \"1.0.0\",\n lastBuildTime: Date.now(),\n storage: null,\n config: {},\n };\n }\n\n // ============================================================\n // Type Extraction Methods\n // ============================================================\n\n /**\n * Extract BOTH type info AND keys in a single pass\n *\n * One parse serves both extractions. It used to be one whole TypeScript\n * Program per file — halved from two by an earlier pass, which optimised\n * inside a premise that did not need to hold. `read-config-ast.ts` has the\n * numbers.\n *\n * @param configPath Absolute path to the config file\n * @param configName Config name (e.g., \"auth\", \"notifications\")\n * @returns Combined result with type info and keys\n */\n private async extractConfigInfo(\n configPath: string,\n configName: string,\n ): Promise<{\n typeName: string | null;\n importSource: string | null;\n keys: string[];\n }> {\n if (!(await this.exists(configPath))) {\n return { typeName: null, importSource: null, keys: [] };\n }\n\n // Parse, do not resolve — `read-config-ast.ts` explains why, with numbers.\n const sourceFile = await readConfigAst(configPath);\n\n if (!sourceFile) {\n return { typeName: null, importSource: null, keys: [] };\n }\n\n // === Type Info Extraction ===\n const importedTypes = new Map<string, string>();\n const localExportedTypes = new Set<string>();\n let foundTypeName: string | null = null;\n\n // === Keys Extraction ===\n const keys: string[] = [];\n\n const visitForTypes = (node: ts.Node): void => {\n // Collect imported types\n if (ts.isImportDeclaration(node)) {\n const moduleSpecifier = node.moduleSpecifier;\n if (ts.isStringLiteral(moduleSpecifier)) {\n const source = moduleSpecifier.text;\n const importClause = node.importClause;\n if (importClause?.namedBindings && ts.isNamedImports(importClause.namedBindings)) {\n for (const element of importClause.namedBindings.elements) {\n importedTypes.set(element.name.text, source);\n }\n }\n }\n }\n\n // Collect locally exported types\n if (ts.isTypeAliasDeclaration(node)) {\n const modifiers = ts.getModifiers(node);\n if (modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {\n localExportedTypes.add(node.name.text);\n }\n }\n\n // Collect locally exported interfaces\n if (ts.isInterfaceDeclaration(node)) {\n const modifiers = ts.getModifiers(node);\n if (modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {\n localExportedTypes.add(node.name.text);\n }\n }\n\n // Find type used on config variable + extract keys\n if (ts.isVariableDeclaration(node)) {\n // Type info\n if (node.type && ts.isTypeReferenceNode(node.type)) {\n foundTypeName = node.type.typeName.getText(sourceFile);\n }\n\n // Keys extraction\n if (node.initializer && ts.isObjectLiteralExpression(node.initializer)) {\n const visitKeys = (objNode: ts.ObjectLiteralExpression, prefix: string): void => {\n for (const prop of objNode.properties) {\n if (ts.isPropertyAssignment(prop) && prop.name) {\n const keyName = prop.name.getText(sourceFile);\n const fullKey = prefix ? `${prefix}.${keyName}` : keyName;\n keys.push(fullKey);\n if (ts.isObjectLiteralExpression(prop.initializer)) {\n visitKeys(prop.initializer, fullKey);\n }\n }\n }\n };\n visitKeys(node.initializer, configName);\n }\n }\n\n ts.forEachChild(node, visitForTypes);\n };\n\n ts.forEachChild(sourceFile, visitForTypes);\n\n // Resolve type info\n let typeName: string | null = null;\n let importSource: string | null = null;\n\n if (foundTypeName) {\n if (importedTypes.has(foundTypeName)) {\n typeName = foundTypeName;\n importSource = importedTypes.get(foundTypeName)!;\n } else if (localExportedTypes.has(foundTypeName)) {\n typeName = foundTypeName;\n const relativePath = Path.toRelative(configPath).replace(/\\.(ts|tsx)$/, \"\");\n importSource = `../../${relativePath}`;\n }\n }\n\n return { typeName, importSource, keys };\n }\n\n /**\n * Extract driver keys from storage config\n */\n private async extractStorageDriverKeys(configPath: string): Promise<string[]> {\n const absolutePath = resolve(configPath);\n\n if (!(await this.exists(absolutePath))) {\n devServeLog(`⚠️ Storage config not found: ${absolutePath}`);\n return [];\n }\n\n const sourceFile = await readConfigAst(absolutePath);\n\n if (!sourceFile) {\n devServeLog(`⚠️ Could not parse storage config: ${absolutePath}`);\n return [];\n }\n\n const keys: string[] = [];\n\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAssignment(node)) {\n const propName = node.name.getText(sourceFile);\n\n if (propName === \"drivers\" && ts.isObjectLiteralExpression(node.initializer)) {\n for (const prop of node.initializer.properties) {\n if (ts.isPropertyAssignment(prop) || ts.isShorthandPropertyAssignment(prop)) {\n const keyName = prop.name?.getText(sourceFile);\n\n if (keyName) {\n keys.push(keyName);\n }\n }\n }\n }\n }\n\n ts.forEachChild(node, visit);\n };\n\n ts.forEachChild(sourceFile, visit);\n\n return keys;\n }\n\n /**\n * Find a config file by name\n */\n private async findConfigFile(configName: string): Promise<string | undefined> {\n const possiblePaths = [`src/config/${configName}.ts`, `config/${configName}.ts`];\n\n for (const path of possiblePaths) {\n const fullPath = join(process.cwd(), path);\n\n if (await this.exists(fullPath)) {\n return path;\n }\n }\n\n try {\n const files = filesOrchestrator.getFiles();\n\n for (const [filePath] of files) {\n if (filePath.includes(`config/${configName}`)) {\n return filePath;\n }\n }\n } catch {\n // Files orchestrator not initialized yet\n }\n\n return undefined;\n }\n\n /**\n * Ensure output directory exists\n */\n private async ensureOutputDir(): Promise<void> {\n await ensureDirectoryAsync(this.outputDir);\n }\n\n /**\n * Check if a path exists (async wrapper)\n */\n private async exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * The ports `runTypingsGeneration` needs, bound to this instance and this\n * package's dev logger.\n */\n private get typingsGenerationPorts(): TypingsGenerationPorts {\n return {\n generate: () => this.generateAll(),\n info: (message) => devLogInfo(message),\n success: (message) => devLogSuccess(message),\n error: (message) => devLogError(message),\n };\n }\n\n /**\n * Generate every config's typings.\n *\n * Runs IN THIS PROCESS. It used to spawn `npx warlock generate.typings`,\n * which could not resolve in a source checkout — see\n * `run-typings-generation.ts` for the whole story.\n */\n public async executeGenerateAllCommand(): Promise<void> {\n await runTypingsGeneration(this.typingsGenerationPorts);\n }\n\n /**\n * Regenerate typings after a batch reload — but only when the batch\n * plausibly touched something the typings depend on: a config file, a file\n * that registers translation keys, or a registering file that was deleted.\n *\n * A deleted file is already gone from `filesOrchestrator` by the time this\n * runs (deletes are processed before `dev-server:batch-complete` fires), so\n * its content can't be re-checked here — `translationSourceFiles` is the\n * set from the last generation, kept for exactly this comparison.\n */\n public async executeTypingsGenerator(upcomingFiles: string[]): Promise<void> {\n const files = filesOrchestrator.getFiles();\n\n const aKnownTranslationSourceVanished = Array.from(this.translationSourceFiles).some(\n (path) => !files.has(path),\n );\n\n const touchedAConfig =\n aKnownTranslationSourceVanished ||\n Array.from(new Set(upcomingFiles)).some((file) => {\n const normalizedPath = Path.normalize(file);\n if (normalizedPath.includes(\"src/config/\")) return true;\n if (isRouteLocalesJsonPath(normalizedPath)) return true;\n if (isModuleLocaleDictionaryPath(normalizedPath)) return true;\n if (this.translationSourceFiles.has(normalizedPath)) return true;\n\n const fileManager = files.get(normalizedPath);\n return (\n fileManager !== undefined &&\n isTranslationRegisteringSource(normalizedPath, fileManager.source)\n );\n });\n\n if (!touchedAConfig) return;\n\n /*\n The changed paths are deliberately NOT passed along. The previous version\n built a `files` array here and then threw it away, spawning the same\n whole-project command as the branch above — so \"incremental\" was a name,\n not a behaviour. `generateAll()` reads the orchestrator, which the batch\n reload has already updated, so the full pass is both correct and the only\n pass that ever actually ran.\n */\n await runTypingsGeneration(this.typingsGenerationPorts);\n }\n}\n\n/**\n * Singleton instance for use throughout dev-server\n */\nexport const typeGenerator = new TypeGenerator();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,cAAc;AACpB,MAAM,oBAAoB;AAE1B,SAAS,2BAA2B,QAA0B;CAC5D,OACE,OAAO,WAAW,YAClB,WAAW,QACX,UAAU,UACT,OAA8B,SAAS,0BACxC,kBAAkB,SAClB,OAAO,QAAQ,SAAS,wBAAwB,YAAY,EAAE;AAElE;;AAGA,eAAsB,qCACpB,UAAU,QAAQ,IAAI,GACM;CAG5B,MAAM,aAAa,cAAc,QAAQ,SAAS,cAAc,CAAC;CAEjE,IAAI;EACF,cAAc,aAAa,UAAU;CACvC,SAAS,QAAQ;EACf,IAAI,2BAA2B,MAAM,GAAG,OAAO,CAAC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4BAA2C;EACtD,MAAM,qBAAqB,KAAK,sBAAsB;CACxD;;;;;;;;;;;CAYA,MAAa,wBAAwB,eAAwC;EAC3E,MAAM,QAAQ,kBAAkB,SAAS;EAsBzC,IAAI,EApBoC,MAAM,KAAK,KAAK,sBAAsB,CAAC,CAAC,MAC7E,SAAS,CAAC,MAAM,IAAI,IAAI,CAIK,KAC9B,MAAM,KAAK,IAAI,IAAI,aAAa,CAAC,CAAC,CAAC,MAAM,SAAS;GAChD,MAAM,iBAAiB,KAAK,UAAU,IAAI;GAC1C,IAAI,eAAe,SAAS,aAAa,GAAG,OAAO;GACnD,IAAI,uBAAuB,cAAc,GAAG,OAAO;GACnD,IAAI,6BAA6B,cAAc,GAAG,OAAO;GACzD,IAAI,KAAK,uBAAuB,IAAI,cAAc,GAAG,OAAO;GAE5D,MAAM,cAAc,MAAM,IAAI,cAAc;GAC5C,OACE,gBAAgB,UAChB,+BAA+B,gBAAgB,YAAY,MAAM;EAErE,CAAC,IAEkB;EAUrB,MAAM,qBAAqB,KAAK,sBAAsB;CACxD;AACF;;;;AAKA,MAAa,gBAAgB,IAAI,cAAc"}
|
|
1
|
+
{"version":3,"file":"type-generator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/type-generator.ts"],"sourcesContent":["import { ensureDirectoryAsync } from \"@warlock.js/fs\";\nimport { constants } from \"fs\";\nimport { access, readFile, writeFile } from \"fs/promises\";\nimport { moduleResolve } from \"import-meta-resolve\";\nimport { join, resolve } from \"path\";\nimport { pathToFileURL } from \"node:url\";\nimport ts from \"typescript\";\nimport { warlockPath } from \"../utils\";\nimport { devLogDim, devLogError, devLogInfo, devLogSuccess, devServeLog } from \"./dev-logger\";\nimport { readConfigAst } from \"./read-config-ast\";\nimport { runTypingsGeneration, type TypingsGenerationPorts } from \"./run-typings-generation\";\nimport { filesOrchestrator } from \"./files-orchestrator\";\nimport { Path } from \"../utils/normalized-path\";\nimport { extractTranslationKeys } from \"./extract-translation-keys\";\nimport {\n isModuleLocaleDictionaryPath,\n isTranslationRegisteringSource,\n} from \"./translation-keys-sources\";\nimport { parseLocaleDictionary } from \"../localization\";\nimport { getFilesFromDirectory } from \"./utils\";\nimport {\n extractModelResourceEntries,\n renderModelResourceRegistry,\n writeFileIfChanged,\n type ModelResourceEntry,\n} from \"./model-resource-typings\";\nimport { parseImports } from \"./parse-imports\";\n\ntype RouteLocaleBuildModule = {\n listRouteLocaleKeys?: (options: {\n appRoot?: string;\n }) => readonly string[] | Promise<readonly string[]>;\n};\n\nconst WEB_PACKAGE = \"@warlock.js/web\";\nconst WEB_BUILD_PACKAGE = \"@warlock.js/web/build\";\n\nfunction isAbsentOptionalWebPackage(thrown: unknown): boolean {\n return (\n typeof thrown === \"object\" &&\n thrown !== null &&\n \"code\" in thrown &&\n (thrown as { code?: unknown }).code === \"ERR_MODULE_NOT_FOUND\" &&\n thrown instanceof Error &&\n thrown.message.includes(`Cannot find package '${WEB_PACKAGE}'`)\n );\n}\n\n/** Load the build-only web key lister without creating a core-to-web static edge. */\nexport async function listRouteLocaleKeysForTypeGeneration(\n appRoot = process.cwd(),\n): Promise<readonly string[]> {\n // Published web entries are import-only. Resolve with ESM conditions from\n // the consuming project; require.resolve rejects those installed exports.\n const projectUrl = pathToFileURL(resolve(appRoot, \"package.json\"));\n\n try {\n moduleResolve(WEB_PACKAGE, projectUrl);\n } catch (thrown) {\n if (isAbsentOptionalWebPackage(thrown)) return [];\n throw thrown;\n }\n\n const buildModuleUrl = moduleResolve(WEB_BUILD_PACKAGE, projectUrl);\n const buildModule = (await import(buildModuleUrl.href)) as RouteLocaleBuildModule;\n\n if (typeof buildModule.listRouteLocaleKeys !== \"function\") {\n throw new Error(\n `${WEB_BUILD_PACKAGE} does not export listRouteLocaleKeys. Upgrade @warlock.js/web to a compatible version.`,\n );\n }\n\n return buildModule.listRouteLocaleKeys({ appRoot });\n}\n\n/** True only for the route-locales convention under the canonical web root. */\nexport function isRouteLocalesJsonPath(path: string): boolean {\n const normalized = Path.normalize(path);\n const relativePath = normalized.startsWith(\"src/\") ? normalized : Path.toRelative(normalized);\n return /^src\\/web(?:\\/.*)?\\/locales\\.json$/.test(relativePath);\n}\n\n/**\n * Typings manifest structure for tracking file hashes\n */\ntype TypingsManifest = {\n version: string;\n lastBuildTime: number;\n storage: {\n sourceHash: string;\n drivers: string[];\n } | null;\n config: Record<\n string,\n {\n sourceHash: string;\n typeName: string | null;\n importSource: string | null;\n keys: string[];\n }\n >;\n};\n\n/**\n * TypeGenerator - Generates TypeScript type definitions from config files\n *\n * Parses source config files using the TypeScript Compiler API to extract\n * keys and generate module augmentation types for IDE autocomplete.\n *\n * Uses manifest-based reconciliation to only regenerate when source files change.\n */\nexport class TypeGenerator {\n /**\n * Output directory for generated typings\n */\n private outputDir = warlockPath(\"typings\");\n\n /**\n * Path to typings manifest file\n */\n private manifestPath = join(this.outputDir, \"typings-manifest.json\");\n\n /**\n * Cached manifest data\n */\n private manifest: TypingsManifest | null = null;\n\n /**\n * Cache for config type info and keys\n */\n private configCache = new Map<\n string,\n {\n sourceHash: string;\n typeName: string | null;\n importSource: string | null;\n keys: string[];\n }\n >();\n\n /**\n * Generate all framework type definitions\n *\n * Uses manifest-based reconciliation:\n * - If output files don't exist: full regeneration\n * - If files exist: only regenerate changed configs\n */\n public async generateAll(): Promise<void> {\n await this.ensureOutputDir();\n\n const storageFile = join(this.outputDir, \"storage.d.ts\");\n const configFile = join(this.outputDir, \"config.d.ts\");\n const translationsFile = join(this.outputDir, \"translations.d.ts\");\n\n const [manifestExists, storageExists, configExists, translationsExist] = await Promise.all([\n this.exists(this.manifestPath),\n this.exists(storageFile),\n this.exists(configFile),\n this.exists(translationsFile),\n ]);\n\n if (!manifestExists || !storageExists || !configExists || !translationsExist) {\n // Full regeneration (first run or files deleted)\n await this.fullGeneration();\n } else {\n // Load manifest for hash comparison\n await this.loadManifest();\n // Reconciliation: only regenerate changed files\n await this.reconcile();\n }\n\n await this.generateTranslationTypes();\n await this.generateModelResourceTypes();\n\n await this.saveManifest();\n }\n\n /**\n * Full regeneration of all type files\n */\n private async fullGeneration(): Promise<void> {\n // Generate storage types\n const storageConfigPath = await this.findConfigFile(\"storage\");\n if (storageConfigPath) {\n this.generateStorageTypes(storageConfigPath);\n }\n\n // Generate config types\n await this.generateConfigTypes();\n }\n\n /**\n * Reconcile: only regenerate changed files\n */\n private async reconcile(): Promise<void> {\n const files = filesOrchestrator.getFiles();\n let storageChanged = false;\n let configChanged = false;\n let unchangedCount = 0;\n\n this.configCache.clear();\n\n // Check storage config\n for (const [path, fileManager] of files) {\n if (path.startsWith(\"src/config/storage\")) {\n const manifestEntry = this.manifest?.storage;\n if (!manifestEntry || manifestEntry.sourceHash !== fileManager.hash) {\n storageChanged = true;\n await this.generateStorageTypes(path);\n }\n break;\n }\n }\n\n // Check config files\n for (const [path, fileManager] of files) {\n if (!path.startsWith(\"src/config/\")) continue;\n if (\n path\n .split(\"/\")\n .pop()\n ?.replace(/[.][^.]+$/, \"\") === \"index\"\n )\n continue;\n\n // Extract config name (remove dir prefix and extension)\n const configName = path.replace(\"src/config/\", \"\").replace(/\\.[^.]+$/, \"\");\n\n const manifestEntry = this.manifest?.config[configName];\n\n if (!manifestEntry || manifestEntry.sourceHash !== fileManager.hash) {\n // File changed or new - regenerate\n configChanged = true;\n const info = await this.extractConfigInfo(fileManager.absolutePath, configName);\n\n this.configCache.set(configName, {\n sourceHash: fileManager.hash,\n typeName: info.typeName,\n importSource: info.importSource,\n keys: info.keys,\n });\n } else {\n // Unchanged - load from manifest\n unchangedCount++;\n this.configCache.set(configName, manifestEntry);\n }\n }\n\n if (configChanged) {\n await this.writeConfigTypesFromCache();\n } else {\n devLogInfo(`Config types unchanged (${unchangedCount} configs cached)`);\n }\n }\n\n /**\n * Generate storage driver name types\n */\n public async generateStorageTypes(configPath: string): Promise<void> {\n try {\n const driverKeys = await this.extractStorageDriverKeys(configPath);\n\n if (driverKeys.length === 0) {\n devServeLog(\"⚠️ No storage drivers found in config\");\n return;\n }\n\n // Get file hash from filesOrchestrator\n const fileManager = filesOrchestrator.getFiles().get(configPath);\n const sourceHash = fileManager?.hash || \"\";\n\n // Update manifest\n if (!this.manifest) {\n this.manifest = this.createEmptyManifest();\n }\n this.manifest.storage = {\n sourceHash,\n drivers: driverKeys,\n };\n\n const interfaceContent = driverKeys\n .map((k) => ` ${this.toInterfaceKey(k)}: true;`)\n .join(\"\\n\");\n\n const content = `// Auto-generated by Warlock.js - DO NOT EDIT\n// Generated from: ${configPath}\n// Regenerates on dev-server start and when storage config changes\n\nimport \"@warlock.js/core\";\n\ndeclare module \"@warlock.js/core\" {\n interface StorageDriverRegistry {\n${interfaceContent}\n }\n}\n`;\n\n const outputPath = join(this.outputDir, \"storage.d.ts\");\n await writeFile(outputPath, content, \"utf-8\");\n\n devLogSuccess(`Generated storage types: ${driverKeys.join(\", \")}`);\n } catch (error) {\n devServeLog(`⚠️ Failed to generate storage types: ${error}`);\n }\n }\n\n /**\n * Check if a file change should trigger type regeneration\n */\n public shouldRegenerateTypes(changedPath: string): boolean {\n return (\n changedPath.includes(\"src/config/\") ||\n changedPath.includes(\"config/\") ||\n this.isLocalesFile(changedPath) ||\n isRouteLocalesJsonPath(changedPath)\n );\n }\n\n /**\n * Handle file change - uses incremental update via cache\n */\n public async handleFileChange(changedPath: string): Promise<void> {\n if (!this.shouldRegenerateTypes(changedPath)) {\n return;\n }\n\n // Regenerate storage types if storage config changed\n if (changedPath.includes(\"config/storage\")) {\n await this.generateStorageTypes(changedPath);\n await this.saveManifest();\n return;\n }\n\n if (this.isLocalesFile(changedPath) || isRouteLocalesJsonPath(changedPath)) {\n await this.generateTranslationTypes();\n return;\n }\n\n // Extract config name from path\n const match = changedPath.match(/config\\/([^/]+)\\.[^.]+$/);\n if (!match) {\n return;\n }\n\n const configName = match[1];\n if (!configName || configName === \"index\") return;\n\n devLogInfo(`Config changed: ${configName}, updating...`);\n\n // Get file manager for hash\n const fileManager = filesOrchestrator.getFiles().get(changedPath);\n const sourceHash = fileManager?.hash || Date.now().toString();\n\n // Update only the changed config in cache (use optimized combined extraction)\n const configDir = join(process.cwd(), \"src/config\");\n const configPath = join(configDir, `${configName}.ts`);\n\n const info = await this.extractConfigInfo(configPath, configName);\n\n this.configCache.set(configName, {\n sourceHash,\n typeName: info.typeName,\n importSource: info.importSource,\n keys: info.keys,\n });\n\n // Regenerate config.d.ts from cache\n await this.writeConfigTypesFromCache();\n await this.saveManifest();\n }\n\n /**\n * Generate config types - populates cache and writes file\n */\n public async generateConfigTypes(): Promise<void> {\n try {\n const files = filesOrchestrator.getFiles();\n\n // Clear and repopulate cache\n this.configCache.clear();\n\n for (const [path, fileManager] of files) {\n if (!path.startsWith(\"src/config/\")) continue;\n if (\n path\n .split(\"/\")\n .pop()\n ?.replace(/[.][^.]+$/, \"\") === \"index\"\n )\n continue;\n\n // Extract config name\n const configName = path.replace(\"src/config/\", \"\").replace(/\\.[^.]+$/, \"\");\n\n // One parse per config, both extractions off it — see `read-config-ast.ts`.\n const info = await this.extractConfigInfo(fileManager.absolutePath, configName);\n\n this.configCache.set(configName, {\n sourceHash: fileManager.hash,\n typeName: info.typeName,\n importSource: info.importSource,\n keys: info.keys,\n });\n }\n\n await this.writeConfigTypesFromCache();\n } catch (error) {\n devServeLog(`⚠️ Failed to generate config types: ${error}`);\n }\n }\n\n /**\n * Files (relative paths) that contributed to the last generated registry —\n * used to notice a registering file being deleted, since by the time a\n * delete event reaches {@link executeTypingsGenerator} the file is already\n * gone from `filesOrchestrator`'s map and its content can no longer be\n * inspected.\n */\n private translationSourceFiles = new Set<string>();\n\n /**\n * Generate web's app-augmented translation-key registry.\n *\n * Scans every discovered app source file — not only dedicated\n * `utils/locales.*` files — for `groupedTranslations` calls, both the\n * named-group and object forms, at any nesting depth. Dynamic group names,\n * dictionaries, or keys cannot be resolved statically and are skipped; an\n * app relying on those must document them itself.\n */\n private async generateTranslationTypes(): Promise<void> {\n const keys = new Set<string>();\n const sourceFiles = new Set<string>();\n\n for (const [path, fileManager] of filesOrchestrator.getFiles()) {\n if (!isTranslationRegisteringSource(path, fileManager.source)) {\n continue;\n }\n\n sourceFiles.add(path);\n\n if (isModuleLocaleDictionaryPath(path)) {\n const dictionary = parseLocaleDictionary({\n sourceFile: path,\n source: fileManager.source,\n defaultNamespace: path.split(\"/\")[2]!,\n });\n for (const key of Object.keys(dictionary.entries)) {\n keys.add(key);\n }\n continue;\n }\n\n const sourceFile = await readConfigAst(fileManager.absolutePath);\n if (sourceFile) {\n for (const key of extractTranslationKeys(sourceFile)) {\n keys.add(key);\n }\n }\n }\n\n // The dev source map intentionally tracks executable TypeScript only. Module\n // dictionaries are JSON data, so discover them directly without loading app\n // code; use the runtime parser to keep `$group` and flattening identical.\n for (const absolutePath of await getFilesFromDirectory(\n join(process.cwd(), \"src\", \"app\"),\n \"**/utils/locales.json\",\n )) {\n const path = Path.toRelative(absolutePath);\n sourceFiles.add(path);\n const dictionary = parseLocaleDictionary({\n sourceFile: path,\n source: await readFile(absolutePath, \"utf-8\"),\n defaultNamespace: path.split(\"/\")[2]!,\n });\n for (const key of Object.keys(dictionary.entries)) {\n keys.add(key);\n }\n }\n\n for (const key of await listRouteLocaleKeysForTypeGeneration()) {\n keys.add(key);\n }\n\n this.translationSourceFiles = sourceFiles;\n\n const entries = Array.from(keys)\n .sort()\n .map((key) => ` ${JSON.stringify(key)}: true;`)\n .join(\"\\n\");\n const content = `// Auto-generated by Warlock.js - DO NOT EDIT\n// Generated from groupedTranslations calls and route-locales JSON in discovered\n// app source. Dynamic group names/keys cannot be resolved statically and are\n// not included here — document those yourself.\n\nimport \"@warlock.js/web\";\n\ndeclare module \"@warlock.js/web\" {\n interface TranslationKeyRegistry {\n${entries}\n }\n}\n`;\n\n await writeFile(join(this.outputDir, \"translations.d.ts\"), content, \"utf-8\");\n devLogSuccess(`Generated translation types: ${keys.size} keys`);\n }\n\n /**\n * Files that contributed to the last `model-resources.d.ts`: the model files\n * and the modules their resources were resolved to. Kept for the same reason\n * as {@link translationSourceFiles}: a deleted file is already gone from the\n * orchestrator when the batch reaches {@link executeTypingsGenerator}.\n */\n private modelResourceSourceFiles = new Set<string>();\n\n /**\n * Generate `model-resources.d.ts`: the `ModelResourceRegistry` augmentation\n * behind `Serialized<Model>`.\n *\n * Reads every discovered model file (`*.model.ts`) and records the ones that\n * declare `static resource = <Identifier>`. Static AST read only, no app\n * module is imported; see `model-resource-typings.ts` for what is skipped.\n * The file is rewritten only when its text changes.\n */\n private async generateModelResourceTypes(): Promise<void> {\n try {\n const entries: ModelResourceEntry[] = [];\n const sourceFiles = new Set<string>();\n const skippedModels: string[] = [];\n\n for (const [path, fileManager] of filesOrchestrator.getFiles()) {\n if (fileManager.type !== \"model\" || !fileManager.source.includes(\"resource\")) continue;\n\n const imports = await parseImports(fileManager.source, fileManager.absolutePath);\n const extraction = extractModelResourceEntries({\n source: fileManager.source,\n absolutePath: fileManager.absolutePath,\n resolveImport: (specifier) => imports.get(specifier)?.absolutePath,\n });\n\n if (extraction.entries.length > 0) sourceFiles.add(path);\n\n for (const entry of extraction.entries) {\n entries.push(entry);\n sourceFiles.add(Path.toRelative(entry.resourceFile));\n }\n\n for (const skipped of extraction.skipped) {\n skippedModels.push(`${skipped.className} (${skipped.reason})`);\n }\n }\n\n this.modelResourceSourceFiles = sourceFiles;\n\n const written = await writeFileIfChanged(\n join(this.outputDir, \"model-resources.d.ts\"),\n renderModelResourceRegistry(entries, this.outputDir),\n );\n\n if (written) devLogSuccess(`Generated model resource types: ${entries.length} models`);\n\n if (skippedModels.length > 0) {\n devLogDim(\n `Model resources not typed (not statically resolvable): ${skippedModels.join(\", \")}`,\n );\n }\n } catch (error) {\n devServeLog(`⚠️ Failed to generate model resource types: ${error}`);\n }\n }\n\n private isLocalesFile(path: string): boolean {\n return Path.normalize(path).includes(\"/utils/locales.\");\n }\n\n /**\n * Quote an interface key that isn't a valid JS identifier (e.g. a config\n * named `use-cases` or a storage driver `do-spaces`) so the generated\n * `.d.ts` stays syntactically valid. Identifier-safe names are left bare\n * to keep the output clean.\n */\n private toInterfaceKey(name: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);\n }\n\n /**\n * Write config.d.ts from cached data\n */\n private async writeConfigTypesFromCache(): Promise<void> {\n const configTypeInfos: Array<{\n name: string;\n typeName: string | null;\n importSource: string | null;\n }> = [];\n const allKeys: string[] = [];\n\n // Update manifest config section\n if (!this.manifest) {\n this.manifest = this.createEmptyManifest();\n }\n this.manifest.config = {};\n\n for (const [name, data] of this.configCache) {\n configTypeInfos.push({\n name,\n typeName: data.typeName,\n importSource: data.importSource,\n });\n allKeys.push(...data.keys);\n\n // Store in manifest\n this.manifest.config[name] = data;\n }\n\n // Group imports by source\n const imports = new Map<string, Set<string>>();\n for (const info of configTypeInfos) {\n if (info.typeName && info.importSource) {\n if (!imports.has(info.importSource)) {\n imports.set(info.importSource, new Set());\n }\n imports.get(info.importSource)!.add(info.typeName);\n }\n }\n\n const importStatements = Array.from(imports.entries())\n .map(([source, types]) => `import type { ${Array.from(types).join(\", \")} } from \"${source}\";`)\n .join(\"\\n\");\n\n const configEntries = configTypeInfos\n .map((info) => ` ${this.toInterfaceKey(info.name)}: ${info.typeName || \"unknown\"};`)\n .join(\"\\n\");\n\n const keyEntries = allKeys.map((key) => ` \"${key}\": true;`).join(\"\\n\");\n\n const content = `// Auto-generated by Warlock.js - DO NOT EDIT\n// Regenerates on dev-server start and when config files change\n\n${importStatements}\nimport \"@warlock.js/core\";\n\ndeclare module \"@warlock.js/core\" {\n interface ConfigRegistry {\n${configEntries}\n }\n\n interface ConfigKeyRegistry {\n${keyEntries}\n }\n}\n`;\n\n const outputPath = join(this.outputDir, \"config.d.ts\");\n await writeFile(outputPath, content, \"utf-8\");\n\n devLogSuccess(\n `Generated config types: ${this.configCache.size} configs, ${allKeys.length} keys`,\n );\n }\n\n // ============================================================\n // Manifest Management\n // ============================================================\n\n /**\n * Load manifest from disk\n */\n private async loadManifest(): Promise<boolean> {\n try {\n if (await this.exists(this.manifestPath)) {\n const content = await readFile(this.manifestPath, \"utf-8\");\n this.manifest = JSON.parse(content);\n return true;\n }\n } catch {\n // Manifest corrupted or missing\n }\n this.manifest = null;\n return false;\n }\n\n /**\n * Save manifest to disk\n */\n private async saveManifest(): Promise<void> {\n if (!this.manifest) {\n this.manifest = this.createEmptyManifest();\n }\n this.manifest.lastBuildTime = Date.now();\n\n await writeFile(this.manifestPath, JSON.stringify(this.manifest, null, 2), \"utf-8\");\n }\n\n /**\n * Create empty manifest structure\n */\n private createEmptyManifest(): TypingsManifest {\n return {\n version: \"1.0.0\",\n lastBuildTime: Date.now(),\n storage: null,\n config: {},\n };\n }\n\n // ============================================================\n // Type Extraction Methods\n // ============================================================\n\n /**\n * Extract BOTH type info AND keys in a single pass\n *\n * One parse serves both extractions. It used to be one whole TypeScript\n * Program per file — halved from two by an earlier pass, which optimised\n * inside a premise that did not need to hold. `read-config-ast.ts` has the\n * numbers.\n *\n * @param configPath Absolute path to the config file\n * @param configName Config name (e.g., \"auth\", \"notifications\")\n * @returns Combined result with type info and keys\n */\n private async extractConfigInfo(\n configPath: string,\n configName: string,\n ): Promise<{\n typeName: string | null;\n importSource: string | null;\n keys: string[];\n }> {\n if (!(await this.exists(configPath))) {\n return { typeName: null, importSource: null, keys: [] };\n }\n\n // Parse, do not resolve — `read-config-ast.ts` explains why, with numbers.\n const sourceFile = await readConfigAst(configPath);\n\n if (!sourceFile) {\n return { typeName: null, importSource: null, keys: [] };\n }\n\n // === Type Info Extraction ===\n const importedTypes = new Map<string, string>();\n const localExportedTypes = new Set<string>();\n let foundTypeName: string | null = null;\n\n // === Keys Extraction ===\n const keys: string[] = [];\n\n const visitForTypes = (node: ts.Node): void => {\n // Collect imported types\n if (ts.isImportDeclaration(node)) {\n const moduleSpecifier = node.moduleSpecifier;\n if (ts.isStringLiteral(moduleSpecifier)) {\n const source = moduleSpecifier.text;\n const importClause = node.importClause;\n if (importClause?.namedBindings && ts.isNamedImports(importClause.namedBindings)) {\n for (const element of importClause.namedBindings.elements) {\n importedTypes.set(element.name.text, source);\n }\n }\n }\n }\n\n // Collect locally exported types\n if (ts.isTypeAliasDeclaration(node)) {\n const modifiers = ts.getModifiers(node);\n if (modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {\n localExportedTypes.add(node.name.text);\n }\n }\n\n // Collect locally exported interfaces\n if (ts.isInterfaceDeclaration(node)) {\n const modifiers = ts.getModifiers(node);\n if (modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {\n localExportedTypes.add(node.name.text);\n }\n }\n\n // Find type used on config variable + extract keys\n if (ts.isVariableDeclaration(node)) {\n // Type info\n if (node.type && ts.isTypeReferenceNode(node.type)) {\n foundTypeName = node.type.typeName.getText(sourceFile);\n }\n\n // Keys extraction\n if (node.initializer && ts.isObjectLiteralExpression(node.initializer)) {\n const visitKeys = (objNode: ts.ObjectLiteralExpression, prefix: string): void => {\n for (const prop of objNode.properties) {\n if (ts.isPropertyAssignment(prop) && prop.name) {\n const keyName = prop.name.getText(sourceFile);\n const fullKey = prefix ? `${prefix}.${keyName}` : keyName;\n keys.push(fullKey);\n if (ts.isObjectLiteralExpression(prop.initializer)) {\n visitKeys(prop.initializer, fullKey);\n }\n }\n }\n };\n visitKeys(node.initializer, configName);\n }\n }\n\n ts.forEachChild(node, visitForTypes);\n };\n\n ts.forEachChild(sourceFile, visitForTypes);\n\n // Resolve type info\n let typeName: string | null = null;\n let importSource: string | null = null;\n\n if (foundTypeName) {\n if (importedTypes.has(foundTypeName)) {\n typeName = foundTypeName;\n importSource = importedTypes.get(foundTypeName)!;\n } else if (localExportedTypes.has(foundTypeName)) {\n typeName = foundTypeName;\n const relativePath = Path.toRelative(configPath).replace(/\\.(ts|tsx)$/, \"\");\n importSource = `../../${relativePath}`;\n }\n }\n\n return { typeName, importSource, keys };\n }\n\n /**\n * Extract driver keys from storage config\n */\n private async extractStorageDriverKeys(configPath: string): Promise<string[]> {\n const absolutePath = resolve(configPath);\n\n if (!(await this.exists(absolutePath))) {\n devServeLog(`⚠️ Storage config not found: ${absolutePath}`);\n return [];\n }\n\n const sourceFile = await readConfigAst(absolutePath);\n\n if (!sourceFile) {\n devServeLog(`⚠️ Could not parse storage config: ${absolutePath}`);\n return [];\n }\n\n const keys: string[] = [];\n\n const visit = (node: ts.Node): void => {\n if (ts.isPropertyAssignment(node)) {\n const propName = node.name.getText(sourceFile);\n\n if (propName === \"drivers\" && ts.isObjectLiteralExpression(node.initializer)) {\n for (const prop of node.initializer.properties) {\n if (ts.isPropertyAssignment(prop) || ts.isShorthandPropertyAssignment(prop)) {\n const keyName = prop.name?.getText(sourceFile);\n\n if (keyName) {\n keys.push(keyName);\n }\n }\n }\n }\n }\n\n ts.forEachChild(node, visit);\n };\n\n ts.forEachChild(sourceFile, visit);\n\n return keys;\n }\n\n /**\n * Find a config file by name\n */\n private async findConfigFile(configName: string): Promise<string | undefined> {\n const possiblePaths = [`src/config/${configName}.ts`, `config/${configName}.ts`];\n\n for (const path of possiblePaths) {\n const fullPath = join(process.cwd(), path);\n\n if (await this.exists(fullPath)) {\n return path;\n }\n }\n\n try {\n const files = filesOrchestrator.getFiles();\n\n for (const [filePath] of files) {\n if (filePath.includes(`config/${configName}`)) {\n return filePath;\n }\n }\n } catch {\n // Files orchestrator not initialized yet\n }\n\n return undefined;\n }\n\n /**\n * Ensure output directory exists\n */\n private async ensureOutputDir(): Promise<void> {\n await ensureDirectoryAsync(this.outputDir);\n }\n\n /**\n * Check if a path exists (async wrapper)\n */\n private async exists(path: string): Promise<boolean> {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * The ports `runTypingsGeneration` needs, bound to this instance and this\n * package's dev logger.\n */\n private get typingsGenerationPorts(): TypingsGenerationPorts {\n return {\n generate: () => this.generateAll(),\n info: (message) => devLogInfo(message),\n success: (message) => devLogSuccess(message),\n error: (message) => devLogError(message),\n };\n }\n\n /**\n * Generate every config's typings.\n *\n * Runs IN THIS PROCESS. It used to spawn `npx warlock generate.typings`,\n * which could not resolve in a source checkout — see\n * `run-typings-generation.ts` for the whole story.\n */\n public async executeGenerateAllCommand(): Promise<void> {\n await runTypingsGeneration(this.typingsGenerationPorts);\n }\n\n /**\n * Regenerate typings after a batch reload — but only when the batch\n * plausibly touched something the typings depend on: a config file, a file\n * that registers translation keys, or a registering file that was deleted.\n *\n * A deleted file is already gone from `filesOrchestrator` by the time this\n * runs (deletes are processed before `dev-server:batch-complete` fires), so\n * its content can't be re-checked here — `translationSourceFiles` is the\n * set from the last generation, kept for exactly this comparison.\n */\n public async executeTypingsGenerator(upcomingFiles: string[]): Promise<void> {\n const files = filesOrchestrator.getFiles();\n\n const aKnownTranslationSourceVanished = Array.from(this.translationSourceFiles).some(\n (path) => !files.has(path),\n );\n\n const aKnownModelResourceSourceVanished = Array.from(this.modelResourceSourceFiles).some(\n (path) => !files.has(path),\n );\n\n const touchedAConfig =\n aKnownTranslationSourceVanished ||\n aKnownModelResourceSourceVanished ||\n Array.from(new Set(upcomingFiles)).some((file) => {\n const normalizedPath = Path.normalize(file);\n if (normalizedPath.includes(\"src/config/\")) return true;\n if (isRouteLocalesJsonPath(normalizedPath)) return true;\n if (isModuleLocaleDictionaryPath(normalizedPath)) return true;\n if (this.translationSourceFiles.has(normalizedPath)) return true;\n if (this.modelResourceSourceFiles.has(normalizedPath)) return true;\n if (files.get(normalizedPath)?.type === \"model\") return true;\n\n const fileManager = files.get(normalizedPath);\n return (\n fileManager !== undefined &&\n isTranslationRegisteringSource(normalizedPath, fileManager.source)\n );\n });\n\n if (!touchedAConfig) return;\n\n /*\n The changed paths are deliberately NOT passed along. The previous version\n built a `files` array here and then threw it away, spawning the same\n whole-project command as the branch above — so \"incremental\" was a name,\n not a behaviour. `generateAll()` reads the orchestrator, which the batch\n reload has already updated, so the full pass is both correct and the only\n pass that ever actually ran.\n */\n await runTypingsGeneration(this.typingsGenerationPorts);\n }\n}\n\n/**\n * Singleton instance for use throughout dev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CHANGED
|
@@ -42,4 +42,5 @@ import { HttpServerRebuiltListener, notifyHttpServerRebuilt, onHttpServerRebuilt
|
|
|
42
42
|
import { deriveTraceId, parseTraceparentTraceId } from "./tracing/trace-id.mjs";
|
|
43
43
|
import { TracingContextSource, buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, registerTracingHooks, resetTracingConfigForTests, resolveTracingConfig } from "./tracing/tracing-dispatcher.mjs";
|
|
44
44
|
import { RequestContextStore, requestContext, useCurrentUser, useRequest, useRequestStore } from "./context/request-context.mjs";
|
|
45
|
-
import { requestMemo } from "./context/request-memo.mjs";
|
|
45
|
+
import { requestMemo } from "./context/request-memo.mjs";
|
|
46
|
+
import { ModelResourceRegistry, Serialized, SerializedWire } from "./serialized.mjs";
|
package/esm/http/request.d.mts
CHANGED
|
@@ -385,14 +385,14 @@ declare class Request<RequestValidation = any> {
|
|
|
385
385
|
* @internal Framework orchestration — do not call from app code. Wired
|
|
386
386
|
* from the Fastify route handler in `router.scan()`.
|
|
387
387
|
*/
|
|
388
|
-
execute(): Promise<any[] | Record<string, any
|
|
388
|
+
execute(): Promise<any[] | Response | Record<string, any>>;
|
|
389
389
|
/**
|
|
390
390
|
* Iterate the collected middlewares in order; return the first short-circuit
|
|
391
391
|
* value or `undefined` when every middleware passes through.
|
|
392
392
|
*
|
|
393
393
|
* @internal Framework orchestration — do not call from app code.
|
|
394
394
|
*/
|
|
395
|
-
protected executeMiddleware(): Promise<any[] | Record<string, any> |
|
|
395
|
+
protected executeMiddleware(): Promise<any[] | Response | Record<string, any> | undefined>;
|
|
396
396
|
/**
|
|
397
397
|
* Gather the middleware list for the current route — today just the
|
|
398
398
|
* route-level array; future extraction may merge group + app-wide layers.
|