@loculus/infer 0.0.0 → 0.1.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 +17 -0
- package/README.md +11 -3
- package/dist/cli.d.ts +1 -3
- package/dist/cli.js +2 -3
- package/dist/generate-B66c6Tig.js +808 -0
- package/dist/index.d.ts +2 -6
- package/dist/index.js +1 -1
- package/package.json +6 -5
- package/dist/generate-ncDNvye5.js +0 -672
|
@@ -0,0 +1,808 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
|
+
import * as ts from "typescript/ast";
|
|
4
|
+
import { API, CheckFlags, ElementFlags, NodeBuilderFlags, SymbolFlags, TypeFlags, formatDiagnostics } from "typescript/sync";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { glob } from "glob";
|
|
7
|
+
import { minimatch } from "minimatch";
|
|
8
|
+
// src/descriptions.ts
|
|
9
|
+
const wrappers = /* @__PURE__ */ new Set([
|
|
10
|
+
"transform",
|
|
11
|
+
"refine",
|
|
12
|
+
"unflatten"
|
|
13
|
+
]);
|
|
14
|
+
function readDescriptions(expression, checker, seen = /* @__PURE__ */ new Set()) {
|
|
15
|
+
const node = expression && unwrap(expression);
|
|
16
|
+
if (!node || seen.has(node)) return {};
|
|
17
|
+
seen.add(node);
|
|
18
|
+
if (ts.isIdentifier(node)) {
|
|
19
|
+
let symbol = checker.getSymbolAtLocation(node);
|
|
20
|
+
if (symbol?.flags && symbol.flags & SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
|
|
21
|
+
const declaration = symbol?.valueDeclaration?.resolve();
|
|
22
|
+
return declaration && ts.isVariableDeclaration(declaration) ? readDescriptions(declaration.initializer, checker, seen) : {};
|
|
23
|
+
}
|
|
24
|
+
if (!ts.isCallExpression(node)) return {};
|
|
25
|
+
const callee = node.expression;
|
|
26
|
+
const name = ts.isPropertyAccessExpression(callee) ? callee.name.text : ts.isIdentifier(callee) ? callee.text : "";
|
|
27
|
+
const args = node.arguments ?? [];
|
|
28
|
+
if (wrappers.has(name)) {
|
|
29
|
+
const inner = readDescriptions(args[0], checker, seen);
|
|
30
|
+
const options = name === "unflatten" ? void 0 : readOwnDescription(args.slice(1));
|
|
31
|
+
return {
|
|
32
|
+
...inner,
|
|
33
|
+
...options === void 0 ? {} : { description: options },
|
|
34
|
+
...name === "unflatten" ? { inputOnlyFields: true } : {}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const tree = {};
|
|
38
|
+
const shape = args[0] && unwrap(args[0]);
|
|
39
|
+
if (name === "object" && shape && ts.isObjectLiteralExpression(shape)) {
|
|
40
|
+
tree.fields = /* @__PURE__ */ new Map();
|
|
41
|
+
for (const property of shape.properties) if (ts.isPropertyAssignment(property)) {
|
|
42
|
+
const key = propertyKey(property.name);
|
|
43
|
+
if (key !== void 0) tree.fields.set(key, readDescriptions(property.initializer, checker, new Set(seen)));
|
|
44
|
+
} else if (ts.isShorthandPropertyAssignment(property)) {
|
|
45
|
+
let symbol = checker.getShorthandAssignmentValueSymbol(property);
|
|
46
|
+
if (symbol?.flags && symbol.flags & SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
|
|
47
|
+
const declaration = symbol?.valueDeclaration?.resolve();
|
|
48
|
+
tree.fields.set(propertyKey(property.name) ?? property.name.getText(), declaration && ts.isVariableDeclaration(declaration) ? readDescriptions(declaration.initializer, checker, new Set(seen)) : {});
|
|
49
|
+
}
|
|
50
|
+
const description = readOwnDescription(args.slice(1));
|
|
51
|
+
if (description !== void 0) tree.description = description;
|
|
52
|
+
return tree;
|
|
53
|
+
}
|
|
54
|
+
if (name === "array") {
|
|
55
|
+
const element = readDescriptions(args[0], checker, seen);
|
|
56
|
+
if (element.fields) tree.element = element;
|
|
57
|
+
const description = readOwnDescription(args.slice(1));
|
|
58
|
+
if (description !== void 0) tree.description = description;
|
|
59
|
+
return tree;
|
|
60
|
+
}
|
|
61
|
+
const description = readOwnDescription(args);
|
|
62
|
+
if (description !== void 0) tree.description = description;
|
|
63
|
+
return tree;
|
|
64
|
+
}
|
|
65
|
+
function readOwnDescription(args) {
|
|
66
|
+
for (const arg of args) {
|
|
67
|
+
const node = unwrap(arg);
|
|
68
|
+
if (!ts.isObjectLiteralExpression(node)) continue;
|
|
69
|
+
const property = node.properties.find((property) => ts.isPropertyAssignment(property) && propertyKey(property.name) === "description");
|
|
70
|
+
if (!property || !ts.isPropertyAssignment(property)) continue;
|
|
71
|
+
const value = property.initializer && unwrap(property.initializer);
|
|
72
|
+
if (value && (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value))) return value.text;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function propertyKey(name) {
|
|
76
|
+
if (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name) || ts.isNumericLiteral(name)) return name.text;
|
|
77
|
+
if (ts.isComputedPropertyName(name)) {
|
|
78
|
+
const inner = unwrap(name.expression);
|
|
79
|
+
if (ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) return inner.text;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function unwrap(node) {
|
|
83
|
+
let current = node;
|
|
84
|
+
while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isNonNullExpression(current)) current = current.expression;
|
|
85
|
+
return current;
|
|
86
|
+
}
|
|
87
|
+
// \0@oxc-project+runtime@0.158.0/helpers/esm/usingCtx.js
|
|
88
|
+
function _usingCtx() {
|
|
89
|
+
var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
|
|
90
|
+
var n = Error();
|
|
91
|
+
return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
|
|
92
|
+
}, e = {}, n = [];
|
|
93
|
+
function using(r, e) {
|
|
94
|
+
if (null != e) {
|
|
95
|
+
if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
|
|
96
|
+
if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
|
|
97
|
+
if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
|
|
98
|
+
if ("function" != typeof o) throw new TypeError("Object is not disposable.");
|
|
99
|
+
t && (o = function o() {
|
|
100
|
+
try {
|
|
101
|
+
t.call(e);
|
|
102
|
+
} catch (r) {
|
|
103
|
+
return Promise.reject(r);
|
|
104
|
+
}
|
|
105
|
+
}), n.push({
|
|
106
|
+
v: e,
|
|
107
|
+
d: o,
|
|
108
|
+
a: r
|
|
109
|
+
});
|
|
110
|
+
} else r && n.push({
|
|
111
|
+
d: e,
|
|
112
|
+
a: r
|
|
113
|
+
});
|
|
114
|
+
return e;
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
e,
|
|
118
|
+
u: using.bind(null, !1),
|
|
119
|
+
a: using.bind(null, !0),
|
|
120
|
+
d: function d() {
|
|
121
|
+
var o, t = this.e, s = 0;
|
|
122
|
+
function next() {
|
|
123
|
+
for (; o = n.pop();) try {
|
|
124
|
+
if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
|
|
125
|
+
if (o.d) {
|
|
126
|
+
var r = o.d.call(o.v);
|
|
127
|
+
if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
|
|
128
|
+
} else s |= 1;
|
|
129
|
+
} catch (r) {
|
|
130
|
+
return err(r);
|
|
131
|
+
}
|
|
132
|
+
if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
|
|
133
|
+
if (t !== e) throw t;
|
|
134
|
+
}
|
|
135
|
+
function err(n) {
|
|
136
|
+
return t = t !== e ? new r(n, t) : n, next();
|
|
137
|
+
}
|
|
138
|
+
return next();
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
// src/extractor.ts
|
|
143
|
+
const builderFlags = NodeBuilderFlags.NoTruncation | NodeBuilderFlags.InTypeAlias | NodeBuilderFlags.MultilineObjectLiterals;
|
|
144
|
+
/** Reads `Input` and `Output` types of exported Loculus schemas with the TypeScript compiler. */
|
|
145
|
+
var LoculusTypeExtractor = class {
|
|
146
|
+
#api;
|
|
147
|
+
#options;
|
|
148
|
+
#resolver;
|
|
149
|
+
#files = /* @__PURE__ */ new Set();
|
|
150
|
+
#program;
|
|
151
|
+
#cwd;
|
|
152
|
+
constructor(options = {}) {
|
|
153
|
+
this.#cwd = resolve(options.cwd ?? process.cwd());
|
|
154
|
+
const tsConfigFilePath = options.project ? resolve(this.#cwd, options.project) : findTsConfig(this.#cwd);
|
|
155
|
+
try {
|
|
156
|
+
this.#api = new API({ cwd: this.#cwd });
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (error instanceof Error && error.message.startsWith("Unable to resolve @typescript/typescript-")) throw new Error(`TypeScript native compiler is unavailable for ${process.platform}/${process.arch}. Install optional dependencies with npm install --include=optional, and use a platform supported by TypeScript 7.1.`, { cause: error });
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
const parsed = tsConfigFilePath ? this.#api.parseConfigFile(tsConfigFilePath) : this.#api.parseCommandLine([
|
|
163
|
+
"--strict",
|
|
164
|
+
"--target",
|
|
165
|
+
"es2022",
|
|
166
|
+
"--module",
|
|
167
|
+
"nodenext",
|
|
168
|
+
"--moduleResolution",
|
|
169
|
+
"nodenext",
|
|
170
|
+
"--skipLibCheck"
|
|
171
|
+
]);
|
|
172
|
+
const errors = parsed.errors.filter((error) => error.code !== 18002 && error.code !== 18003);
|
|
173
|
+
if (errors.length) throw new Error(formatDiagnostics(errors, this.#api));
|
|
174
|
+
this.#options = parsed.options;
|
|
175
|
+
this.#resolver = this.#api.createModuleResolver(this.#options);
|
|
176
|
+
} catch (error) {
|
|
177
|
+
this.#api[Symbol.dispose]();
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** Lists exported Loculus schema names in a file. */
|
|
182
|
+
listSchemas(filePath) {
|
|
183
|
+
return this.#candidates(this.#sourceFile(filePath)).map((candidate) => candidate.exportName);
|
|
184
|
+
}
|
|
185
|
+
/** Extracts every exported Loculus schema in a file, in declaration order. */
|
|
186
|
+
extractAll(filePath, options = {}) {
|
|
187
|
+
const sourceFile = this.#sourceFile(filePath);
|
|
188
|
+
let candidates = this.#candidates(sourceFile);
|
|
189
|
+
if (options.schemas) {
|
|
190
|
+
const wanted = new Set(options.schemas);
|
|
191
|
+
candidates = candidates.filter((candidate) => wanted.has(candidate.exportName));
|
|
192
|
+
}
|
|
193
|
+
if (candidates.length === 0) return [];
|
|
194
|
+
const project = this.#program.getProject();
|
|
195
|
+
const scope = new Map(project.checker.getSymbolsInScope(sourceFile, SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Alias).map((symbol) => [symbol.name, symbol]));
|
|
196
|
+
return candidates.map(({ exportName, declaration }) => {
|
|
197
|
+
const tree = options.withDescriptions ? readDescriptions(declaration.initializer, project.checker) : {};
|
|
198
|
+
const inputReferences = new References(sourceFile, scope, this.#program, this.#resolver);
|
|
199
|
+
const outputReferences = new References(sourceFile, scope, this.#program, this.#resolver);
|
|
200
|
+
const schemaType = project.checker.getTypeAtLocation(declaration);
|
|
201
|
+
const order = this.#shapeOrder(schemaType, declaration);
|
|
202
|
+
const input = this.#print(declaration, schemaType, "_input", tree, order, false, inputReferences);
|
|
203
|
+
const output = this.#print(declaration, schemaType, "_output", tree, order, true, outputReferences);
|
|
204
|
+
const description = options.withDescriptions ? tree.description : void 0;
|
|
205
|
+
return {
|
|
206
|
+
schemaName: exportName,
|
|
207
|
+
filePath: sourceFile.fileName,
|
|
208
|
+
input,
|
|
209
|
+
output,
|
|
210
|
+
...description === void 0 ? {} : { description },
|
|
211
|
+
imports: inputReferences.merge(outputReferences),
|
|
212
|
+
inputImports: inputReferences.imports(),
|
|
213
|
+
outputImports: outputReferences.imports(),
|
|
214
|
+
warnings: [.../* @__PURE__ */ new Set([...inputReferences.warnings, ...outputReferences.warnings])]
|
|
215
|
+
};
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
/** Extracts one exported Loculus schema. Throws when it is not found. */
|
|
219
|
+
extract(filePath, schemaName, options = {}) {
|
|
220
|
+
const [result] = this.extractAll(filePath, {
|
|
221
|
+
...options,
|
|
222
|
+
schemas: [schemaName]
|
|
223
|
+
});
|
|
224
|
+
if (!result) throw new Error(`Loculus schema "${schemaName}" is not exported from ${filePath}`);
|
|
225
|
+
return result;
|
|
226
|
+
}
|
|
227
|
+
/** Loads several files before extraction so their dependencies are resolved once, not per file. */
|
|
228
|
+
addSourceFiles(filePaths) {
|
|
229
|
+
const before = this.#files.size;
|
|
230
|
+
for (const filePath of filePaths) this.#files.add(resolve(this.#cwd, filePath));
|
|
231
|
+
if (this.#program && before === this.#files.size) return;
|
|
232
|
+
this.#program?.[Symbol.dispose]();
|
|
233
|
+
this.#program = void 0;
|
|
234
|
+
this.#program = this.#api.createProgram([...this.#files], this.#options);
|
|
235
|
+
}
|
|
236
|
+
dispose() {
|
|
237
|
+
const program = this.#program;
|
|
238
|
+
this.#program = void 0;
|
|
239
|
+
try {
|
|
240
|
+
program?.[Symbol.dispose]();
|
|
241
|
+
} finally {
|
|
242
|
+
try {
|
|
243
|
+
this.#resolver[Symbol.dispose]();
|
|
244
|
+
} finally {
|
|
245
|
+
this.#api[Symbol.dispose]();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
[Symbol.dispose]() {
|
|
250
|
+
this.dispose();
|
|
251
|
+
}
|
|
252
|
+
#sourceFile(filePath) {
|
|
253
|
+
this.addSourceFiles([filePath]);
|
|
254
|
+
const file = this.#program.getSourceFile(resolve(this.#cwd, filePath));
|
|
255
|
+
if (!file) throw new Error(`Source file not found: ${filePath}`);
|
|
256
|
+
return file;
|
|
257
|
+
}
|
|
258
|
+
#candidates(sourceFile) {
|
|
259
|
+
const checker = this.#program.getProject().checker;
|
|
260
|
+
const module = checker.getSymbolOfSourceFile(sourceFile.fileName);
|
|
261
|
+
if (!module) return [];
|
|
262
|
+
const candidates = [];
|
|
263
|
+
for (const exported of checker.getExportsOfModule(module)) {
|
|
264
|
+
if (exported.name === "default") continue;
|
|
265
|
+
const symbol = exported.flags & SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported;
|
|
266
|
+
for (const handle of symbol.declarations) {
|
|
267
|
+
const declaration = handle.resolve();
|
|
268
|
+
if (declaration && ts.isVariableDeclaration(declaration) && declaration.getSourceFile().fileName === sourceFile.fileName && isLoculusSchema(checker.getTypeAtLocation(declaration), declaration, checker)) candidates.push({
|
|
269
|
+
exportName: exported.name,
|
|
270
|
+
declaration
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return candidates.sort((a, b) => a.declaration.getStart() - b.declaration.getStart());
|
|
275
|
+
}
|
|
276
|
+
/** Field order of `object()` shapes, which the printed intersection types do not keep. */
|
|
277
|
+
#shapeOrder(type, location, depth = 0) {
|
|
278
|
+
const checker = this.#program.getProject().checker;
|
|
279
|
+
const shape = type.getProperty("shape");
|
|
280
|
+
if (!shape || depth > 32) return void 0;
|
|
281
|
+
const fields = /* @__PURE__ */ new Map();
|
|
282
|
+
for (const property of checker.getTypeOfSymbolAtLocation(shape, location).getProperties()) fields.set(property.name, this.#shapeOrder(checker.getTypeOfSymbolAtLocation(property, location), location, depth + 1));
|
|
283
|
+
return fields;
|
|
284
|
+
}
|
|
285
|
+
#print(declaration, schemaType, marker, tree, order, output, references) {
|
|
286
|
+
const checker = this.#program.getProject().checker;
|
|
287
|
+
const location = declaration;
|
|
288
|
+
const property = schemaType.getProperty(marker);
|
|
289
|
+
if (!property) throw new Error(`${declaration.name.getText()} has no ${marker} type`);
|
|
290
|
+
const node = reorder(new TypeNodeBuilder(checker, location).build(checker.getTypeOfSymbolAtLocation(property, location)), order);
|
|
291
|
+
references.collect(node);
|
|
292
|
+
let text = this.#api.printer.printNode(node);
|
|
293
|
+
text = text.replace(/^( {4})+/gm, (indent) => " ".repeat(indent.length / 2));
|
|
294
|
+
text = references.replaceImportTypes(text);
|
|
295
|
+
return addDescriptions(text, tree, output, this.#api);
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
/**
|
|
299
|
+
* Builds a type node that spells out anonymous object types, intersections and
|
|
300
|
+
* helper aliases such as `ObjectInput`, while keeping named interfaces and
|
|
301
|
+
* classes (`Date`, `URL`, user interfaces) as references.
|
|
302
|
+
*/
|
|
303
|
+
var TypeNodeBuilder = class {
|
|
304
|
+
#checker;
|
|
305
|
+
#location;
|
|
306
|
+
#visiting = /* @__PURE__ */ new Set();
|
|
307
|
+
constructor(checker, location) {
|
|
308
|
+
this.#checker = checker;
|
|
309
|
+
this.#location = location;
|
|
310
|
+
}
|
|
311
|
+
build(type) {
|
|
312
|
+
if (!this.#needsExpansion(type, /* @__PURE__ */ new Set())) return this.#reference(type);
|
|
313
|
+
if (this.#visiting.has(type)) return this.#reference(type);
|
|
314
|
+
this.#visiting.add(type);
|
|
315
|
+
try {
|
|
316
|
+
return this.#expand(type);
|
|
317
|
+
} finally {
|
|
318
|
+
this.#visiting.delete(type);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
#expand(type) {
|
|
322
|
+
const checker = this.#checker;
|
|
323
|
+
const { factory } = ts;
|
|
324
|
+
if (type.isUnionType()) {
|
|
325
|
+
const members = [];
|
|
326
|
+
const booleans = type.getTypes().filter((member) => member.flags & TypeFlags.BooleanLiteral);
|
|
327
|
+
const nullish = (member) => member.flags & TypeFlags.Undefined ? 2 : member.flags & TypeFlags.Null ? 1 : 0;
|
|
328
|
+
const absorbed = (member) => member.isIntersectionType() && member.getTypes().some((part) => type.getTypes().includes(part));
|
|
329
|
+
for (const member of [...type.getTypes()].filter((member) => !absorbed(member)).sort((a, b) => nullish(a) - nullish(b))) {
|
|
330
|
+
if (member.flags & TypeFlags.BooleanLiteral && booleans.length === 2) {
|
|
331
|
+
if (member === booleans[0]) members.push(factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword));
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
const node = this.build(member);
|
|
335
|
+
members.push(ts.isFunctionTypeNode(node) || ts.isConstructorTypeNode(node) || ts.isConditionalTypeNode(node) ? factory.createParenthesizedTypeNode(node) : node);
|
|
336
|
+
}
|
|
337
|
+
return factory.createUnionTypeNode(members);
|
|
338
|
+
}
|
|
339
|
+
if (type.isIntersectionType() && type.getTypes().some((part) => !(part.flags & TypeFlags.Object))) return factory.createIntersectionTypeNode(type.getTypes().map((part) => {
|
|
340
|
+
const node = this.build(part);
|
|
341
|
+
return ts.isUnionTypeNode(node) || ts.isFunctionTypeNode(node) ? factory.createParenthesizedTypeNode(node) : node;
|
|
342
|
+
}));
|
|
343
|
+
if (checker.isArrayType(type)) {
|
|
344
|
+
const [element] = checker.getTypeArguments(type);
|
|
345
|
+
let node = this.build(element);
|
|
346
|
+
if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node) || ts.isFunctionTypeNode(node) || ts.isConditionalTypeNode(node)) node = factory.createParenthesizedTypeNode(node);
|
|
347
|
+
const array = factory.createArrayTypeNode(node);
|
|
348
|
+
return isReadonlyArray(type) ? factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, array) : array;
|
|
349
|
+
}
|
|
350
|
+
if (checker.isTupleType(type)) {
|
|
351
|
+
const target = type.getTarget();
|
|
352
|
+
const elements = checker.getTypeArguments(type).map((element, index) => {
|
|
353
|
+
const flags = target.elementFlags[index];
|
|
354
|
+
const node = this.build(element);
|
|
355
|
+
if (flags & ElementFlags.Rest) return factory.createRestTypeNode(factory.createArrayTypeNode(node));
|
|
356
|
+
return flags & ElementFlags.Optional ? factory.createOptionalTypeNode(node) : node;
|
|
357
|
+
});
|
|
358
|
+
const tuple = factory.createTupleTypeNode(elements);
|
|
359
|
+
return target.readonly ? factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, tuple) : tuple;
|
|
360
|
+
}
|
|
361
|
+
const properties = checker.getPropertiesOfType(type);
|
|
362
|
+
if (properties.some((property) => String(property.escapedName).startsWith("__@"))) return this.#reference(type);
|
|
363
|
+
const members = properties.map((property) => {
|
|
364
|
+
const propertyType = checker.getTypeOfSymbolAtLocation(property, this.#location);
|
|
365
|
+
return factory.createPropertySignatureDeclaration(isReadonlyProperty(property) ? [factory.createToken(ts.SyntaxKind.ReadonlyKeyword)] : void 0, propertyName(property.name), property.flags & SymbolFlags.Optional ? factory.createToken(ts.SyntaxKind.QuestionToken) : void 0, this.build(propertyType), void 0);
|
|
366
|
+
});
|
|
367
|
+
const indexInfos = checker.getIndexInfosOfType(type).map((info) => factory.createIndexSignatureDeclaration(info.isReadonly ? [factory.createToken(ts.SyntaxKind.ReadonlyKeyword)] : void 0, [factory.createParameterDeclaration(void 0, void 0, factory.createIdentifier("key"), void 0, this.#reference(info.keyType))], this.build(info.valueType)));
|
|
368
|
+
return factory.createTypeLiteralNode([...indexInfos, ...members]);
|
|
369
|
+
}
|
|
370
|
+
/** Whether the type contains an anonymous object or intersection the compiler would print by alias. */
|
|
371
|
+
#needsExpansion(type, seen) {
|
|
372
|
+
if (seen.has(type)) return false;
|
|
373
|
+
seen.add(type);
|
|
374
|
+
if (type.getCallSignatures().length || type.getConstructSignatures().length) return false;
|
|
375
|
+
if (type.getAliasSymbol() && type.flags & (TypeFlags.Object | TypeFlags.UnionOrIntersection)) return true;
|
|
376
|
+
if (type.isUnionType()) return type.getTypes().some((member) => this.#needsExpansion(member, seen));
|
|
377
|
+
if (type.isIntersectionType()) return true;
|
|
378
|
+
if (this.#checker.isArrayType(type) || this.#checker.isTupleType(type)) return this.#checker.getTypeArguments(type).some((member) => this.#needsExpansion(member, seen));
|
|
379
|
+
if (!(type.flags & TypeFlags.Object)) return false;
|
|
380
|
+
return !isNamed(type);
|
|
381
|
+
}
|
|
382
|
+
#reference(type) {
|
|
383
|
+
const node = this.#checker.typeToTypeNode(type, this.#location, builderFlags);
|
|
384
|
+
if (!node) throw new Error(`Cannot print type ${this.#checker.typeToString(type)}`);
|
|
385
|
+
return node;
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
function leftmost(name) {
|
|
389
|
+
while (ts.isQualifiedName(name)) name = name.left;
|
|
390
|
+
return name.text;
|
|
391
|
+
}
|
|
392
|
+
function isNamed(type) {
|
|
393
|
+
const symbol = type.getSymbol();
|
|
394
|
+
return symbol !== void 0 && (symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface | SymbolFlags.Enum)) !== 0;
|
|
395
|
+
}
|
|
396
|
+
function isReadonlyProperty(property) {
|
|
397
|
+
if (property.checkFlags & CheckFlags.Readonly) return true;
|
|
398
|
+
const declaration = (property.valueDeclaration ?? property.declarations[0])?.resolve();
|
|
399
|
+
return declaration !== void 0 && (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Readonly) !== 0;
|
|
400
|
+
}
|
|
401
|
+
function isReadonlyArray(type) {
|
|
402
|
+
return type.isTypeReference() && type.getTarget().getSymbol()?.name === "ReadonlyArray";
|
|
403
|
+
}
|
|
404
|
+
function propertyName(name) {
|
|
405
|
+
return /^[A-Za-z_$][\w$]*$/.test(name) ? ts.factory.createIdentifier(name) : ts.factory.createStringLiteral(name, ts.TokenFlags.None);
|
|
406
|
+
}
|
|
407
|
+
function isLoculusSchema(type, node, checker) {
|
|
408
|
+
const standard = type.getProperty("~standard");
|
|
409
|
+
if (!standard || !type.getProperty("_input") || !type.getProperty("_output")) return false;
|
|
410
|
+
const property = checker.getTypeOfSymbolAtLocation(standard, node).getProperty("vendor");
|
|
411
|
+
const vendor = property && checker.getTypeOfSymbolAtLocation(property, node);
|
|
412
|
+
return vendor?.isStringLiteralType() === true && vendor.value === "loculus";
|
|
413
|
+
}
|
|
414
|
+
function findTsConfig(from) {
|
|
415
|
+
for (let directory = from;; directory = dirname(directory)) {
|
|
416
|
+
const candidate = join(directory, "tsconfig.json");
|
|
417
|
+
if (existsSync(candidate)) return candidate;
|
|
418
|
+
if (dirname(directory) === directory) return void 0;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
function memberName(member) {
|
|
422
|
+
const name = ts.isPropertySignatureDeclaration(member) || ts.isMethodSignatureDeclaration(member) ? member.name : void 0;
|
|
423
|
+
return name && (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) ? name.text : void 0;
|
|
424
|
+
}
|
|
425
|
+
function reorder(node, order) {
|
|
426
|
+
if (!order) return node;
|
|
427
|
+
if (ts.isUnionTypeNode(node)) return ts.factory.updateUnionTypeNode(node, ts.factory.createNodeArray(node.types.map((type) => reorder(type, order))));
|
|
428
|
+
if (ts.isParenthesizedTypeNode(node)) return ts.factory.updateParenthesizedTypeNode(node, reorder(node.type, order));
|
|
429
|
+
if (!ts.isTypeLiteralNode(node)) return node;
|
|
430
|
+
const keys = [...order.keys()];
|
|
431
|
+
const rank = (member) => {
|
|
432
|
+
const index = keys.indexOf(memberName(member) ?? "");
|
|
433
|
+
return index === -1 ? keys.length : index;
|
|
434
|
+
};
|
|
435
|
+
const members = node.members.map((member, index) => {
|
|
436
|
+
const child = order.get(memberName(member) ?? "");
|
|
437
|
+
return {
|
|
438
|
+
member: child && ts.isPropertySignatureDeclaration(member) && member.type ? ts.factory.updatePropertySignatureDeclaration(member, member.modifiers, member.name, member.postfixToken, reorder(member.type, child), member.initializer) : member,
|
|
439
|
+
rank: rank(member),
|
|
440
|
+
index
|
|
441
|
+
};
|
|
442
|
+
});
|
|
443
|
+
members.sort((a, b) => a.rank - b.rank || a.index - b.index);
|
|
444
|
+
return ts.factory.updateTypeLiteralNode(node, ts.factory.createNodeArray(members.map((entry) => entry.member)));
|
|
445
|
+
}
|
|
446
|
+
function addDescriptions(text, tree, output, api) {
|
|
447
|
+
try {
|
|
448
|
+
var _usingCtx$2 = _usingCtx();
|
|
449
|
+
if (!tree.fields && !tree.element || tree.inputOnlyFields && output) return text;
|
|
450
|
+
const source = _usingCtx$2.u(api.createSourceFile("__loculus_generated.ts", "type __LoculusGenerated = " + text)).sourceFile;
|
|
451
|
+
const declaration = source.statements[0];
|
|
452
|
+
if (!declaration || !ts.isTypeAliasDeclaration(declaration)) throw new Error("Cannot parse generated type");
|
|
453
|
+
const edits = [];
|
|
454
|
+
const visit = (node, tree) => {
|
|
455
|
+
if (tree.inputOnlyFields && output) return;
|
|
456
|
+
if (ts.isTypeOperatorNode(node) || ts.isParenthesizedTypeNode(node)) return visit(node.type, tree);
|
|
457
|
+
if (ts.isArrayTypeNode(node)) {
|
|
458
|
+
if (tree.element) visit(node.elementType, tree.element);
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
if (ts.isUnionTypeNode(node)) {
|
|
462
|
+
for (const member of node.types) visit(member, tree);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
if (!ts.isTypeLiteralNode(node) || !tree.fields) return;
|
|
466
|
+
for (const member of node.members) {
|
|
467
|
+
if (!ts.isPropertySignatureDeclaration(member)) continue;
|
|
468
|
+
const field = tree.fields.get(memberName(member) ?? "");
|
|
469
|
+
if (!field) continue;
|
|
470
|
+
if (field.description !== void 0) {
|
|
471
|
+
const start = member.getStart();
|
|
472
|
+
const lineStart = source.text.lastIndexOf("\n", start - 1) + 1;
|
|
473
|
+
const indent = source.text.slice(lineStart, start);
|
|
474
|
+
edits.push({
|
|
475
|
+
position: lineStart,
|
|
476
|
+
text: formatDoc(field.description, indent)
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
if (member.type) visit(member.type, field);
|
|
480
|
+
}
|
|
481
|
+
};
|
|
482
|
+
visit(declaration.type, tree);
|
|
483
|
+
let result = source.text;
|
|
484
|
+
for (const edit of edits.sort((a, b) => b.position - a.position)) result = result.slice(0, edit.position) + edit.text + result.slice(edit.position);
|
|
485
|
+
return result.slice(26);
|
|
486
|
+
} catch (_) {
|
|
487
|
+
_usingCtx$2.e = _;
|
|
488
|
+
} finally {
|
|
489
|
+
_usingCtx$2.d();
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
/** Formats a TSDoc comment at the given indentation, ending with a newline. */
|
|
493
|
+
function formatDoc(description, indent = "") {
|
|
494
|
+
const lines = description.replaceAll("*/", "*\\/").split(/\r?\n/);
|
|
495
|
+
if (lines.length === 1) return `${indent}/** ${lines[0]} */\n`;
|
|
496
|
+
return `${indent}/**\n${lines.map((line) => `${indent} *${line ? ` ${line}` : ""}`).join("\n")}\n${indent} */\n`;
|
|
497
|
+
}
|
|
498
|
+
/** Tracks named types referenced by printed type nodes. */
|
|
499
|
+
var References = class References {
|
|
500
|
+
warnings = [];
|
|
501
|
+
#sourceFile;
|
|
502
|
+
#program;
|
|
503
|
+
#resolver;
|
|
504
|
+
#scope;
|
|
505
|
+
#imports = /* @__PURE__ */ new Map();
|
|
506
|
+
constructor(sourceFile, scope, program, resolver) {
|
|
507
|
+
this.#resolver = resolver;
|
|
508
|
+
this.#program = program;
|
|
509
|
+
this.#sourceFile = sourceFile;
|
|
510
|
+
this.#scope = scope;
|
|
511
|
+
}
|
|
512
|
+
imports() {
|
|
513
|
+
return [...this.#imports.values()];
|
|
514
|
+
}
|
|
515
|
+
/** The imports of both, rejecting one name bound to different types. */
|
|
516
|
+
merge(other) {
|
|
517
|
+
const merged = new References(this.#sourceFile, this.#scope, this.#program, this.#resolver);
|
|
518
|
+
for (const entry of [...this.imports(), ...other.imports()]) merged.#record(entry);
|
|
519
|
+
return merged.imports();
|
|
520
|
+
}
|
|
521
|
+
collect(node) {
|
|
522
|
+
if (ts.isTypeReferenceNode(node)) this.#add(leftmost(node.typeName));
|
|
523
|
+
else if (ts.isTypeQueryNode(node)) this.#add(leftmost(node.exprName));
|
|
524
|
+
else if (ts.isComputedPropertyName(node)) {
|
|
525
|
+
let expression = node.expression;
|
|
526
|
+
while (ts.isPropertyAccessExpression(expression)) expression = expression.expression;
|
|
527
|
+
if (ts.isIdentifier(expression)) this.#add(expression.text);
|
|
528
|
+
}
|
|
529
|
+
node.forEachChild((child) => this.collect(child));
|
|
530
|
+
}
|
|
531
|
+
/** Replaces `import("./module").Name` with `Name` and records the import. */
|
|
532
|
+
replaceImportTypes(text) {
|
|
533
|
+
return text.replace(/import\("([^"]+)"\)\.([A-Za-z_$][\w$]*)/g, (_, specifier, name) => {
|
|
534
|
+
const from = specifier.startsWith(".") || isAbsolute(specifier) ? this.#resolveModule(specifier) : specifier;
|
|
535
|
+
this.#record({
|
|
536
|
+
name,
|
|
537
|
+
importedName: name,
|
|
538
|
+
from
|
|
539
|
+
});
|
|
540
|
+
return name;
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
#resolveModule(specifier) {
|
|
544
|
+
return this.#resolver.resolveModuleName(specifier, dirname(this.#sourceFile.fileName)).resolvedModule?.resolvedFileName ?? resolve(dirname(this.#sourceFile.fileName), specifier);
|
|
545
|
+
}
|
|
546
|
+
#add(name) {
|
|
547
|
+
if (this.#imports.has(name)) return;
|
|
548
|
+
const declaration = this.#scope.get(name)?.declarations[0]?.resolve();
|
|
549
|
+
if (!declaration) return;
|
|
550
|
+
if (ts.isImportSpecifier(declaration)) {
|
|
551
|
+
const imported = declaration.propertyName ?? declaration.name;
|
|
552
|
+
this.#record({
|
|
553
|
+
name,
|
|
554
|
+
importedName: imported.text,
|
|
555
|
+
from: this.#moduleOf(declaration)
|
|
556
|
+
});
|
|
557
|
+
} else if (ts.isImportClause(declaration)) this.#record({
|
|
558
|
+
name,
|
|
559
|
+
importedName: "default",
|
|
560
|
+
from: this.#moduleOf(declaration)
|
|
561
|
+
});
|
|
562
|
+
else if (ts.isNamespaceImport(declaration)) this.#record({
|
|
563
|
+
name,
|
|
564
|
+
importedName: "*",
|
|
565
|
+
from: this.#moduleOf(declaration)
|
|
566
|
+
});
|
|
567
|
+
else if (declaration.getSourceFile().fileName === this.#sourceFile.fileName) {
|
|
568
|
+
const checker = this.#program.getProject().checker;
|
|
569
|
+
const module = checker.getSymbolOfSourceFile(this.#sourceFile.fileName);
|
|
570
|
+
const exported = module && checker.getExportsOfModule(module).find((entry) => {
|
|
571
|
+
return (entry.flags & SymbolFlags.Alias ? checker.getAliasedSymbol(entry) : entry).declarations.some((handle) => handle.resolve() === declaration);
|
|
572
|
+
});
|
|
573
|
+
if (exported) this.#record({
|
|
574
|
+
name,
|
|
575
|
+
importedName: exported.name,
|
|
576
|
+
from: this.#sourceFile.fileName
|
|
577
|
+
});
|
|
578
|
+
else this.warnings.push(`"${name}" is used by a schema type but is not exported from ${this.#sourceFile.fileName}`);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
#moduleOf(node) {
|
|
582
|
+
while (!ts.isImportDeclaration(node)) node = node.parent;
|
|
583
|
+
const specifier = node.moduleSpecifier;
|
|
584
|
+
if (!ts.isStringLiteral(specifier)) throw new Error("Expected a string module specifier");
|
|
585
|
+
if (!specifier.text.startsWith(".") && !isAbsolute(specifier.text)) return specifier.text;
|
|
586
|
+
return this.#program.getResolvedModuleFromModuleSpecifier(specifier, this.#sourceFile.fileName)?.resolvedFileName ?? resolve(dirname(this.#sourceFile.fileName), specifier.text);
|
|
587
|
+
}
|
|
588
|
+
#record(entry) {
|
|
589
|
+
const existing = this.#imports.get(entry.name);
|
|
590
|
+
if (!existing) this.#imports.set(entry.name, entry);
|
|
591
|
+
else if (existing.from !== entry.from || existing.importedName !== entry.importedName) throw new Error(`"${entry.name}" refers to different types from ${existing.from} and ${entry.from}; rename one of them`);
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
// src/format.ts
|
|
595
|
+
/** Decides the exported type declarations for extracted schemas. */
|
|
596
|
+
function formatTypes(schemas, options = {}) {
|
|
597
|
+
if (options.inputOnly && options.outputOnly) throw new Error("inputOnly and outputOnly cannot be combined");
|
|
598
|
+
const types = [];
|
|
599
|
+
for (const schema of schemas) {
|
|
600
|
+
const base = baseName(schema.schemaName, options);
|
|
601
|
+
const common = {
|
|
602
|
+
schemaName: schema.schemaName,
|
|
603
|
+
...schema.description === void 0 ? {} : { description: schema.description }
|
|
604
|
+
};
|
|
605
|
+
if (options.mergeSame && !options.inputOnly && !options.outputOnly && schema.input === schema.output) {
|
|
606
|
+
types.push({
|
|
607
|
+
...common,
|
|
608
|
+
name: base,
|
|
609
|
+
kind: "merged",
|
|
610
|
+
text: schema.input
|
|
611
|
+
});
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
if (!options.outputOnly) types.push({
|
|
615
|
+
...common,
|
|
616
|
+
name: base + (options.inputSuffix ?? "Input"),
|
|
617
|
+
kind: "input",
|
|
618
|
+
text: schema.input
|
|
619
|
+
});
|
|
620
|
+
if (!options.inputOnly) types.push({
|
|
621
|
+
...common,
|
|
622
|
+
name: base + (options.outputSuffix ?? "Output"),
|
|
623
|
+
kind: "output",
|
|
624
|
+
text: schema.output
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
const seen = /* @__PURE__ */ new Map();
|
|
628
|
+
for (const type of types) {
|
|
629
|
+
const previous = seen.get(type.name);
|
|
630
|
+
if (previous !== void 0) throw new Error(`Type name "${type.name}" is generated for both ${previous} and ${type.schemaName}`);
|
|
631
|
+
seen.set(type.name, type.schemaName);
|
|
632
|
+
}
|
|
633
|
+
return types;
|
|
634
|
+
}
|
|
635
|
+
function baseName(schemaName, options) {
|
|
636
|
+
const mapped = options.map?.[schemaName];
|
|
637
|
+
if (mapped !== void 0) return mapped;
|
|
638
|
+
const { suffix } = options;
|
|
639
|
+
return suffix && schemaName.endsWith(suffix) && schemaName.length > suffix.length ? schemaName.slice(0, -suffix.length) : schemaName;
|
|
640
|
+
}
|
|
641
|
+
/** Renders extracted schemas as a TypeScript module. */
|
|
642
|
+
function renderModule(schemas, options = {}) {
|
|
643
|
+
const types = formatTypes(schemas, options);
|
|
644
|
+
const directory = options.outFile ? dirname(options.outFile) : options.cwd ?? process.cwd();
|
|
645
|
+
const imports = /* @__PURE__ */ new Map();
|
|
646
|
+
const namespaces = [];
|
|
647
|
+
const bindings = new Map(types.map((type) => [type.name, `the generated type ${type.name}`]));
|
|
648
|
+
const emitted = schemas.flatMap((schema) => formatTypes([schema], options).map((type) => ({
|
|
649
|
+
type,
|
|
650
|
+
schema
|
|
651
|
+
})));
|
|
652
|
+
for (const { type, schema } of emitted) for (const entry of type.kind === "output" ? schema.outputImports : schema.inputImports) {
|
|
653
|
+
const specifier = importSpecifier(entry, directory);
|
|
654
|
+
const identity = `${entry.importedName} from ${specifier}`;
|
|
655
|
+
const bound = bindings.get(entry.name);
|
|
656
|
+
if (bound !== void 0 && bound !== identity) throw new Error(`"${entry.name}" would refer to both ${bound} and ${identity}; rename one of them`);
|
|
657
|
+
bindings.set(entry.name, identity);
|
|
658
|
+
if (entry.importedName === "*") {
|
|
659
|
+
namespaces.push(`import type * as ${entry.name} from ${JSON.stringify(specifier)};`);
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
const names = imports.get(specifier) ?? /* @__PURE__ */ new Map();
|
|
663
|
+
names.set(entry.name, entry.importedName === entry.name ? entry.name : `${entry.importedName} as ${entry.name}`);
|
|
664
|
+
imports.set(specifier, names);
|
|
665
|
+
}
|
|
666
|
+
const lines = [];
|
|
667
|
+
if (options.header) lines.push(options.header, "");
|
|
668
|
+
const importLines = [...[...imports].map(([specifier, names]) => `import type { ${[...new Set(names.values())].sort().join(", ")} } from ${JSON.stringify(specifier)};`), ...new Set(namespaces)];
|
|
669
|
+
if (importLines.length) lines.push(...importLines, "");
|
|
670
|
+
for (const type of types) {
|
|
671
|
+
const doc = type.description === void 0 ? "" : formatDoc(type.description);
|
|
672
|
+
lines.push(`${doc}export type ${type.name} = ${type.text};`, "");
|
|
673
|
+
}
|
|
674
|
+
return lines.join("\n").replace(/\n+$/, "\n");
|
|
675
|
+
}
|
|
676
|
+
function importSpecifier(entry, directory) {
|
|
677
|
+
if (!isAbsolute(entry.from)) return entry.from;
|
|
678
|
+
let specifier = relative(directory, entry.from).split(sep).join("/");
|
|
679
|
+
specifier = specifier.replace(/\.d\.([cm]?)ts$/, ".$1js").replace(/\.([cm]?)tsx?$/, ".$1js");
|
|
680
|
+
return specifier.startsWith(".") ? specifier : `./${specifier}`;
|
|
681
|
+
}
|
|
682
|
+
// src/generate.ts
|
|
683
|
+
const GENERATED_HEADER = "// Generated by @loculus/infer. Do not edit by hand.";
|
|
684
|
+
/** Extracts types from the matching files and renders the output modules without writing them. */
|
|
685
|
+
async function generate(options) {
|
|
686
|
+
try {
|
|
687
|
+
var _usingCtx$1 = _usingCtx();
|
|
688
|
+
if (options.outDir && options.outFile) throw new Error("outDir and outFile cannot be combined");
|
|
689
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
690
|
+
const files = await resolveFiles(options.include, options.exclude, cwd);
|
|
691
|
+
if (files.length === 0) throw new Error(`No files matched ${options.include.join(", ")}`);
|
|
692
|
+
const extractor = _usingCtx$1.u(new LoculusTypeExtractor(options));
|
|
693
|
+
extractor.addSourceFiles(files);
|
|
694
|
+
const extracted = files.map((file) => ({
|
|
695
|
+
file,
|
|
696
|
+
schemas: extractor.extractAll(file, options)
|
|
697
|
+
}));
|
|
698
|
+
const warnings = [...new Set(extracted.flatMap(({ schemas }) => schemas.flatMap((schema) => schema.warnings)))];
|
|
699
|
+
const withSchemas = extracted.filter(({ schemas }) => schemas.length > 0);
|
|
700
|
+
if (options.outFile) {
|
|
701
|
+
const path = resolve(cwd, options.outFile);
|
|
702
|
+
const schemas = withSchemas.flatMap((entry) => entry.schemas);
|
|
703
|
+
return {
|
|
704
|
+
warnings,
|
|
705
|
+
files: [{
|
|
706
|
+
path,
|
|
707
|
+
sources: withSchemas.map((entry) => entry.file),
|
|
708
|
+
schemas,
|
|
709
|
+
content: renderModule(schemas, {
|
|
710
|
+
...options,
|
|
711
|
+
outFile: path,
|
|
712
|
+
header: GENERATED_HEADER
|
|
713
|
+
})
|
|
714
|
+
}]
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
if (options.outDir) {
|
|
718
|
+
const pattern = options.outPattern ?? (options.declaration ? "[name].types.d.ts" : "[name].types.ts");
|
|
719
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
720
|
+
const outputPath = (file) => resolve(cwd, options.outDir, pattern.replaceAll("[name]", basename(file, extname(file))));
|
|
721
|
+
const headerFor = (file, path) => `${GENERATED_HEADER}\n// Source: ${relative(dirname(path), file).split(sep).join("/")}`;
|
|
722
|
+
const generated = withSchemas.map(({ file, schemas }) => {
|
|
723
|
+
const path = outputPath(file);
|
|
724
|
+
const previous = byPath.get(path);
|
|
725
|
+
if (previous) throw new Error(`${previous} and ${file} would both be written to ${path}; use outFile or a different outPattern`);
|
|
726
|
+
byPath.set(path, file);
|
|
727
|
+
return {
|
|
728
|
+
path,
|
|
729
|
+
sources: [file],
|
|
730
|
+
schemas,
|
|
731
|
+
content: renderModule(schemas, {
|
|
732
|
+
...options,
|
|
733
|
+
outFile: path,
|
|
734
|
+
header: headerFor(file, path)
|
|
735
|
+
})
|
|
736
|
+
};
|
|
737
|
+
});
|
|
738
|
+
for (const { file, schemas } of extracted) {
|
|
739
|
+
if (schemas.length > 0 || extractor.listSchemas(file).length > 0) continue;
|
|
740
|
+
const path = outputPath(file);
|
|
741
|
+
if (byPath.has(path)) continue;
|
|
742
|
+
if ((await readFile(path, "utf8").catch(() => void 0))?.startsWith(`${headerFor(file, path)}\n`)) generated.push({
|
|
743
|
+
path,
|
|
744
|
+
sources: [file],
|
|
745
|
+
schemas,
|
|
746
|
+
content: "",
|
|
747
|
+
obsolete: true
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
return {
|
|
751
|
+
warnings,
|
|
752
|
+
files: generated
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
return {
|
|
756
|
+
warnings,
|
|
757
|
+
files: withSchemas.map(({ file, schemas }) => ({
|
|
758
|
+
sources: [file],
|
|
759
|
+
schemas,
|
|
760
|
+
content: renderModule(schemas, {
|
|
761
|
+
...options,
|
|
762
|
+
cwd
|
|
763
|
+
})
|
|
764
|
+
}))
|
|
765
|
+
};
|
|
766
|
+
} catch (_) {
|
|
767
|
+
_usingCtx$1.e = _;
|
|
768
|
+
} finally {
|
|
769
|
+
_usingCtx$1.d();
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
/** Returns the generated files whose content differs from what is on disk. */
|
|
773
|
+
async function findOutdated(files) {
|
|
774
|
+
const outdated = [];
|
|
775
|
+
for (const file of files) {
|
|
776
|
+
if (!file.path) continue;
|
|
777
|
+
const current = await readFile(file.path, "utf8").catch(() => void 0);
|
|
778
|
+
if (file.obsolete ? current !== void 0 : current !== file.content) outdated.push(file);
|
|
779
|
+
}
|
|
780
|
+
return outdated;
|
|
781
|
+
}
|
|
782
|
+
async function resolveFiles(include, exclude = [], cwd) {
|
|
783
|
+
const normalize = (pattern) => process.platform === "win32" ? pattern.replaceAll("\\", "/") : pattern;
|
|
784
|
+
const patterns = include.map(normalize);
|
|
785
|
+
const ignored = exclude.map(normalize);
|
|
786
|
+
const negative = patterns.filter((pattern) => pattern.startsWith("!") && !pattern.startsWith("!(")).map((pattern) => pattern.slice(1));
|
|
787
|
+
const positive = patterns.filter((pattern) => !pattern.startsWith("!") || pattern.startsWith("!("));
|
|
788
|
+
const matches = (await Promise.all(positive.map(async (pattern) => {
|
|
789
|
+
const expanded = pattern.replace(/(^|\/)(!\([^/]+)/g, "$1{$2,.*}");
|
|
790
|
+
const paths = await glob(expanded, {
|
|
791
|
+
cwd,
|
|
792
|
+
absolute: true,
|
|
793
|
+
ignore: [
|
|
794
|
+
...ignored,
|
|
795
|
+
...negative,
|
|
796
|
+
"**/node_modules/**"
|
|
797
|
+
],
|
|
798
|
+
nodir: true,
|
|
799
|
+
follow: true
|
|
800
|
+
});
|
|
801
|
+
return expanded === pattern ? paths : paths.filter((path) => minimatch((isAbsolute(pattern) ? path : relative(cwd, path)).split(sep).join("/"), pattern, {
|
|
802
|
+
dot: true,
|
|
803
|
+
nonegate: true
|
|
804
|
+
}));
|
|
805
|
+
}))).flat();
|
|
806
|
+
return [...new Set(matches.map((file) => resolve(file)))].filter((file) => /\.[cm]?tsx?$/.test(file) && !/\.d\.[cm]?ts$/.test(file)).sort();
|
|
807
|
+
}
|
|
808
|
+
export { renderModule as a, formatTypes as i, findOutdated as n, LoculusTypeExtractor as o, generate as r, formatDoc as s, GENERATED_HEADER as t };
|