@power-plant/schema 0.0.55 → 0.0.57

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.
@@ -0,0 +1,2369 @@
1
+ const require_rolldown_runtime = require('./rolldown-runtime-C24Yb2bl.cjs');
2
+ let typescript = require("typescript");
3
+ typescript = require_rolldown_runtime.__toESM(typescript, 1);
4
+ let _marcj_ts_clone_node = require("@marcj/ts-clone-node");
5
+ let _deepkit_type_spec = require("@deepkit/type-spec");
6
+ let micromatch = require("micromatch");
7
+ micromatch = require_rolldown_runtime.__toESM(micromatch, 1);
8
+ let _typescript_vfs = require("@typescript/vfs");
9
+ let path = require("path");
10
+
11
+ //#region ../../../node_modules/.pnpm/@deepkit+type-compiler@1.0.19_patch_hash=bd438188cbc12e606ed4d519c25ab921a833fbc2d92357_e562d261195ccb1f28e41e80fc823414/node_modules/@deepkit/type-compiler/dist/esm/src/reflection-ast.js
12
+ const { isArrowFunction: isArrowFunction$1, isComputedPropertyName, isIdentifier: isIdentifier$1, isNamedImports, isNumericLiteral, isPrivateIdentifier, isStringLiteral: isStringLiteral$2, isStringLiteralLike, setOriginalNode, getLeadingCommentRanges, isNoSubstitutionTemplateLiteral, NodeFlags: NodeFlags$1, SyntaxKind: SyntaxKind$1 } = typescript.default;
13
+ function is__String(value) {
14
+ return typeof value === "string";
15
+ }
16
+ function getIdentifierName(node) {
17
+ if (is__String(node)) return node;
18
+ if (isIdentifier$1(node) || isPrivateIdentifier(node)) return typescript.default.unescapeLeadingUnderscores(node.escapedText);
19
+ if (isStringLiteral$2(node)) return node.text;
20
+ return "";
21
+ }
22
+ function getEscapedText(node) {
23
+ if (is__String(node)) return node;
24
+ if (isIdentifier$1(node) || isPrivateIdentifier(node)) return node.escapedText;
25
+ return getIdentifierName(node);
26
+ }
27
+ function findSourceFile(node) {
28
+ if (node.kind === SyntaxKind$1.SourceFile) return node;
29
+ let current = node.parent;
30
+ while (current && current.kind !== SyntaxKind$1.SourceFile) current = current.parent;
31
+ return current;
32
+ }
33
+ function joinQualifiedName(name) {
34
+ if (isIdentifier$1(name)) return getIdentifierName(name);
35
+ return joinQualifiedName(name.left) + "_" + getIdentifierName(name.right);
36
+ }
37
+ function getCommentOfNode(sourceFile, node) {
38
+ const comment = getLeadingCommentRanges(sourceFile.text, node.pos);
39
+ if (!comment) return;
40
+ return comment.map((v) => sourceFile.text.substring(v.pos, v.end)).join("\n");
41
+ }
42
+ function parseJSDocAttributeFromText(comment, attribute) {
43
+ const index = comment.indexOf("@" + attribute + " ");
44
+ if (index === -1) {
45
+ let start = 0;
46
+ while (true) {
47
+ const withoutContent = comment.indexOf("@" + attribute, start);
48
+ if (withoutContent === -1) return void 0;
49
+ const nextCharacter = comment[withoutContent + attribute.length + 1];
50
+ if (!nextCharacter || nextCharacter === " " || nextCharacter === "\n" || nextCharacter === "\r" || nextCharacter === " ") return "";
51
+ start = withoutContent + attribute.length + 1;
52
+ }
53
+ return;
54
+ }
55
+ const start = index + attribute.length + 2;
56
+ const nextAttribute = comment.indexOf("@", start);
57
+ const endOfComment = comment.indexOf("*/", start);
58
+ const end = nextAttribute === -1 ? endOfComment : Math.min(nextAttribute, endOfComment);
59
+ return comment.substring(start, end).trim().split("\n").map((v) => {
60
+ const indexOfStar = v.indexOf("*");
61
+ if (indexOfStar === -1) return v.trim();
62
+ return v.substring(indexOfStar + 1).trim();
63
+ }).join("\n");
64
+ }
65
+ function extractJSDocAttribute(sourceFile, node, attribute) {
66
+ if (!node) return void 0;
67
+ const comment = getCommentOfNode(sourceFile, node);
68
+ if (!comment) return void 0;
69
+ return parseJSDocAttributeFromText(comment, attribute);
70
+ }
71
+ /** Tags consumed by the type-compiler itself; never emitted as runtime type annotations. */
72
+ const JSDoc_COMPILER_TAGS = /* @__PURE__ */ new Set(["reflection", "intrinsic"]);
73
+ /**
74
+ * Parse a single JSDoc/TSDoc tag value.
75
+ *
76
+ * - empty / missing → `true` (flag tags like `@internal`)
77
+ * - `true` / `false` → boolean
78
+ * - `"quoted"` / `'quoted'` → unquoted string
79
+ * - otherwise → trimmed string (e.g. `@title The Title`)
80
+ */
81
+ function parseJSDocTagValue(raw) {
82
+ const content = raw.trim();
83
+ if (!content) return true;
84
+ if (content === "true") return true;
85
+ if (content === "false") return false;
86
+ const quote = content[0];
87
+ if ((quote === "\"" || quote === "'") && content.length >= 2 && content[content.length - 1] === quote) return content.slice(1, -1);
88
+ return content;
89
+ }
90
+ function stripJSDocLinePrefix(line) {
91
+ const trimmed = line.trim();
92
+ if (trimmed.startsWith("*")) return trimmed.slice(1).trimStart();
93
+ return trimmed;
94
+ }
95
+ /**
96
+ * Parse a full JSDoc/TSDoc comment into its main description and `@tag` values.
97
+ */
98
+ function parseJSDocTagsFromText(comment) {
99
+ let body = comment.trim();
100
+ if (body.startsWith("/**")) body = body.slice(3);
101
+ else if (body.startsWith("/*")) body = body.slice(2);
102
+ if (body.endsWith("*/")) body = body.slice(0, -2);
103
+ const lines = body.split("\n").map(stripJSDocLinePrefix);
104
+ const descriptionLines = [];
105
+ const tags = [];
106
+ let i = 0;
107
+ while (i < lines.length) {
108
+ const line = lines[i];
109
+ if (line.startsWith("@")) break;
110
+ descriptionLines.push(line);
111
+ i++;
112
+ }
113
+ while (i < lines.length) {
114
+ const line = lines[i];
115
+ if (!line.startsWith("@")) {
116
+ i++;
117
+ continue;
118
+ }
119
+ const afterAt = line.slice(1);
120
+ const space = afterAt.search(/[\s]/);
121
+ const name = (space === -1 ? afterAt : afterAt.slice(0, space)).trim();
122
+ let valueRaw = space === -1 ? "" : afterAt.slice(space + 1);
123
+ i++;
124
+ while (i < lines.length && !lines[i].startsWith("@")) {
125
+ if (lines[i] !== "" || valueRaw !== "") valueRaw = valueRaw === "" ? lines[i] : valueRaw + "\n" + lines[i];
126
+ i++;
127
+ }
128
+ if (!name || JSDoc_COMPILER_TAGS.has(name)) continue;
129
+ tags.push({
130
+ name,
131
+ value: parseJSDocTagValue(valueRaw)
132
+ });
133
+ }
134
+ const description = descriptionLines.join("\n").replace(/^\n+|\n+$/g, "");
135
+ return {
136
+ description: description.length ? description : void 0,
137
+ tags
138
+ };
139
+ }
140
+ function extractJSDocTags(sourceFile, node) {
141
+ if (!node) return { tags: [] };
142
+ const comment = getCommentOfNode(sourceFile, node);
143
+ if (!comment) return { tags: [] };
144
+ return parseJSDocTagsFromText(comment);
145
+ }
146
+ function getPropertyName(f, node) {
147
+ if (!node) return "";
148
+ if (isIdentifier$1(node)) return getIdentifierName(node);
149
+ if (isStringLiteral$2(node)) return node.text;
150
+ if (isNumericLiteral(node)) return +node.text;
151
+ if (isNoSubstitutionTemplateLiteral(node)) return node.text;
152
+ if (isComputedPropertyName(node)) return f.createArrowFunction(void 0, void 0, [], void 0, void 0, node.expression);
153
+ if (isPrivateIdentifier(node)) return getIdentifierName(node);
154
+ return "";
155
+ }
156
+ function getNameAsString(node) {
157
+ if (!node) return "";
158
+ if (isIdentifier$1(node)) return getIdentifierName(node);
159
+ if (isStringLiteral$2(node)) return node.text;
160
+ if (isNumericLiteral(node)) return node.text;
161
+ if ((0, typescript.isBigIntLiteral)(node)) return node.text;
162
+ if (isNoSubstitutionTemplateLiteral(node)) return node.text;
163
+ if (isComputedPropertyName(node)) {
164
+ if (isStringLiteralLike(node) || isNumericLiteral(node)) return node.text;
165
+ return "";
166
+ }
167
+ if (isPrivateIdentifier(node)) return getIdentifierName(node);
168
+ return joinQualifiedName(node);
169
+ }
170
+ function hasModifier(node, modifier) {
171
+ if (!node.modifiers) return false;
172
+ return node.modifiers.some((v) => v.kind === modifier);
173
+ }
174
+ const cloneHook = (node, payload) => {
175
+ if (isIdentifier$1(node)) return { text: () => {
176
+ return getIdentifierName(node);
177
+ } };
178
+ };
179
+ var NodeConverter = class {
180
+ constructor(f) {
181
+ this.f = f;
182
+ }
183
+ toExpression(node) {
184
+ if (node === void 0) return this.f.createIdentifier("undefined");
185
+ if (Array.isArray(node)) return this.f.createArrayLiteralExpression(this.f.createNodeArray(node.map((v) => this.toExpression(v))));
186
+ if ("string" === typeof node) return this.f.createStringLiteral(node, true);
187
+ if ("number" === typeof node) return this.f.createNumericLiteral(node);
188
+ if ("bigint" === typeof node) return this.f.createBigIntLiteral(String(node));
189
+ if ("boolean" === typeof node) return node ? this.f.createTrue() : this.f.createFalse();
190
+ if (node.pos === -1 && node.end === -1 && node.parent === void 0) {
191
+ if (isArrowFunction$1(node)) {
192
+ if (node.body.pos === -1 && node.body.end === -1 && node.body.parent === void 0) return node;
193
+ return this.f.createArrowFunction(node.modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, this.toExpression(node.body));
194
+ }
195
+ return node;
196
+ }
197
+ switch (node.kind) {
198
+ case SyntaxKind$1.Identifier: return finish(node, this.f.createIdentifier(getIdentifierName(node)));
199
+ case SyntaxKind$1.StringLiteral: return finish(node, this.f.createStringLiteral(node.text));
200
+ case SyntaxKind$1.NumericLiteral: return finish(node, this.f.createNumericLiteral(node.text));
201
+ case SyntaxKind$1.BigIntLiteral: return finish(node, this.f.createBigIntLiteral(node.text));
202
+ case SyntaxKind$1.TrueKeyword: return finish(node, this.f.createTrue());
203
+ case SyntaxKind$1.FalseKeyword: return finish(node, this.f.createFalse());
204
+ }
205
+ try {
206
+ return (0, _marcj_ts_clone_node.cloneNode)(node, {
207
+ preserveComments: false,
208
+ factory: this.f,
209
+ setOriginalNodes: true,
210
+ preserveSymbols: true,
211
+ setParents: true,
212
+ hook: cloneHook
213
+ });
214
+ } catch (error) {
215
+ console.error("could not clone node", node);
216
+ throw error;
217
+ }
218
+ }
219
+ };
220
+ function isExternalOrCommonJsModule(file) {
221
+ return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== void 0;
222
+ }
223
+ function isNodeWithLocals(node) {
224
+ return "locals" in node;
225
+ }
226
+ function getGlobalsOfSourceFile(file) {
227
+ if (file.redirectInfo) return;
228
+ if (!isNodeWithLocals(file)) return;
229
+ if (!isExternalOrCommonJsModule(file)) return file.locals;
230
+ if (file.jsGlobalAugmentations) return file.jsGlobalAugmentations;
231
+ if (file.symbol && file.symbol.globalExports) return file.symbol.globalExports;
232
+ }
233
+ /**
234
+ * For imports that can removed (like a class import only used as type only, like `p: Model[]`) we have
235
+ * to modify the import so TS does not remove it.
236
+ */
237
+ function ensureImportIsEmitted(importDeclaration, specifierName) {
238
+ if (specifierName && importDeclaration.importClause && importDeclaration.importClause.namedBindings) {
239
+ if (isNamedImports(importDeclaration.importClause.namedBindings)) {
240
+ for (const element of importDeclaration.importClause.namedBindings.elements) if (element.name.escapedText === specifierName.escapedText) {
241
+ element.flags |= NodeFlags$1.Synthesized;
242
+ return;
243
+ }
244
+ }
245
+ }
246
+ importDeclaration.flags |= NodeFlags$1.Synthesized;
247
+ }
248
+ /**
249
+ * Serializes an entity name as an expression for decorator type metadata.
250
+ *
251
+ * @param node The entity name to serialize.
252
+ */
253
+ function serializeEntityNameAsExpression(f, node) {
254
+ switch (node.kind) {
255
+ case SyntaxKind$1.Identifier: return finish(node, f.createIdentifier(getIdentifierName(node)));
256
+ case SyntaxKind$1.QualifiedName: return finish(node, serializeQualifiedNameAsExpression(f, node));
257
+ }
258
+ return node;
259
+ }
260
+ /**
261
+ * Serializes an qualified name as an expression for decorator type metadata.
262
+ *
263
+ * @param node The qualified name to serialize.
264
+ * @param useFallback A value indicating whether to use logical operators to test for the
265
+ * qualified name at runtime.
266
+ */
267
+ function serializeQualifiedNameAsExpression(f, node) {
268
+ return f.createPropertyAccessExpression(serializeEntityNameAsExpression(f, node.left), node.right);
269
+ }
270
+ function finish(oldNode, newNode) {
271
+ setOriginalNode(newNode, oldNode);
272
+ newNode._original = newNode.original;
273
+ newNode._symbol = oldNode._symbol ?? oldNode.symbol;
274
+ newNode.symbol = newNode._symbol;
275
+ return newNode;
276
+ }
277
+
278
+ //#endregion
279
+ //#region ../../../node_modules/.pnpm/@deepkit+type-compiler@1.0.19_patch_hash=bd438188cbc12e606ed4d519c25ab921a833fbc2d92357_e562d261195ccb1f28e41e80fc823414/node_modules/@deepkit/type-compiler/dist/esm/src/resolver.js
280
+ const { createSourceFile, resolveModuleName, isStringLiteral: isStringLiteral$1, JSDocParsingMode, ScriptTarget: ScriptTarget$1 } = typescript.default;
281
+ function patternMatch(path, patterns, base) {
282
+ const include = patterns.filter((pattern) => pattern[0] !== "!");
283
+ const exclude = patterns.filter((pattern) => pattern[0] === "!").map((pattern) => pattern.substring(1));
284
+ return micromatch.default.isMatch(path, include, { ignore: exclude });
285
+ }
286
+ /**
287
+ * A utility to resolve a module path and its declaration.
288
+ *
289
+ * It automatically reads a SourceFile, binds and caches it.
290
+ */
291
+ var Resolver = class {
292
+ constructor(compilerOptions, host, sourceFiles) {
293
+ this.compilerOptions = compilerOptions;
294
+ this.host = host;
295
+ this.sourceFiles = sourceFiles;
296
+ }
297
+ resolve(from, importOrExportNode) {
298
+ const moduleSpecifier = importOrExportNode.moduleSpecifier;
299
+ if (!moduleSpecifier) return;
300
+ if (!isStringLiteral$1(moduleSpecifier)) return;
301
+ return this.resolveSourceFile(from, moduleSpecifier);
302
+ }
303
+ resolveImpl(modulePath, sourceFile) {
304
+ if (this.host.resolveModuleNameLiterals !== void 0) {
305
+ const results = this.host.resolveModuleNameLiterals([modulePath], sourceFile.fileName, void 0, this.compilerOptions, sourceFile, void 0);
306
+ if (results[0]) return results[0].resolvedModule;
307
+ return;
308
+ }
309
+ if (this.host.resolveModuleNames !== void 0) return this.host.resolveModuleNames([modulePath.text], sourceFile.fileName, void 0, void 0, this.compilerOptions)[0];
310
+ return resolveModuleName(modulePath.text, sourceFile.fileName, this.compilerOptions, this.host).resolvedModule;
311
+ }
312
+ /**
313
+ * Tries to resolve the .ts/d.ts file path for a given module path.
314
+ * Scans relative paths. Looks into package.json "types" and "exports" (with new 4.7 support)
315
+ *
316
+ * @param sourceFile the SourceFile of the file that contains the import. modulePath is relative to that.
317
+ * @param modulePath the x in 'from x'.
318
+ */
319
+ resolveSourceFile(sourceFile, modulePath) {
320
+ const result = this.resolveImpl(modulePath, sourceFile);
321
+ if (!result) return;
322
+ if (!result.resolvedFileName.endsWith(".ts") && !result.resolvedFileName.endsWith(".tsx") && !result.resolvedFileName.endsWith(".d.ts")) return;
323
+ const fileName = result.resolvedFileName;
324
+ if (this.sourceFiles[fileName]) return this.sourceFiles[fileName];
325
+ const source = this.host.readFile(result.resolvedFileName);
326
+ if (!source) return;
327
+ const moduleSourceFile = this.sourceFiles[fileName] = createSourceFile(fileName, source, {
328
+ languageVersion: this.compilerOptions.target || ScriptTarget$1.ES2018,
329
+ jsDocParsingMode: JSDocParsingMode ? JSDocParsingMode.ParseNone : void 0
330
+ }, true);
331
+ this.sourceFiles[fileName] = moduleSourceFile;
332
+ typescript.default.bindSourceFile(moduleSourceFile, this.compilerOptions);
333
+ return moduleSourceFile;
334
+ }
335
+ };
336
+
337
+ //#endregion
338
+ //#region ../../../node_modules/.pnpm/@deepkit+type-compiler@1.0.19_patch_hash=bd438188cbc12e606ed4d519c25ab921a833fbc2d92357_e562d261195ccb1f28e41e80fc823414/node_modules/@deepkit/type-compiler/dist/esm/src/debug.js
339
+ function isDebug(level = 1) {
340
+ const expected = "deepkit" + (level > 1 ? "+".repeat(level - 1) : "");
341
+ return "undefined" !== typeof process && "string" === typeof process.env.DEBUG && process.env.DEBUG.includes(expected);
342
+ }
343
+ /**
344
+ * First level debugging with DEBUG=deepkit
345
+ */
346
+ function debug(...message) {
347
+ if (isDebug(1)) console.debug(...message);
348
+ }
349
+ /**
350
+ * Second level debugging with DEBUG=deepkit+
351
+ */
352
+ function debug2(...message) {
353
+ if (isDebug(2)) console.debug(...message);
354
+ }
355
+
356
+ //#endregion
357
+ //#region ../../../node_modules/.pnpm/@deepkit+type-compiler@1.0.19_patch_hash=bd438188cbc12e606ed4d519c25ab921a833fbc2d92357_e562d261195ccb1f28e41e80fc823414/node_modules/@deepkit/type-compiler/dist/esm/src/config.js
358
+ function isObject(obj) {
359
+ if (!obj) return false;
360
+ return typeof obj === "object" && !Array.isArray(obj);
361
+ }
362
+ const defaultMergeStrategy = "merge";
363
+ /**
364
+ * Read config and parses under TypeScript specification.
365
+ */
366
+ function readTsConfig(parseConfigHost, path$1) {
367
+ const configFile = typescript.default.readConfigFile(path$1, (path$2) => parseConfigHost.readFile(path$2));
368
+ if (configFile.error) {
369
+ debug(`Failed to read tsconfig ${path$1}: ${configFile.error.messageText}`);
370
+ return;
371
+ }
372
+ const parsed = typescript.default.parseJsonConfigFileContent(configFile.config, parseConfigHost, (0, path.dirname)(path$1));
373
+ const ignoredErrors = [18003];
374
+ const softErrors = [18e3];
375
+ const errors = parsed.errors.filter((v) => !ignoredErrors.includes(v.code));
376
+ if (errors.length) debug(`Failed to parse tsconfig ${path$1}: ${parsed.errors.map((v) => v.messageText).join(", ")}`);
377
+ if (errors.filter((v) => !softErrors.includes(v.code)).length) return;
378
+ return Object.assign(configFile.config, { compilerOptions: parsed.options });
379
+ }
380
+ function reflectionModeMatcher(config, filePath) {
381
+ if (Array.isArray(config.exclude)) {
382
+ if (patternMatch(filePath, config.exclude)) return "never";
383
+ }
384
+ if (Array.isArray(config.reflection)) return patternMatch(filePath, config.reflection) ? "default" : "never";
385
+ if (config.reflection === "default" || config.reflection === "explicit") return config.reflection;
386
+ return "never";
387
+ }
388
+ function ensureStringArray(value) {
389
+ if (Array.isArray(value)) return value.map((v) => "" + v);
390
+ if ("string" === typeof value) return [value];
391
+ return [];
392
+ }
393
+ function parseRawMode(mode) {
394
+ if ("boolean" === typeof mode) return mode ? "default" : "never";
395
+ if (mode === "default" || mode === "explicit") return mode;
396
+ return ensureStringArray(mode);
397
+ }
398
+ function resolvePaths(baseDir, paths) {
399
+ if (!paths || !Array.isArray(paths)) return;
400
+ for (let i = 0; i < paths.length; i++) {
401
+ if ("string" !== typeof paths[i]) continue;
402
+ if ((0, path.isAbsolute)(paths[i])) continue;
403
+ let path$3 = paths[i];
404
+ let exclude = false;
405
+ if (path$3.startsWith("!")) {
406
+ exclude = true;
407
+ path$3 = path$3.substring(1);
408
+ }
409
+ if (path$3.startsWith("./") || path$3.includes("/")) path$3 = (0, path.join)(baseDir, path$3);
410
+ path$3 = path$3.replace(/\\/g, "/");
411
+ if (exclude) path$3 = "!" + path$3;
412
+ paths[i] = path$3;
413
+ }
414
+ }
415
+ function appendPaths(strategy = defaultMergeStrategy, parent, existing) {
416
+ if (strategy === "replace") return [...existing || parent];
417
+ if (!existing) return [...parent];
418
+ return [...parent, ...existing];
419
+ }
420
+ function applyConfigValues(existing, parent, baseDir) {
421
+ const parentReflection = isObject(parent.deepkitCompilerOptions) ? parent.deepkitCompilerOptions?.reflection : parent.reflection;
422
+ if (isObject(parent.deepkitCompilerOptions) && "undefined" === typeof existing.mergeStrategy) existing.mergeStrategy = parent.deepkitCompilerOptions.mergeStrategy;
423
+ if ("undefined" !== typeof parentReflection) {
424
+ const next = parseRawMode(parentReflection);
425
+ if ("undefined" === typeof existing.reflection) existing.reflection = next;
426
+ else if ("string" === typeof existing.reflection) {} else if (Array.isArray(next) && Array.isArray(existing.reflection)) existing.reflection = appendPaths(existing.mergeStrategy, next, existing.reflection);
427
+ else if ("string" === typeof next && Array.isArray(existing.reflection)) {}
428
+ }
429
+ if (isObject(parent.deepkitCompilerOptions)) {
430
+ if (`undefined` !== typeof parent.deepkitCompilerOptions.exclude) {
431
+ const next = ensureStringArray(parent.deepkitCompilerOptions.exclude);
432
+ existing.exclude = appendPaths(existing.mergeStrategy, next, existing.exclude);
433
+ }
434
+ }
435
+ resolvePaths(baseDir, existing.reflection);
436
+ resolvePaths(baseDir, existing.exclude);
437
+ if (parent.compilerOptions) {
438
+ if (Object.keys(existing.compilerOptions).length === 0) Object.assign(existing.compilerOptions, parent.compilerOptions);
439
+ }
440
+ existing.extends = parent.extends;
441
+ }
442
+ const defaultExcluded = [
443
+ "lib.dom*.d.ts",
444
+ "*typedarrays.d.ts",
445
+ "lib.webworker*.d.ts",
446
+ "lib.decorator*.d.ts",
447
+ "lib.es2015.proxy.d.ts",
448
+ "lib.es2020.sharedmemory.d.ts",
449
+ "lib.es2015.core.d.ts"
450
+ ];
451
+ function getConfigResolver(cache, host, compilerOptions, sourceFile, tsConfigPath = "") {
452
+ let config = { compilerOptions: {} };
453
+ tsConfigPath = tsConfigPath || ("string" === typeof compilerOptions.configFilePath ? compilerOptions.configFilePath : "");
454
+ if (tsConfigPath) {
455
+ if (cache[tsConfigPath]) return cache[tsConfigPath];
456
+ const configFile = readTsConfig(host, tsConfigPath);
457
+ if (configFile) applyConfigValues(config, configFile, (0, path.dirname)(tsConfigPath));
458
+ } else {
459
+ if (!tsConfigPath && sourceFile) {
460
+ const baseDir = (0, path.dirname)(sourceFile.fileName);
461
+ const configPath = typescript.default.findConfigFile(baseDir, (path$4) => {
462
+ path$4 = (0, path.isAbsolute)(path$4) ? path$4 : (0, path.join)(baseDir, path$4);
463
+ return host.fileExists(path$4);
464
+ });
465
+ debug2(`No tsConfigPath|compilerOptions.configFilePath provided. Manually searching for tsconfig.json in ${baseDir} returned ${configPath}`);
466
+ if (configPath) tsConfigPath = (0, path.isAbsolute)(configPath) ? configPath : (0, path.join)(baseDir, configPath);
467
+ }
468
+ if (tsConfigPath) {
469
+ if (cache[tsConfigPath]) return cache[tsConfigPath];
470
+ const configFile = readTsConfig(host, tsConfigPath);
471
+ if (configFile) applyConfigValues(config, configFile, (0, path.dirname)(tsConfigPath));
472
+ }
473
+ }
474
+ if (tsConfigPath) {
475
+ let basePath = (0, path.dirname)(tsConfigPath);
476
+ let currentConfig = config;
477
+ const seen = /* @__PURE__ */ new Set();
478
+ seen.add(tsConfigPath);
479
+ while (currentConfig.extends) {
480
+ const path$5 = (0, path.join)(basePath, currentConfig.extends);
481
+ if (seen.has(path$5)) break;
482
+ seen.add(path$5);
483
+ const nextConfig = typescript.default.readConfigFile(path$5, (path$6) => host.readFile(path$6));
484
+ if (!nextConfig) break;
485
+ basePath = (0, path.dirname)(path$5);
486
+ applyConfigValues(currentConfig, nextConfig.config, basePath);
487
+ }
488
+ } else throw new Error(`No tsconfig found for ${sourceFile?.fileName}, that is weird. Either provide a tsconfig or compilerOptions.configFilePath`);
489
+ config.exclude = config.exclude ? [...defaultExcluded, ...config.exclude] : [...defaultExcluded];
490
+ config.compilerOptions.configFilePath = tsConfigPath;
491
+ const resolvedConfig = {
492
+ path: tsConfigPath,
493
+ compilerOptions: Object.assign(config.compilerOptions, compilerOptions),
494
+ exclude: config.exclude,
495
+ reflection: config.reflection,
496
+ mergeStrategy: config.mergeStrategy || defaultMergeStrategy
497
+ };
498
+ if (isDebug()) debug(`Found config ${resolvedConfig.path}:\nreflection:`, resolvedConfig.reflection, `\nexclude:`, resolvedConfig.exclude, `\npaths:`, resolvedConfig.compilerOptions.paths);
499
+ const match = (path$7) => {
500
+ return {
501
+ mode: reflectionModeMatcher(config, path$7),
502
+ tsConfigPath
503
+ };
504
+ };
505
+ return cache[tsConfigPath] = {
506
+ config: resolvedConfig,
507
+ match
508
+ };
509
+ }
510
+
511
+ //#endregion
512
+ //#region ../../../node_modules/.pnpm/@deepkit+type-compiler@1.0.19_patch_hash=bd438188cbc12e606ed4d519c25ab921a833fbc2d92357_e562d261195ccb1f28e41e80fc823414/node_modules/@deepkit/type-compiler/dist/esm/src/compiler.js
513
+ const { visitEachChild, visitNode, isPropertyAssignment, isArrayTypeNode, isArrowFunction, isBlock, isCallExpression, isCallSignatureDeclaration, isClassDeclaration, isClassExpression, isConstructorDeclaration, isConstructorTypeNode, isConstructSignatureDeclaration, isEnumDeclaration, isExportDeclaration, isExpression, isExpressionWithTypeArguments, isFunctionDeclaration, isFunctionExpression, isFunctionLike, isIdentifier, isImportClause, isImportDeclaration, isImportSpecifier, isInferTypeNode, isInterfaceDeclaration, isMethodDeclaration, isMethodSignature, isModuleDeclaration, isNamedExports, isNamedTupleMember, isNewExpression, isObjectLiteralExpression, isOptionalTypeNode, isParameter, isParenthesizedExpression, isParenthesizedTypeNode, isPropertyAccessExpression, isQualifiedName, isSourceFile, isStringLiteral, isTypeAliasDeclaration, isTypeLiteralNode, isTypeParameterDeclaration, isTypeQueryNode, isTypeReferenceNode, isUnionTypeNode, isExpressionStatement, isVariableDeclaration, getEffectiveConstraintOfTypeParameter, addSyntheticLeadingComment, createCompilerHost, createPrinter, escapeLeadingUnderscores, EmitHint, NodeFlags, SyntaxKind, ScriptTarget, ModifierFlags, ScriptKind } = typescript.default;
514
+ function encodeOps(ops) {
515
+ return ops.map((v) => String.fromCharCode(v + 33)).join("");
516
+ }
517
+ function filterUndefined(object) {
518
+ return Object.fromEntries(Object.entries(object).filter(([, v]) => v !== void 0));
519
+ }
520
+ const packSizeByte = 6;
521
+ /**
522
+ * It can't be more ops than this given number
523
+ */
524
+ const packSize = 2 ** 6;
525
+ const OPs = {
526
+ [_deepkit_type_spec.ReflectionOp.literal]: { params: 1 },
527
+ [_deepkit_type_spec.ReflectionOp.classReference]: { params: 1 },
528
+ [_deepkit_type_spec.ReflectionOp.propertySignature]: { params: 1 },
529
+ [_deepkit_type_spec.ReflectionOp.property]: { params: 1 },
530
+ [_deepkit_type_spec.ReflectionOp.jump]: { params: 1 },
531
+ [_deepkit_type_spec.ReflectionOp.enum]: { params: 0 },
532
+ [_deepkit_type_spec.ReflectionOp.enumMember]: { params: 1 },
533
+ [_deepkit_type_spec.ReflectionOp.typeParameter]: { params: 1 },
534
+ [_deepkit_type_spec.ReflectionOp.typeParameterDefault]: { params: 1 },
535
+ [_deepkit_type_spec.ReflectionOp.mappedType]: { params: 2 },
536
+ [_deepkit_type_spec.ReflectionOp.call]: { params: 1 },
537
+ [_deepkit_type_spec.ReflectionOp.inline]: { params: 1 },
538
+ [_deepkit_type_spec.ReflectionOp.inlineCall]: { params: 2 },
539
+ [_deepkit_type_spec.ReflectionOp.loads]: { params: 2 },
540
+ [_deepkit_type_spec.ReflectionOp.extends]: { params: 0 },
541
+ [_deepkit_type_spec.ReflectionOp.infer]: { params: 2 },
542
+ [_deepkit_type_spec.ReflectionOp.defaultValue]: { params: 1 },
543
+ [_deepkit_type_spec.ReflectionOp.parameter]: { params: 1 },
544
+ [_deepkit_type_spec.ReflectionOp.method]: { params: 1 },
545
+ [_deepkit_type_spec.ReflectionOp.function]: { params: 1 },
546
+ [_deepkit_type_spec.ReflectionOp.description]: { params: 1 },
547
+ [_deepkit_type_spec.ReflectionOp.numberBrand]: { params: 1 },
548
+ [_deepkit_type_spec.ReflectionOp.typeof]: { params: 1 },
549
+ [_deepkit_type_spec.ReflectionOp.classExtends]: { params: 1 },
550
+ [_deepkit_type_spec.ReflectionOp.distribute]: { params: 1 },
551
+ [_deepkit_type_spec.ReflectionOp.jumpCondition]: { params: 2 },
552
+ [_deepkit_type_spec.ReflectionOp.typeName]: { params: 1 },
553
+ [_deepkit_type_spec.ReflectionOp.implements]: { params: 1 }
554
+ };
555
+ function debugPackStruct(sourceFile, forType, pack) {
556
+ const items = [];
557
+ for (let i = 0; i < pack.ops.length; i++) {
558
+ const op = pack.ops[i];
559
+ const opInfo = OPs[op];
560
+ items.push(_deepkit_type_spec.ReflectionOp[op]);
561
+ if (opInfo && opInfo.params > 0) for (let j = 0; j < opInfo.params; j++) {
562
+ const address = pack.ops[++i];
563
+ items.push(address);
564
+ }
565
+ }
566
+ const printer = createPrinter();
567
+ const stack = [];
568
+ for (const s of pack.stack) if ("object" === typeof s && "getText" in s) stack.push(printer.printNode(EmitHint.Unspecified, s, sourceFile));
569
+ else stack.push(JSON.stringify(s));
570
+ console.log(stack.join(","), "|", ...items);
571
+ }
572
+ function findVariable(frame, name, frameOffset = 0) {
573
+ const variable = frame.variables.find((v) => v.name === name);
574
+ if (variable) return {
575
+ frameOffset,
576
+ stackIndex: variable.index
577
+ };
578
+ if (frame.previous) return findVariable(frame.previous, name, frameOffset + 1);
579
+ }
580
+ function findConditionalFrame(frame) {
581
+ if (frame.conditional) return frame;
582
+ if (frame.previous) return findConditionalFrame(frame.previous);
583
+ }
584
+ var CompilerProgram = class {
585
+ constructor(forNode, sourceFile) {
586
+ this.forNode = forNode;
587
+ this.sourceFile = sourceFile;
588
+ this.ops = [];
589
+ this.stack = [];
590
+ this.mainOffset = 0;
591
+ this.stackPosition = 0;
592
+ this.frame = {
593
+ variables: [],
594
+ opIndex: 0
595
+ };
596
+ this.activeCoRoutines = [];
597
+ this.coRoutines = [];
598
+ this.resolveFunctionParameters = /* @__PURE__ */ new Map();
599
+ }
600
+ buildPackStruct() {
601
+ const ops = [...this.ops];
602
+ if (this.coRoutines.length) for (let i = this.coRoutines.length - 1; i >= 0; i--) ops.unshift(...this.coRoutines[i].ops);
603
+ if (this.mainOffset) ops.unshift(_deepkit_type_spec.ReflectionOp.jump, this.mainOffset);
604
+ return {
605
+ ops,
606
+ stack: this.stack
607
+ };
608
+ }
609
+ isEmpty() {
610
+ return this.ops.length === 0;
611
+ }
612
+ pushConditionalFrame() {
613
+ const frame = this.pushFrame();
614
+ frame.conditional = true;
615
+ }
616
+ pushStack(item) {
617
+ this.stack.push(item);
618
+ return this.stackPosition++;
619
+ }
620
+ pushCoRoutine() {
621
+ this.pushFrame(true);
622
+ this.activeCoRoutines.push({ ops: [] });
623
+ }
624
+ popCoRoutine() {
625
+ const coRoutine = this.activeCoRoutines.pop();
626
+ if (!coRoutine) throw new Error("No active co routine found");
627
+ this.popFrameImplicit();
628
+ if (this.mainOffset === 0) this.mainOffset = 2;
629
+ const startIndex = this.mainOffset;
630
+ coRoutine.ops.push(_deepkit_type_spec.ReflectionOp.return);
631
+ this.coRoutines.push(coRoutine);
632
+ this.mainOffset += coRoutine.ops.length;
633
+ return startIndex;
634
+ }
635
+ pushOp(...ops) {
636
+ for (const op of ops) if ("number" !== typeof op) throw new Error("No valid OP added");
637
+ if (this.activeCoRoutines.length) {
638
+ this.activeCoRoutines[this.activeCoRoutines.length - 1].ops.push(...ops);
639
+ return;
640
+ }
641
+ this.ops.push(...ops);
642
+ }
643
+ pushOpAtFrame(frame, ...ops) {
644
+ if (this.activeCoRoutines.length) {
645
+ this.activeCoRoutines[this.activeCoRoutines.length - 1].ops.splice(frame.opIndex, 0, ...ops);
646
+ return;
647
+ }
648
+ this.ops.splice(frame.opIndex, 0, ...ops);
649
+ }
650
+ /**
651
+ * Returns the index of the `entry` in the stack, if already exists. If not, add it, and return that new index.
652
+ */
653
+ findOrAddStackEntry(entry) {
654
+ const index = this.stack.indexOf(entry);
655
+ if (index !== -1) return index;
656
+ return this.pushStack(entry);
657
+ }
658
+ /**
659
+ * To make room for a stack entry expected on the stack as input for example.
660
+ */
661
+ increaseStackPosition() {
662
+ return this.stackPosition++;
663
+ }
664
+ resolveFunctionParametersIncrease(fn) {
665
+ this.resolveFunctionParameters.set(fn, (this.resolveFunctionParameters.get(fn) || 0) + 1);
666
+ }
667
+ resolveFunctionParametersDecrease(fn) {
668
+ this.resolveFunctionParameters.set(fn, (this.resolveFunctionParameters.get(fn) || 1) - 1);
669
+ }
670
+ isResolveFunctionParameters(fn) {
671
+ return (this.resolveFunctionParameters.get(fn) || 0) > 0;
672
+ }
673
+ /**
674
+ *
675
+ * Each pushFrame() call needs a popFrame() call.
676
+ */
677
+ pushFrame(implicit = false) {
678
+ if (!implicit) this.pushOp(_deepkit_type_spec.ReflectionOp.frame);
679
+ const opIndex = this.activeCoRoutines.length ? this.activeCoRoutines[this.activeCoRoutines.length - 1].ops.length : this.ops.length;
680
+ this.frame = {
681
+ previous: this.frame,
682
+ variables: [],
683
+ opIndex
684
+ };
685
+ return this.frame;
686
+ }
687
+ findConditionalFrame() {
688
+ return findConditionalFrame(this.frame);
689
+ }
690
+ /**
691
+ * Remove stack without doing it as OP in the processor. Some other command calls popFrame() already, which makes popFrameImplicit() an implicit popFrame.
692
+ * e.g. union, class, etc. all call popFrame(). the current CompilerProgram needs to be aware of that, which this function is for.
693
+ */
694
+ popFrameImplicit() {
695
+ if (this.frame.previous) this.frame = this.frame.previous;
696
+ }
697
+ moveFrame() {
698
+ this.pushOp(_deepkit_type_spec.ReflectionOp.moveFrame);
699
+ if (this.frame.previous) this.frame = this.frame.previous;
700
+ }
701
+ pushVariable(name, frame = this.frame) {
702
+ this.pushOpAtFrame(frame, _deepkit_type_spec.ReflectionOp.var);
703
+ frame.variables.push({
704
+ index: frame.variables.length,
705
+ name
706
+ });
707
+ return frame.variables.length - 1;
708
+ }
709
+ pushTemplateParameter(name, withDefault = false) {
710
+ this.pushOp(withDefault ? _deepkit_type_spec.ReflectionOp.typeParameterDefault : _deepkit_type_spec.ReflectionOp.typeParameter, this.findOrAddStackEntry(name));
711
+ this.frame.variables.push({
712
+ index: this.frame.variables.length,
713
+ name
714
+ });
715
+ return this.frame.variables.length - 1;
716
+ }
717
+ findVariable(name, frame = this.frame) {
718
+ return findVariable(frame, name);
719
+ }
720
+ };
721
+ function getAssignTypeExpression(call) {
722
+ if (isParenthesizedExpression(call) && isCallExpression(call.expression)) call = call.expression;
723
+ if (isCallExpression(call) && isIdentifier(call.expression) && getIdentifierName(call.expression) === "__assignType" && call.arguments.length > 0) return call.arguments[0];
724
+ }
725
+ function getReceiveTypeParameter(type) {
726
+ if (isUnionTypeNode(type)) for (const t of type.types) {
727
+ const rfn = getReceiveTypeParameter(t);
728
+ if (rfn) return rfn;
729
+ }
730
+ else if (isTypeReferenceNode(type) && isIdentifier(type.typeName) && getIdentifierName(type.typeName) === "ReceiveType" && !!type.typeArguments && type.typeArguments.length === 1) return type;
731
+ }
732
+ var Cache = class {
733
+ constructor() {
734
+ this.resolver = {};
735
+ this.sourceFiles = {};
736
+ }
737
+ /**
738
+ * Signals the cache to check if it needs to be cleared.
739
+ */
740
+ tick() {
741
+ if (Object.keys(this.sourceFiles).length > 300) this.sourceFiles = {};
742
+ }
743
+ };
744
+ /**
745
+ * Read the TypeScript AST and generate pack struct (instructions + pre-defined stack).
746
+ *
747
+ * This transformer extracts type and add the encoded (so its small and low overhead) at classes and functions as property.
748
+ *
749
+ * Deepkit/type can then extract and decode them on-demand.
750
+ */
751
+ var ReflectionTransformer = class {
752
+ constructor(context, cache = new Cache()) {
753
+ this.context = context;
754
+ this.cache = cache;
755
+ this.embedAssignType = false;
756
+ /**
757
+ * Types added to this map will get a type program directly under it.
758
+ * This is for types used in the very same file.
759
+ */
760
+ this.compileDeclarations = /* @__PURE__ */ new Map();
761
+ /**
762
+ * Types added to this map will get a type program at the top root level of the program.
763
+ * This is for imported types, which need to be inlined into the current file, as we do not emit type imports (TS will omit them).
764
+ */
765
+ this.embedDeclarations = /* @__PURE__ */ new Map();
766
+ /**
767
+ * When a node was embedded or compiled (from the maps above), we store it here to know to not add it again.
768
+ */
769
+ this.compiledDeclarations = /* @__PURE__ */ new Set();
770
+ this.addImports = [];
771
+ this.additionalImports = /* @__PURE__ */ new Map();
772
+ this.overriddenHost = false;
773
+ this.knownClasses = {
774
+ "Int8Array": _deepkit_type_spec.ReflectionOp.int8Array,
775
+ "Uint8Array": _deepkit_type_spec.ReflectionOp.uint8Array,
776
+ "Uint8ClampedArray": _deepkit_type_spec.ReflectionOp.uint8ClampedArray,
777
+ "Int16Array": _deepkit_type_spec.ReflectionOp.int16Array,
778
+ "Uint16Array": _deepkit_type_spec.ReflectionOp.uint16Array,
779
+ "Int32Array": _deepkit_type_spec.ReflectionOp.int32Array,
780
+ "Uint32Array": _deepkit_type_spec.ReflectionOp.uint32Array,
781
+ "Float32Array": _deepkit_type_spec.ReflectionOp.float32Array,
782
+ "Float64Array": _deepkit_type_spec.ReflectionOp.float64Array,
783
+ "ArrayBuffer": _deepkit_type_spec.ReflectionOp.arrayBuffer,
784
+ "BigInt64Array": _deepkit_type_spec.ReflectionOp.bigInt64Array,
785
+ "Date": _deepkit_type_spec.ReflectionOp.date,
786
+ "RegExp": _deepkit_type_spec.ReflectionOp.regexp,
787
+ "String": _deepkit_type_spec.ReflectionOp.string,
788
+ "Number": _deepkit_type_spec.ReflectionOp.number,
789
+ "BigInt": _deepkit_type_spec.ReflectionOp.bigint,
790
+ "Boolean": _deepkit_type_spec.ReflectionOp.boolean
791
+ };
792
+ this.f = context.factory;
793
+ this.nodeConverter = new NodeConverter(this.f);
794
+ this.compilerOptions = { ...filterUndefined(context.getCompilerOptions()) };
795
+ this.host = createCompilerHost(this.compilerOptions);
796
+ this.resolver = new Resolver(this.compilerOptions, this.host, this.cache.sourceFiles);
797
+ this.parseConfigHost = {
798
+ useCaseSensitiveFileNames: true,
799
+ fileExists: (path) => this.host.fileExists(path),
800
+ readFile: (path) => this.host.readFile(path),
801
+ readDirectory: (path, extensions, exclude, include, depth) => {
802
+ if (!this.host.readDirectory) return [];
803
+ return this.host.readDirectory(path, extensions || [], exclude, include || [], depth);
804
+ }
805
+ };
806
+ {
807
+ const T = this.f.createIdentifier("T");
808
+ const Options = this.f.createIdentifier("Options");
809
+ this.intrinsicMetaDeclaration = this.f.createTypeAliasDeclaration([], "TypeAnnotation", [this.f.createTypeParameterDeclaration([], T), this.f.createTypeParameterDeclaration([], Options, void 0, this.f.createTypeReferenceNode("never"))], this.f.createTypeLiteralNode([this.f.createPropertySignature(void 0, "__meta", this.f.createToken(SyntaxKind.QuestionToken), this.f.createIntersectionTypeNode([this.f.createTypeReferenceNode("never"), this.f.createTupleTypeNode([this.f.createTypeReferenceNode(T), this.f.createTypeReferenceNode(Options)])]))]));
810
+ }
811
+ }
812
+ forHost(host) {
813
+ this.host = host;
814
+ this.resolver.host = host;
815
+ this.overriddenHost = true;
816
+ return this;
817
+ }
818
+ withReflection(config) {
819
+ const match = (path) => {
820
+ return {
821
+ mode: reflectionModeMatcher(config, path),
822
+ tsConfigPath: ""
823
+ };
824
+ };
825
+ const configResolver = {
826
+ ...config,
827
+ path: "",
828
+ mergeStrategy: "replace",
829
+ compilerOptions: this.compilerOptions
830
+ };
831
+ this.overriddenConfigResolver = {
832
+ config: configResolver,
833
+ match
834
+ };
835
+ return this;
836
+ }
837
+ transformBundle(node) {
838
+ return node;
839
+ }
840
+ getTempResultIdentifier() {
841
+ if (this.tempResultIdentifier) return this.tempResultIdentifier;
842
+ const locals = isNodeWithLocals(this.sourceFile) ? this.sourceFile.locals : void 0;
843
+ if (locals) {
844
+ let found = "Ωr";
845
+ for (let i = 0;; i++) {
846
+ found = "Ωr" + (i ? i : "");
847
+ if (!locals.has(escapeLeadingUnderscores(found))) break;
848
+ }
849
+ this.tempResultIdentifier = this.f.createIdentifier(found);
850
+ } else this.tempResultIdentifier = this.f.createIdentifier("Ωr");
851
+ return this.tempResultIdentifier;
852
+ }
853
+ getConfigResolver(sourceFile) {
854
+ if (this.overriddenConfigResolver) return this.overriddenConfigResolver;
855
+ return getConfigResolver(this.cache.resolver, this.parseConfigHost, this.compilerOptions, sourceFile);
856
+ }
857
+ getReflectionConfig(sourceFile) {
858
+ return this.getConfigResolver(sourceFile).match(sourceFile.fileName);
859
+ }
860
+ isWithReflection(sourceFile, node) {
861
+ const mode = this.getExplicitReflectionMode(sourceFile, node);
862
+ if (mode === false) return false;
863
+ if (!sourceFile) return true;
864
+ const reflection = this.getReflectionConfig(sourceFile);
865
+ if (reflection.mode === "explicit") return mode === true;
866
+ return reflection.mode === "default";
867
+ }
868
+ transformSourceFile(sourceFile) {
869
+ this.sourceFile = sourceFile;
870
+ if (sourceFile.scriptKind !== ScriptKind.TS && sourceFile.scriptKind !== ScriptKind.TSX) return sourceFile;
871
+ if (sourceFile.deepkitTransformed) return sourceFile;
872
+ this.embedAssignType = false;
873
+ this.addImports = [];
874
+ this.additionalImports.clear();
875
+ const start = Date.now();
876
+ const configResolver = this.getConfigResolver(sourceFile);
877
+ const reflection = configResolver.match(sourceFile.fileName);
878
+ Object.assign(this.compilerOptions, configResolver.config.compilerOptions);
879
+ if (reflection.mode === "never") {
880
+ debug(`Transform file with reflection=${reflection.mode} took ${Date.now() - start}ms (${this.getModuleType()}) ${sourceFile.fileName} via config ${reflection.tsConfigPath || "none"}.`);
881
+ return sourceFile;
882
+ }
883
+ if (!sourceFile.locals) typescript.default.bindSourceFile(sourceFile, this.compilerOptions);
884
+ if (sourceFile.kind !== SyntaxKind.SourceFile) {
885
+ if ("undefined" === typeof require) throw new Error(`Invalid TypeScript library imported. SyntaxKind different ${sourceFile.kind} !== ${SyntaxKind.SourceFile}.`);
886
+ const path = require.resolve("typescript");
887
+ throw new Error(`Invalid TypeScript library imported. SyntaxKind different ${sourceFile.kind} !== ${SyntaxKind.SourceFile}. typescript package path: ${path}`);
888
+ }
889
+ const visitor = (node) => {
890
+ node = visitEachChild(node, visitor, this.context);
891
+ if (isInterfaceDeclaration(node) || isTypeAliasDeclaration(node) || isEnumDeclaration(node)) {
892
+ if (this.isWithReflection(sourceFile, node)) this.compileDeclarations.set(node, {
893
+ name: node.name,
894
+ sourceFile: this.sourceFile
895
+ });
896
+ }
897
+ if (isMethodDeclaration(node) && node.parent && node.body && isObjectLiteralExpression(node.parent)) {
898
+ let valid = true;
899
+ if (node.name.kind === SyntaxKind.Identifier && getIdentifierName(node.name) === "default") valid = false;
900
+ if (valid) {
901
+ const method = this.decorateFunctionExpression(this.f.createFunctionExpression(node.modifiers, node.asteriskToken, isIdentifier(node.name) ? node.name : void 0, node.typeParameters, node.parameters, node.type, node.body));
902
+ node = this.f.createPropertyAssignment(node.name, method);
903
+ }
904
+ }
905
+ if (isClassDeclaration(node)) return this.decorateClass(sourceFile, node);
906
+ else if (isParameter(node) && node.parent && node.type) {
907
+ const typeParameters = isConstructorDeclaration(node.parent) ? node.parent.parent.typeParameters : node.parent.typeParameters;
908
+ if (!typeParameters) return node;
909
+ const receiveType = getReceiveTypeParameter(node.type);
910
+ if (receiveType && receiveType.typeArguments) {
911
+ const first = receiveType.typeArguments[0];
912
+ if (first && isTypeReferenceNode(first) && isIdentifier(first.typeName)) {
913
+ const name = getIdentifierName(first.typeName);
914
+ const index = typeParameters.findIndex((v) => getIdentifierName(v.name) === name);
915
+ let container = this.f.createIdentifier("globalThis");
916
+ if (isArrowFunction(node.parent)) {
917
+ const next = this.getArrowFunctionΩPropertyAccessIdentifier(node.parent);
918
+ if (!next) return node;
919
+ container = next;
920
+ } else if ((isFunctionDeclaration(node.parent) || isFunctionExpression(node.parent)) && node.parent.name) container = node.parent.name;
921
+ else if (isMethodDeclaration(node.parent) && isIdentifier(node.parent.name)) container = this.f.createPropertyAccessExpression(this.f.createIdentifier("this"), node.parent.name);
922
+ else if (isConstructorDeclaration(node.parent)) container = this.f.createPropertyAccessExpression(this.f.createIdentifier("this"), "constructor");
923
+ return this.f.updateParameterDeclaration(node, node.modifiers, node.dotDotDotToken, node.name, node.questionToken, receiveType, this.f.createElementAccessChain(this.f.createPropertyAccessExpression(container, this.f.createIdentifier("Ω")), this.f.createToken(SyntaxKind.QuestionDotToken), this.f.createNumericLiteral(index)));
924
+ }
925
+ }
926
+ } else if (isClassExpression(node)) return this.decorateClass(sourceFile, node);
927
+ else if (isFunctionExpression(node)) return this.decorateFunctionExpression(this.injectResetΩ(node));
928
+ else if (isFunctionDeclaration(node)) return this.decorateFunctionDeclaration(this.injectResetΩ(node));
929
+ else if (isMethodDeclaration(node) || isConstructorDeclaration(node)) return this.injectResetΩ(node);
930
+ else if (isArrowFunction(node)) return this.decorateArrowFunction(this.injectResetΩ(node));
931
+ else if ((isNewExpression(node) || isCallExpression(node)) && node.typeArguments && node.typeArguments.length > 0) {
932
+ if (isCallExpression(node)) {
933
+ if (isIdentifier(node.expression) && [
934
+ "valuesOf",
935
+ "propertiesOf",
936
+ "typeOf"
937
+ ].includes(getIdentifierName(node.expression))) {
938
+ const args = [...node.arguments];
939
+ if (!args.length) args.push(this.f.createArrayLiteralExpression());
940
+ const type = this.getTypeOfType(node.typeArguments[0]);
941
+ if (!type) return node;
942
+ args.push(type);
943
+ return this.f.updateCallExpression(node, node.expression, node.typeArguments, this.f.createNodeArray(args));
944
+ }
945
+ }
946
+ const expressionToCheck = getAssignTypeExpression(node.expression) || node.expression;
947
+ if (isArrowFunction(expressionToCheck)) return node;
948
+ const typeExpressions = [];
949
+ for (const a of node.typeArguments) {
950
+ const type = this.getTypeOfType(a);
951
+ typeExpressions.push(type || this.f.createIdentifier("undefined"));
952
+ }
953
+ let container = this.f.createIdentifier("globalThis");
954
+ if (isIdentifier(node.expression)) container = node.expression;
955
+ else if (isPropertyAccessExpression(node.expression)) container = node.expression;
956
+ const assignQ = this.f.createBinaryExpression(this.f.createPropertyAccessExpression(container, "Ω"), this.f.createToken(SyntaxKind.EqualsToken), this.f.createArrayLiteralExpression(typeExpressions));
957
+ const update = isNewExpression(node) ? this.f.updateNewExpression : this.f.updateCallExpression;
958
+ if (isPropertyAccessExpression(node.expression)) {
959
+ if (isCallExpression(node.expression.expression)) {
960
+ const r = this.getTempResultIdentifier();
961
+ const assignQ = this.f.createBinaryExpression(this.f.createPropertyAccessExpression(this.f.createPropertyAccessExpression(r, node.expression.name), "Ω"), this.f.createToken(SyntaxKind.EqualsToken), this.f.createArrayLiteralExpression(typeExpressions));
962
+ return update(node, this.f.createPropertyAccessExpression(this.f.createParenthesizedExpression(this.f.createBinaryExpression(this.f.createBinaryExpression(this.f.createBinaryExpression(r, this.f.createToken(typescript.default.SyntaxKind.EqualsToken), node.expression.expression), this.f.createToken(typescript.default.SyntaxKind.CommaToken), assignQ), this.f.createToken(typescript.default.SyntaxKind.CommaToken), r)), node.expression.name), node.typeArguments, node.arguments);
963
+ } else if (isParenthesizedExpression(node.expression.expression)) {
964
+ const r = this.getTempResultIdentifier();
965
+ const assignQ = this.f.createBinaryExpression(this.f.createPropertyAccessExpression(this.f.createPropertyAccessExpression(r, node.expression.name), "Ω"), this.f.createToken(SyntaxKind.EqualsToken), this.f.createArrayLiteralExpression(typeExpressions));
966
+ const updatedNode = update(node, this.f.updatePropertyAccessExpression(node.expression, this.f.updateParenthesizedExpression(node.expression.expression, this.f.createBinaryExpression(this.f.createBinaryExpression(this.f.createBinaryExpression(r, this.f.createToken(SyntaxKind.EqualsToken), node.expression.expression.expression), this.f.createToken(SyntaxKind.CommaToken), assignQ), this.f.createToken(SyntaxKind.CommaToken), r)), node.expression.name), node.typeArguments, node.arguments);
967
+ return this.f.createParenthesizedExpression(updatedNode);
968
+ }
969
+ }
970
+ return this.f.createParenthesizedExpression(this.f.createBinaryExpression(assignQ, this.f.createToken(SyntaxKind.CommaToken), node));
971
+ }
972
+ return node;
973
+ };
974
+ this.sourceFile = visitNode(this.sourceFile, visitor);
975
+ const newTopStatements = [];
976
+ while (true) {
977
+ let allCompiled = true;
978
+ for (const d of this.compileDeclarations.values()) {
979
+ if (d.compiled) continue;
980
+ allCompiled = false;
981
+ break;
982
+ }
983
+ if (this.embedDeclarations.size === 0 && allCompiled) break;
984
+ for (const [node, d] of [...this.compileDeclarations.entries()]) {
985
+ if (d.compiled) continue;
986
+ d.compiled = this.createProgramVarFromNode(node, d.name, this.sourceFile);
987
+ }
988
+ if (this.embedDeclarations.size) {
989
+ for (const node of this.embedDeclarations.keys()) this.compiledDeclarations.add(node);
990
+ const entries = Array.from(this.embedDeclarations.entries());
991
+ this.embedDeclarations.clear();
992
+ for (const [node, d] of entries) newTopStatements.push(...this.createProgramVarFromNode(node, d.name, d.sourceFile));
993
+ }
994
+ }
995
+ const compileDeclarations = (node) => {
996
+ node = visitEachChild(node, compileDeclarations, this.context);
997
+ if (isTypeAliasDeclaration(node) || isInterfaceDeclaration(node) || isEnumDeclaration(node)) {
998
+ const d = this.compileDeclarations.get(node);
999
+ if (!d) return node;
1000
+ this.compileDeclarations.delete(node);
1001
+ this.compiledDeclarations.add(node);
1002
+ if (d.compiled) return [...d.compiled, node];
1003
+ }
1004
+ return node;
1005
+ };
1006
+ this.sourceFile = visitNode(this.sourceFile, compileDeclarations);
1007
+ if (this.addImports.length) {
1008
+ const handledIdentifier = [];
1009
+ const importMap = /* @__PURE__ */ new Map();
1010
+ for (const imp of this.addImports) {
1011
+ if (handledIdentifier.includes(getIdentifierName(imp.identifier))) continue;
1012
+ handledIdentifier.push(getIdentifierName(imp.identifier));
1013
+ let arr = importMap.get(imp.importDeclaration);
1014
+ if (!arr) {
1015
+ arr = [];
1016
+ importMap.set(imp.importDeclaration, arr);
1017
+ }
1018
+ arr.push(imp.identifier);
1019
+ }
1020
+ for (const [importDeclaration, identifiers] of importMap.entries()) {
1021
+ if (this.additionalImports.has(importDeclaration)) throw new Error("Internal error: additional import already exists");
1022
+ if (this.getModuleType() === "cjs") {
1023
+ const varDeclaration = this.f.createVariableStatement(void 0, this.f.createVariableDeclarationList([this.f.createVariableDeclaration(this.f.createObjectBindingPattern(identifiers.map((identifier) => this.f.createBindingElement(void 0, void 0, identifier, void 0))), void 0, void 0, this.f.createCallExpression(this.f.createIdentifier("require"), void 0, [importDeclaration.moduleSpecifier]))], typescript.default.NodeFlags.None));
1024
+ const typeDeclWithComment = addSyntheticLeadingComment(varDeclaration, SyntaxKind.MultiLineCommentTrivia, "@ts-ignore", true);
1025
+ this.additionalImports.set(importDeclaration, typeDeclWithComment);
1026
+ } else {
1027
+ const namedImports = this.f.createNamedImports(identifiers.map((identifier) => this.f.createImportSpecifier(false, void 0, identifier)));
1028
+ const importStatement = this.f.createImportDeclaration(void 0, this.f.createImportClause(false, void 0, namedImports), importDeclaration.moduleSpecifier);
1029
+ const typeDeclWithComment = addSyntheticLeadingComment(importStatement, SyntaxKind.MultiLineCommentTrivia, "@ts-ignore", true);
1030
+ this.additionalImports.set(importDeclaration, typeDeclWithComment);
1031
+ }
1032
+ }
1033
+ }
1034
+ if (this.embedAssignType) {
1035
+ const assignType = this.f.createFunctionDeclaration(void 0, void 0, this.f.createIdentifier("__assignType"), void 0, [this.f.createParameterDeclaration(void 0, void 0, this.f.createIdentifier("fn"), void 0, void 0, void 0), this.f.createParameterDeclaration(void 0, void 0, this.f.createIdentifier("args"), void 0, void 0, void 0)], void 0, this.f.createBlock([this.f.createExpressionStatement(this.f.createBinaryExpression(this.f.createPropertyAccessExpression(this.f.createIdentifier("fn"), this.f.createIdentifier("__type")), this.f.createToken(SyntaxKind.EqualsToken), this.f.createIdentifier("args"))), this.f.createReturnStatement(this.f.createIdentifier("fn"))], true));
1036
+ newTopStatements.push(assignType);
1037
+ }
1038
+ if (this.tempResultIdentifier) newTopStatements.push(this.f.createVariableStatement(void 0, this.f.createVariableDeclarationList([this.f.createVariableDeclaration(this.tempResultIdentifier, void 0, void 0, void 0)], typescript.default.NodeFlags.None)));
1039
+ const indexOfFirstLiteralExpression = this.sourceFile.statements.findIndex((v) => isExpressionStatement(v) && isStringLiteral(v.expression));
1040
+ const newStatements = indexOfFirstLiteralExpression === -1 ? [...newTopStatements, ...this.attachAdditionalStatements(this.sourceFile.statements)] : [
1041
+ ...this.sourceFile.statements.slice(0, indexOfFirstLiteralExpression + 1),
1042
+ ...newTopStatements,
1043
+ ...this.attachAdditionalStatements(this.sourceFile.statements.slice(indexOfFirstLiteralExpression + 1))
1044
+ ];
1045
+ this.sourceFile = this.f.updateSourceFile(this.sourceFile, newStatements);
1046
+ const took = Date.now() - start;
1047
+ debug(`Transform file with reflection=${reflection.mode} took ${took}ms (${this.getModuleType()}) ${sourceFile.fileName} via config ${reflection.tsConfigPath || "none"}.`);
1048
+ this.sourceFile.deepkitTransformed = true;
1049
+ return this.sourceFile;
1050
+ }
1051
+ attachAdditionalStatements(statements) {
1052
+ const result = [];
1053
+ for (const statement of statements) {
1054
+ if (isImportDeclaration(statement) || (0, typescript.isJSDocImportTag)(statement)) {
1055
+ const additional = this.additionalImports.get(statement);
1056
+ if (additional) result.push(additional);
1057
+ }
1058
+ result.push(statement);
1059
+ }
1060
+ return result;
1061
+ }
1062
+ getModuleType() {
1063
+ if (this.compilerOptions.module === typescript.default.ModuleKind.Node16 || this.compilerOptions.module === typescript.default.ModuleKind.NodeNext) {
1064
+ if (this.sourceFile.impliedNodeFormat === typescript.default.ModuleKind.ESNext) return "esm";
1065
+ return "cjs";
1066
+ }
1067
+ return this.compilerOptions.module === typescript.default.ModuleKind.CommonJS ? "cjs" : "esm";
1068
+ }
1069
+ getArrowFunctionΩPropertyAccessIdentifier(node) {
1070
+ let { parent } = node.original || node;
1071
+ if (isVariableDeclaration(parent) && isIdentifier(parent.name)) return parent.name;
1072
+ else if (isPropertyAssignment(parent) && isIdentifier(parent.name)) {
1073
+ const names = [];
1074
+ while (parent) if (isObjectLiteralExpression(parent)) parent = parent.parent;
1075
+ else if (isVariableDeclaration(parent)) {
1076
+ names.unshift(getIdentifierName(parent.name));
1077
+ break;
1078
+ } else if (isIdentifier(parent.name)) {
1079
+ names.unshift(getIdentifierName(parent.name));
1080
+ parent = parent.parent;
1081
+ } else return;
1082
+ return this.f.createIdentifier(names.join("."));
1083
+ }
1084
+ }
1085
+ injectResetΩ(node) {
1086
+ let hasReceiveType = false;
1087
+ for (const param of node.parameters) if (param.type && getReceiveTypeParameter(param.type)) hasReceiveType = true;
1088
+ if (!hasReceiveType) return node;
1089
+ let container = this.f.createIdentifier("globalThis");
1090
+ if (isArrowFunction(node)) {
1091
+ const next = this.getArrowFunctionΩPropertyAccessIdentifier(node);
1092
+ if (!next) return node;
1093
+ container = next;
1094
+ } else if ((isFunctionDeclaration(node) || isFunctionExpression(node)) && node.name) container = node.name;
1095
+ else if (isMethodDeclaration(node) && isIdentifier(node.name)) container = this.f.createPropertyAccessExpression(this.f.createIdentifier("this"), node.name);
1096
+ else if (isConstructorDeclaration(node)) container = this.f.createPropertyAccessExpression(this.f.createIdentifier("this"), "constructor");
1097
+ const reset = this.f.createExpressionStatement(this.f.createBinaryExpression(this.f.createPropertyAccessExpression(container, this.f.createIdentifier("Ω")), this.f.createToken(typescript.default.SyntaxKind.EqualsToken), this.f.createIdentifier("undefined")));
1098
+ let body = node.body && isBlock(node.body) ? node.body : void 0;
1099
+ let bodyStatements = node.body && isBlock(node.body) ? [...node.body.statements] : [];
1100
+ if (node.body) {
1101
+ if (isExpression(node.body)) bodyStatements = [this.f.createReturnStatement(node.body)];
1102
+ body = this.f.updateBlock(node.body, [reset, ...bodyStatements]);
1103
+ }
1104
+ if (isArrowFunction(node)) return this.f.updateArrowFunction(node, node.modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, body);
1105
+ else if (isFunctionDeclaration(node)) return this.f.updateFunctionDeclaration(node, node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, body);
1106
+ else if (isFunctionExpression(node)) return this.f.updateFunctionExpression(node, node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, body || node.body);
1107
+ else if (isMethodDeclaration(node)) return this.f.updateMethodDeclaration(node, node.modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, body);
1108
+ else if (isConstructorDeclaration(node)) return this.f.updateConstructorDeclaration(node, node.modifiers, node.parameters, body);
1109
+ return node;
1110
+ }
1111
+ createProgramVarFromNode(node, name, sourceFile) {
1112
+ const typeProgram = new CompilerProgram(node, sourceFile);
1113
+ if ((isTypeAliasDeclaration(node) || isInterfaceDeclaration(node)) && node.typeParameters) for (const param of node.typeParameters) {
1114
+ if (param.default) this.extractPackStructOfType(param.default, typeProgram);
1115
+ typeProgram.pushTemplateParameter(getIdentifierName(param.name), !!param.default);
1116
+ }
1117
+ this.extractPackStructOfType(node, typeProgram);
1118
+ if (isTypeAliasDeclaration(node) || isInterfaceDeclaration(node) || isClassDeclaration(node) || isClassExpression(node)) typeProgram.pushOp(_deepkit_type_spec.ReflectionOp.nominal);
1119
+ const typeProgramExpression = this.packOpsAndStack(typeProgram);
1120
+ const variable = this.f.createVariableStatement([], this.f.createVariableDeclarationList([this.f.createVariableDeclaration(this.getDeclarationVariableName(name), void 0, void 0, typeProgramExpression)], NodeFlags.Const));
1121
+ if (hasModifier(node, SyntaxKind.ExportKeyword)) return [variable, this.f.createExportDeclaration(void 0, false, this.f.createNamedExports([this.f.createExportSpecifier(false, this.getDeclarationVariableName(name), this.getDeclarationVariableName(name))]))];
1122
+ return [variable];
1123
+ }
1124
+ extractPackStructOfExpression(node, program) {
1125
+ switch (node.kind) {
1126
+ case SyntaxKind.StringLiteral:
1127
+ program.pushOp(_deepkit_type_spec.ReflectionOp.string);
1128
+ return;
1129
+ case SyntaxKind.NumericLiteral:
1130
+ program.pushOp(_deepkit_type_spec.ReflectionOp.number);
1131
+ return;
1132
+ case SyntaxKind.FalseKeyword:
1133
+ case SyntaxKind.TrueKeyword:
1134
+ program.pushOp(_deepkit_type_spec.ReflectionOp.boolean);
1135
+ return;
1136
+ case SyntaxKind.BigIntLiteral:
1137
+ program.pushOp(_deepkit_type_spec.ReflectionOp.bigint);
1138
+ return;
1139
+ case SyntaxKind.CallExpression: {
1140
+ const call = node;
1141
+ if (isIdentifier(call.expression) && getIdentifierName(call.expression) === "Symbol") {
1142
+ program.pushOp(_deepkit_type_spec.ReflectionOp.symbol);
1143
+ return;
1144
+ }
1145
+ break;
1146
+ }
1147
+ case SyntaxKind.NewExpression: {
1148
+ const call = node;
1149
+ if (isIdentifier(call.expression)) {
1150
+ const op = {
1151
+ "Date": _deepkit_type_spec.ReflectionOp.date,
1152
+ "RegExp": _deepkit_type_spec.ReflectionOp.regexp,
1153
+ "Uint8Array": _deepkit_type_spec.ReflectionOp.uint8Array,
1154
+ "Uint8ClampedArray": _deepkit_type_spec.ReflectionOp.uint8ClampedArray,
1155
+ "Uint16Array": _deepkit_type_spec.ReflectionOp.uint16Array,
1156
+ "Uint32Array": _deepkit_type_spec.ReflectionOp.uint32Array,
1157
+ "Int8Array": _deepkit_type_spec.ReflectionOp.int8Array,
1158
+ "Int16Array": _deepkit_type_spec.ReflectionOp.int16Array,
1159
+ "Int32Array": _deepkit_type_spec.ReflectionOp.int32Array,
1160
+ "Float32Array": _deepkit_type_spec.ReflectionOp.float32Array,
1161
+ "Float64Array": _deepkit_type_spec.ReflectionOp.float64Array,
1162
+ "ArrayBuffer": _deepkit_type_spec.ReflectionOp.arrayBuffer
1163
+ }[getIdentifierName(call.expression)];
1164
+ if (op) {
1165
+ program.pushOp(op);
1166
+ return;
1167
+ }
1168
+ }
1169
+ break;
1170
+ }
1171
+ }
1172
+ program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1173
+ }
1174
+ extractPackStructOfType(node, program) {
1175
+ if (isParenthesizedTypeNode(node)) return this.extractPackStructOfType(node.type, program);
1176
+ switch (node.kind) {
1177
+ case SyntaxKind.StringKeyword:
1178
+ program.pushOp(_deepkit_type_spec.ReflectionOp.string);
1179
+ break;
1180
+ case SyntaxKind.NumberKeyword:
1181
+ program.pushOp(_deepkit_type_spec.ReflectionOp.number);
1182
+ break;
1183
+ case SyntaxKind.BooleanKeyword:
1184
+ program.pushOp(_deepkit_type_spec.ReflectionOp.boolean);
1185
+ break;
1186
+ case SyntaxKind.BigIntKeyword:
1187
+ program.pushOp(_deepkit_type_spec.ReflectionOp.bigint);
1188
+ break;
1189
+ case SyntaxKind.VoidKeyword:
1190
+ program.pushOp(_deepkit_type_spec.ReflectionOp.void);
1191
+ break;
1192
+ case SyntaxKind.UnknownKeyword:
1193
+ program.pushOp(_deepkit_type_spec.ReflectionOp.unknown);
1194
+ break;
1195
+ case SyntaxKind.ObjectKeyword:
1196
+ program.pushOp(_deepkit_type_spec.ReflectionOp.object);
1197
+ break;
1198
+ case SyntaxKind.SymbolKeyword:
1199
+ program.pushOp(_deepkit_type_spec.ReflectionOp.symbol);
1200
+ break;
1201
+ case SyntaxKind.NullKeyword:
1202
+ program.pushOp(_deepkit_type_spec.ReflectionOp.null);
1203
+ break;
1204
+ case SyntaxKind.NeverKeyword:
1205
+ program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1206
+ break;
1207
+ case SyntaxKind.AnyKeyword:
1208
+ program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1209
+ break;
1210
+ case SyntaxKind.UndefinedKeyword:
1211
+ program.pushOp(_deepkit_type_spec.ReflectionOp.undefined);
1212
+ break;
1213
+ case SyntaxKind.TrueKeyword:
1214
+ program.pushOp(_deepkit_type_spec.ReflectionOp.literal, program.pushStack(this.f.createTrue()));
1215
+ break;
1216
+ case SyntaxKind.FalseKeyword:
1217
+ program.pushOp(_deepkit_type_spec.ReflectionOp.literal, program.pushStack(this.f.createFalse()));
1218
+ break;
1219
+ case SyntaxKind.ClassDeclaration:
1220
+ case SyntaxKind.ClassExpression: {
1221
+ const narrowed = node;
1222
+ if (node) {
1223
+ const jsDocNode = narrowed.name?.parent || narrowed;
1224
+ this.withJSDocTypeAnnotations(program, jsDocNode, () => {
1225
+ const members = [];
1226
+ if (narrowed.typeParameters) for (const typeParameter of narrowed.typeParameters) {
1227
+ const name = getNameAsString(typeParameter.name);
1228
+ if (typeParameter.default) this.extractPackStructOfType(typeParameter.default, program);
1229
+ program.pushTemplateParameter(name, !!typeParameter.default);
1230
+ }
1231
+ if (narrowed.heritageClauses) {
1232
+ for (const heritage of narrowed.heritageClauses) if (heritage.token === SyntaxKind.ExtendsKeyword) for (const extendType of heritage.types) {
1233
+ program.pushFrame();
1234
+ if (extendType.typeArguments) for (const typeArgument of extendType.typeArguments) this.extractPackStructOfType(typeArgument, program);
1235
+ const index = program.pushStack(this.f.createArrowFunction(void 0, void 0, [], void 0, void 0, this.nodeConverter.toExpression(extendType.expression)));
1236
+ program.pushOp(_deepkit_type_spec.ReflectionOp.classReference, index);
1237
+ program.popFrameImplicit();
1238
+ }
1239
+ }
1240
+ for (const member of narrowed.members) {
1241
+ const name = getNameAsString(member.name);
1242
+ if (name) {
1243
+ if (members.some((v) => getNameAsString(v.name) === name)) continue;
1244
+ }
1245
+ members.push(member);
1246
+ this.extractPackStructOfType(member, program);
1247
+ }
1248
+ program.pushOp(_deepkit_type_spec.ReflectionOp.class);
1249
+ if (narrowed.heritageClauses) {
1250
+ for (const heritageClause of narrowed.heritageClauses) if (heritageClause.token === SyntaxKind.ExtendsKeyword) {
1251
+ const first = heritageClause.types[0];
1252
+ if (isExpressionWithTypeArguments(first) && first.typeArguments) {
1253
+ for (const typeArgument of first.typeArguments) this.extractPackStructOfType(typeArgument, program);
1254
+ program.pushOp(_deepkit_type_spec.ReflectionOp.classExtends, first.typeArguments.length);
1255
+ }
1256
+ } else if (heritageClause.token === SyntaxKind.ImplementsKeyword) {
1257
+ for (const type of heritageClause.types) this.extractPackStructOfTypeReference(type, program);
1258
+ program.pushOp(_deepkit_type_spec.ReflectionOp.implements, heritageClause.types.length);
1259
+ }
1260
+ }
1261
+ if (narrowed.name) this.resolveTypeName(getIdentifierName(narrowed.name), program);
1262
+ });
1263
+ }
1264
+ break;
1265
+ }
1266
+ case SyntaxKind.IntersectionType: {
1267
+ const narrowed = node;
1268
+ program.pushFrame();
1269
+ for (const type of narrowed.types) this.extractPackStructOfType(type, program);
1270
+ program.pushOp(_deepkit_type_spec.ReflectionOp.intersection);
1271
+ program.popFrameImplicit();
1272
+ break;
1273
+ }
1274
+ case SyntaxKind.MappedType: {
1275
+ const narrowed = node;
1276
+ program.pushFrame();
1277
+ program.pushVariable(getIdentifierName(narrowed.typeParameter.name));
1278
+ const constraint = getEffectiveConstraintOfTypeParameter(narrowed.typeParameter);
1279
+ if (constraint) this.extractPackStructOfType(constraint, program);
1280
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1281
+ let modifier = 0;
1282
+ if (narrowed.questionToken) {
1283
+ if (narrowed.questionToken.kind === SyntaxKind.QuestionToken) modifier |= 1;
1284
+ if (narrowed.questionToken.kind === SyntaxKind.MinusToken) modifier |= 2;
1285
+ }
1286
+ if (narrowed.readonlyToken) {
1287
+ if (narrowed.readonlyToken.kind === SyntaxKind.ReadonlyKeyword) modifier |= 4;
1288
+ if (narrowed.readonlyToken.kind === SyntaxKind.MinusToken) modifier |= 8;
1289
+ }
1290
+ program.pushCoRoutine();
1291
+ if (narrowed.nameType) program.pushFrame();
1292
+ if (narrowed.type) this.extractPackStructOfType(narrowed.type, program);
1293
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1294
+ if (narrowed.nameType) {
1295
+ this.extractPackStructOfType(narrowed.nameType, program);
1296
+ program.pushOp(_deepkit_type_spec.ReflectionOp.tuple);
1297
+ program.popFrameImplicit();
1298
+ }
1299
+ const coRoutineIndex = program.popCoRoutine();
1300
+ if (narrowed.nameType) program.pushOp(_deepkit_type_spec.ReflectionOp.mappedType2, coRoutineIndex, modifier);
1301
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.mappedType, coRoutineIndex, modifier);
1302
+ program.popFrameImplicit();
1303
+ break;
1304
+ }
1305
+ case SyntaxKind.TypeAliasDeclaration: {
1306
+ let narrowed = node;
1307
+ if (program.sourceFile && getNameAsString(narrowed.name) === "TypeAnnotation") {
1308
+ if (extractJSDocAttribute(program.sourceFile, narrowed, "intrinsic") !== void 0) narrowed = this.intrinsicMetaDeclaration;
1309
+ }
1310
+ if (isTypeLiteralNode(narrowed.type) || isInterfaceDeclaration(narrowed.type)) {
1311
+ this.extractPackStructOfType(narrowed.type, program);
1312
+ if (narrowed.name) this.resolveTypeName(getIdentifierName(narrowed.name), program);
1313
+ } else this.withJSDocTypeAnnotations(program, narrowed, () => {
1314
+ this.extractPackStructOfType(narrowed.type, program);
1315
+ if (narrowed.name) this.resolveTypeName(getIdentifierName(narrowed.name), program);
1316
+ });
1317
+ break;
1318
+ }
1319
+ case SyntaxKind.TypeLiteral:
1320
+ case SyntaxKind.InterfaceDeclaration: {
1321
+ const narrowed = node;
1322
+ let descriptionNode = narrowed;
1323
+ if (isTypeLiteralNode(narrowed)) descriptionNode = narrowed.parent;
1324
+ this.withJSDocTypeAnnotations(program, descriptionNode, () => {
1325
+ program.pushFrame();
1326
+ if (isInterfaceDeclaration(narrowed) && narrowed.heritageClauses) {
1327
+ for (const heritage of narrowed.heritageClauses) if (heritage.token === SyntaxKind.ExtendsKeyword) for (const extendType of heritage.types) this.extractPackStructOfTypeReference(extendType, program);
1328
+ }
1329
+ for (const member of narrowed.members) this.extractPackStructOfType(member, program);
1330
+ program.pushOp(_deepkit_type_spec.ReflectionOp.objectLiteral);
1331
+ if (isInterfaceDeclaration(narrowed)) {
1332
+ if (narrowed.name) this.resolveTypeName(getIdentifierName(narrowed.name), program);
1333
+ }
1334
+ program.popFrameImplicit();
1335
+ });
1336
+ break;
1337
+ }
1338
+ case SyntaxKind.TypeReference:
1339
+ this.extractPackStructOfTypeReference(node, program);
1340
+ break;
1341
+ case SyntaxKind.ArrayType:
1342
+ this.extractPackStructOfType(node.elementType, program);
1343
+ program.pushOp(_deepkit_type_spec.ReflectionOp.array);
1344
+ break;
1345
+ case SyntaxKind.RestType: {
1346
+ let type = node.type;
1347
+ if (isArrayTypeNode(type)) type = type.elementType;
1348
+ this.extractPackStructOfType(type, program);
1349
+ program.pushOp(_deepkit_type_spec.ReflectionOp.rest);
1350
+ break;
1351
+ }
1352
+ case SyntaxKind.TupleType:
1353
+ program.pushFrame();
1354
+ for (const element of node.elements) if (isOptionalTypeNode(element)) {
1355
+ this.extractPackStructOfType(element.type, program);
1356
+ program.pushOp(_deepkit_type_spec.ReflectionOp.tupleMember);
1357
+ program.pushOp(_deepkit_type_spec.ReflectionOp.optional);
1358
+ } else if (isNamedTupleMember(element)) {
1359
+ if (element.dotDotDotToken) {
1360
+ let type = element.type;
1361
+ if (isArrayTypeNode(type)) type = type.elementType;
1362
+ this.extractPackStructOfType(type, program);
1363
+ program.pushOp(_deepkit_type_spec.ReflectionOp.rest);
1364
+ } else this.extractPackStructOfType(element.type, program);
1365
+ const index = program.findOrAddStackEntry(getIdentifierName(element.name));
1366
+ program.pushOp(_deepkit_type_spec.ReflectionOp.namedTupleMember, index);
1367
+ if (element.questionToken) program.pushOp(_deepkit_type_spec.ReflectionOp.optional);
1368
+ } else this.extractPackStructOfType(element, program);
1369
+ program.pushOp(_deepkit_type_spec.ReflectionOp.tuple);
1370
+ program.popFrameImplicit();
1371
+ break;
1372
+ case SyntaxKind.PropertySignature: {
1373
+ const narrowed = node;
1374
+ if (narrowed.type) {
1375
+ const description = this.withJSDocTypeAnnotations(program, narrowed, () => {
1376
+ this.extractPackStructOfType(narrowed.type, program);
1377
+ }, { applyDescriptionOp: false });
1378
+ const name = getPropertyName(this.f, narrowed.name);
1379
+ program.pushOp(_deepkit_type_spec.ReflectionOp.propertySignature, program.findOrAddStackEntry(name));
1380
+ if (narrowed.questionToken) program.pushOp(_deepkit_type_spec.ReflectionOp.optional);
1381
+ if (hasModifier(narrowed, SyntaxKind.ReadonlyKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.readonly);
1382
+ if (description) program.pushOp(_deepkit_type_spec.ReflectionOp.description, program.findOrAddStackEntry(description));
1383
+ } else program.pushOp(_deepkit_type_spec.ReflectionOp.unknown);
1384
+ break;
1385
+ }
1386
+ case SyntaxKind.PropertyDeclaration: {
1387
+ const narrowed = node;
1388
+ if (false === this.getExplicitReflectionMode(program.sourceFile, narrowed)) return;
1389
+ const description = this.withJSDocTypeAnnotations(program, narrowed, () => {
1390
+ if (narrowed.type) this.extractPackStructOfType(narrowed.type, program);
1391
+ else if (narrowed.initializer) this.extractPackStructOfExpression(narrowed.initializer, program);
1392
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.unknown);
1393
+ }, { applyDescriptionOp: false });
1394
+ const name = getPropertyName(this.f, narrowed.name);
1395
+ program.pushOp(_deepkit_type_spec.ReflectionOp.property, program.findOrAddStackEntry(name));
1396
+ if (narrowed.questionToken) program.pushOp(_deepkit_type_spec.ReflectionOp.optional);
1397
+ if (hasModifier(narrowed, SyntaxKind.ReadonlyKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.readonly);
1398
+ if (hasModifier(narrowed, SyntaxKind.PrivateKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.private);
1399
+ if (hasModifier(narrowed, SyntaxKind.ProtectedKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.protected);
1400
+ if (hasModifier(narrowed, SyntaxKind.AbstractKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.abstract);
1401
+ if (hasModifier(narrowed, SyntaxKind.StaticKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.static);
1402
+ if (narrowed.initializer) program.pushOp(_deepkit_type_spec.ReflectionOp.defaultValue, program.findOrAddStackEntry(this.f.createFunctionExpression(void 0, void 0, void 0, void 0, void 0, void 0, this.f.createBlock([this.f.createReturnStatement(narrowed.initializer)]))));
1403
+ if (description) program.pushOp(_deepkit_type_spec.ReflectionOp.description, program.findOrAddStackEntry(description));
1404
+ break;
1405
+ }
1406
+ case SyntaxKind.ConditionalType: {
1407
+ const narrowed = node;
1408
+ const distributiveOverIdentifier = isTypeReferenceNode(narrowed.checkType) && isIdentifier(narrowed.checkType.typeName) ? narrowed.checkType.typeName : void 0;
1409
+ if (distributiveOverIdentifier) {
1410
+ program.pushFrame();
1411
+ this.extractPackStructOfType(narrowed.checkType, program);
1412
+ program.pushVariable(getIdentifierName(distributiveOverIdentifier));
1413
+ program.pushCoRoutine();
1414
+ }
1415
+ program.pushConditionalFrame();
1416
+ this.extractPackStructOfType(narrowed.checkType, program);
1417
+ this.extractPackStructOfType(narrowed.extendsType, program);
1418
+ program.pushOp(_deepkit_type_spec.ReflectionOp.extends);
1419
+ program.pushCoRoutine();
1420
+ this.extractPackStructOfType(narrowed.trueType, program);
1421
+ const trueProgram = program.popCoRoutine();
1422
+ program.pushCoRoutine();
1423
+ this.extractPackStructOfType(narrowed.falseType, program);
1424
+ const falseProgram = program.popCoRoutine();
1425
+ program.pushOp(_deepkit_type_spec.ReflectionOp.jumpCondition, trueProgram, falseProgram);
1426
+ program.moveFrame();
1427
+ if (distributiveOverIdentifier) {
1428
+ const coRoutineIndex = program.popCoRoutine();
1429
+ program.pushOp(_deepkit_type_spec.ReflectionOp.distribute, coRoutineIndex);
1430
+ program.popFrameImplicit();
1431
+ }
1432
+ break;
1433
+ }
1434
+ case SyntaxKind.InferType: {
1435
+ const narrowed = node;
1436
+ const frame = program.findConditionalFrame();
1437
+ if (frame) {
1438
+ const typeParameterName = getIdentifierName(narrowed.typeParameter.name);
1439
+ let variable = program.findVariable(typeParameterName);
1440
+ if (!variable) {
1441
+ program.pushVariable(typeParameterName, frame);
1442
+ variable = program.findVariable(typeParameterName);
1443
+ if (!variable) throw new Error("Could not find inserted infer variable");
1444
+ }
1445
+ program.pushOp(_deepkit_type_spec.ReflectionOp.infer, variable.frameOffset, variable.stackIndex);
1446
+ } else program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1447
+ break;
1448
+ }
1449
+ case SyntaxKind.MethodSignature:
1450
+ case SyntaxKind.MethodDeclaration:
1451
+ case SyntaxKind.Constructor:
1452
+ case SyntaxKind.ArrowFunction:
1453
+ case SyntaxKind.FunctionExpression:
1454
+ case SyntaxKind.ConstructSignature:
1455
+ case SyntaxKind.ConstructorType:
1456
+ case SyntaxKind.FunctionType:
1457
+ case SyntaxKind.CallSignature:
1458
+ case SyntaxKind.FunctionDeclaration: {
1459
+ const narrowed = node;
1460
+ if (false === this.getExplicitReflectionMode(program.sourceFile, narrowed)) {
1461
+ program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1462
+ return;
1463
+ }
1464
+ const name = isCallSignatureDeclaration(node) ? "" : isConstructorTypeNode(narrowed) || isConstructSignatureDeclaration(node) ? "new" : isConstructorDeclaration(narrowed) ? "constructor" : getPropertyName(this.f, narrowed.name);
1465
+ if (!narrowed.type && narrowed.parameters.length === 0 && !name) return;
1466
+ program.pushFrame();
1467
+ for (let i = 0; i < narrowed.parameters.length; i++) {
1468
+ const parameter = narrowed.parameters[i];
1469
+ const parameterName = isIdentifier(parameter.name) ? getNameAsString(parameter.name) : "param" + i;
1470
+ const type = parameter.type ? parameter.dotDotDotToken && isArrayTypeNode(parameter.type) ? parameter.type.elementType : parameter.type : void 0;
1471
+ const description = this.withJSDocTypeAnnotations(program, parameter, () => {
1472
+ if (type) this.extractPackStructOfType(type, program);
1473
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1474
+ }, { applyDescriptionOp: false });
1475
+ if (parameter.dotDotDotToken) program.pushOp(_deepkit_type_spec.ReflectionOp.rest);
1476
+ program.pushOp(_deepkit_type_spec.ReflectionOp.parameter, program.findOrAddStackEntry(parameterName));
1477
+ if (parameter.questionToken) program.pushOp(_deepkit_type_spec.ReflectionOp.optional);
1478
+ if (hasModifier(parameter, SyntaxKind.PublicKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.public);
1479
+ if (hasModifier(parameter, SyntaxKind.PrivateKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.private);
1480
+ if (hasModifier(parameter, SyntaxKind.ProtectedKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.protected);
1481
+ if (hasModifier(parameter, SyntaxKind.ReadonlyKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.readonly);
1482
+ if (description) program.pushOp(_deepkit_type_spec.ReflectionOp.description, program.findOrAddStackEntry(description));
1483
+ if (parameter.initializer && parameter.type && !getReceiveTypeParameter(parameter.type)) program.pushOp(_deepkit_type_spec.ReflectionOp.defaultValue, program.findOrAddStackEntry(this.f.createArrowFunction(void 0, void 0, [], void 0, void 0, parameter.initializer)));
1484
+ }
1485
+ if (narrowed.type) this.extractPackStructOfType(narrowed.type, program);
1486
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1487
+ program.pushOp(isCallSignatureDeclaration(node) ? _deepkit_type_spec.ReflectionOp.callSignature : isMethodSignature(narrowed) || isConstructSignatureDeclaration(narrowed) ? _deepkit_type_spec.ReflectionOp.methodSignature : isMethodDeclaration(narrowed) || isConstructorDeclaration(narrowed) ? _deepkit_type_spec.ReflectionOp.method : _deepkit_type_spec.ReflectionOp.function, program.findOrAddStackEntry(name));
1488
+ if ((isMethodSignature(narrowed) || isMethodDeclaration(narrowed)) && narrowed.questionToken) program.pushOp(_deepkit_type_spec.ReflectionOp.optional);
1489
+ if (isMethodDeclaration(narrowed)) {
1490
+ if (hasModifier(narrowed, SyntaxKind.PrivateKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.private);
1491
+ if (hasModifier(narrowed, SyntaxKind.ProtectedKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.protected);
1492
+ if (hasModifier(narrowed, SyntaxKind.AbstractKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.abstract);
1493
+ if (hasModifier(narrowed, SyntaxKind.StaticKeyword)) program.pushOp(_deepkit_type_spec.ReflectionOp.static);
1494
+ }
1495
+ const { description } = this.collectJSDocAnnotations(narrowed);
1496
+ if (description) program.pushOp(_deepkit_type_spec.ReflectionOp.description, program.findOrAddStackEntry(description));
1497
+ program.popFrameImplicit();
1498
+ break;
1499
+ }
1500
+ case SyntaxKind.LiteralType: {
1501
+ const narrowed = node;
1502
+ if (narrowed.literal.kind === SyntaxKind.NullKeyword) program.pushOp(_deepkit_type_spec.ReflectionOp.null);
1503
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.literal, program.findOrAddStackEntry(narrowed.literal));
1504
+ break;
1505
+ }
1506
+ case SyntaxKind.TemplateLiteralType: {
1507
+ const narrowed = node;
1508
+ program.pushFrame();
1509
+ if (narrowed.head.rawText) program.pushOp(_deepkit_type_spec.ReflectionOp.literal, program.findOrAddStackEntry(narrowed.head.rawText));
1510
+ for (const span of narrowed.templateSpans) {
1511
+ this.extractPackStructOfType(span.type, program);
1512
+ if (span.literal.rawText) program.pushOp(_deepkit_type_spec.ReflectionOp.literal, program.findOrAddStackEntry(span.literal.rawText));
1513
+ }
1514
+ program.pushOp(_deepkit_type_spec.ReflectionOp.templateLiteral);
1515
+ program.popFrameImplicit();
1516
+ break;
1517
+ }
1518
+ case SyntaxKind.UnionType: {
1519
+ const narrowed = node;
1520
+ if (narrowed.types.length === 0) {} else if (narrowed.types.length === 1) this.extractPackStructOfType(narrowed.types[0], program);
1521
+ else {
1522
+ program.pushFrame();
1523
+ for (const subType of narrowed.types) this.extractPackStructOfType(subType, program);
1524
+ program.pushOp(_deepkit_type_spec.ReflectionOp.union);
1525
+ program.popFrameImplicit();
1526
+ }
1527
+ break;
1528
+ }
1529
+ case SyntaxKind.EnumDeclaration: {
1530
+ const narrowed = node;
1531
+ program.pushFrame();
1532
+ for (const type of narrowed.members) {
1533
+ const name = getPropertyName(this.f, type.name);
1534
+ program.pushOp(_deepkit_type_spec.ReflectionOp.enumMember, program.findOrAddStackEntry(name));
1535
+ if (type.initializer) program.pushOp(_deepkit_type_spec.ReflectionOp.defaultValue, program.findOrAddStackEntry(this.f.createArrowFunction(void 0, void 0, [], void 0, void 0, type.initializer)));
1536
+ }
1537
+ program.pushOp(_deepkit_type_spec.ReflectionOp.enum);
1538
+ const { description } = this.collectJSDocAnnotations(narrowed);
1539
+ if (description) program.pushOp(_deepkit_type_spec.ReflectionOp.description, program.findOrAddStackEntry(description));
1540
+ if (narrowed.name) this.resolveTypeName(getIdentifierName(narrowed.name), program);
1541
+ program.popFrameImplicit();
1542
+ break;
1543
+ }
1544
+ case SyntaxKind.IndexSignature: {
1545
+ const narrowed = node;
1546
+ if (narrowed.parameters.length && narrowed.parameters[0].type) this.extractPackStructOfType(narrowed.parameters[0].type, program);
1547
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1548
+ this.extractPackStructOfType(narrowed.type, program);
1549
+ program.pushOp(_deepkit_type_spec.ReflectionOp.indexSignature);
1550
+ break;
1551
+ }
1552
+ case SyntaxKind.TypeQuery: {
1553
+ const narrowed = node;
1554
+ if (isIdentifier(narrowed.exprName)) {
1555
+ const resolved = this.resolveDeclaration(narrowed.exprName);
1556
+ if (resolved && findSourceFile(resolved.declaration) !== this.sourceFile && resolved.importDeclaration) ensureImportIsEmitted(resolved.importDeclaration, narrowed.exprName);
1557
+ }
1558
+ const expression = serializeEntityNameAsExpression(this.f, narrowed.exprName);
1559
+ program.pushOp(_deepkit_type_spec.ReflectionOp.typeof, program.pushStack(this.f.createArrowFunction(void 0, void 0, [], void 0, void 0, expression)));
1560
+ break;
1561
+ }
1562
+ case SyntaxKind.TypeOperator: {
1563
+ const narrowed = node;
1564
+ if (narrowed.type.kind === SyntaxKind.ThisType) {
1565
+ program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1566
+ break;
1567
+ }
1568
+ switch (narrowed.operator) {
1569
+ case SyntaxKind.KeyOfKeyword:
1570
+ this.extractPackStructOfType(narrowed.type, program);
1571
+ program.pushOp(_deepkit_type_spec.ReflectionOp.keyof);
1572
+ break;
1573
+ case SyntaxKind.ReadonlyKeyword:
1574
+ this.extractPackStructOfType(narrowed.type, program);
1575
+ program.pushOp(_deepkit_type_spec.ReflectionOp.readonly);
1576
+ break;
1577
+ default: program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1578
+ }
1579
+ break;
1580
+ }
1581
+ case SyntaxKind.IndexedAccessType: {
1582
+ const narrowed = node;
1583
+ this.extractPackStructOfType(narrowed.objectType, program);
1584
+ this.extractPackStructOfType(narrowed.indexType, program);
1585
+ program.pushOp(_deepkit_type_spec.ReflectionOp.indexAccess);
1586
+ break;
1587
+ }
1588
+ case SyntaxKind.Identifier: {
1589
+ const narrowed = node;
1590
+ const variable = program.findVariable(getIdentifierName(narrowed));
1591
+ if (variable) program.pushOp(_deepkit_type_spec.ReflectionOp.loads, variable.frameOffset, variable.stackIndex);
1592
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1593
+ break;
1594
+ }
1595
+ default: program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1596
+ }
1597
+ }
1598
+ getGlobalLibs() {
1599
+ if (this.cache.globalSourceFiles) return this.cache.globalSourceFiles;
1600
+ this.cache.globalSourceFiles = [];
1601
+ const options = { ...this.compilerOptions };
1602
+ if (options.target && options.target === ScriptTarget.ESNext) options.target = ScriptTarget.ES2022;
1603
+ const libs = (0, _typescript_vfs.knownLibFilesForCompilerOptions)(options, typescript.default);
1604
+ for (const lib of libs) {
1605
+ if (this.isExcluded(lib)) continue;
1606
+ const sourceFile = this.resolver.resolveSourceFile(this.sourceFile, this.f.createStringLiteral("typescript/lib/" + lib.replace(".d.ts", "")));
1607
+ if (!sourceFile) continue;
1608
+ this.cache.globalSourceFiles.push(sourceFile);
1609
+ }
1610
+ return this.cache.globalSourceFiles;
1611
+ }
1612
+ /**
1613
+ * This is a custom resolver based on populated `locals` from the binder. It uses a custom resolution algorithm since
1614
+ * we have no access to the binder/TypeChecker directly and instantiating a TypeChecker per file/transformer is incredible slow.
1615
+ */
1616
+ resolveDeclaration(typeName) {
1617
+ let current = typeName.parent;
1618
+ if (typeName.kind === SyntaxKind.QualifiedName) return;
1619
+ let declaration = void 0;
1620
+ while (current) {
1621
+ if (isNodeWithLocals(current) && current.locals) {
1622
+ const found = current.locals.get(typeName.escapedText);
1623
+ if (found && found.declarations && found.declarations[0]) {
1624
+ /**
1625
+ * Discard parameters, since they can not be referenced from inside
1626
+ *
1627
+ * ```typescript
1628
+ * type B = string;
1629
+ * function a(B: B) {}
1630
+ *
1631
+ * class A {
1632
+ * constructor(B: B) {}
1633
+ * }
1634
+ * ```
1635
+ *
1636
+ */
1637
+ if (!isParameter(found.declarations[0])) {
1638
+ declaration = found.declarations[0];
1639
+ break;
1640
+ }
1641
+ }
1642
+ }
1643
+ if (current.kind === SyntaxKind.SourceFile) break;
1644
+ current = current.parent;
1645
+ }
1646
+ if (!declaration) for (const file of this.getGlobalLibs()) {
1647
+ const globals = getGlobalsOfSourceFile(file);
1648
+ if (!globals) continue;
1649
+ const symbol = globals.get(typeName.escapedText);
1650
+ if (symbol && symbol.declarations && symbol.declarations[0]) {
1651
+ declaration = symbol.declarations[0];
1652
+ break;
1653
+ }
1654
+ }
1655
+ let importDeclaration = void 0;
1656
+ let typeOnly = false;
1657
+ if (declaration && isImportSpecifier(declaration)) {
1658
+ if (declaration.isTypeOnly) typeOnly = true;
1659
+ importDeclaration = declaration.parent.parent.parent;
1660
+ } else if (declaration && isImportDeclaration(declaration)) importDeclaration = declaration;
1661
+ else if (declaration && isImportClause(declaration)) importDeclaration = declaration.parent;
1662
+ if (importDeclaration) {
1663
+ if (importDeclaration.importClause && importDeclaration.importClause.isTypeOnly) typeOnly = true;
1664
+ declaration = this.resolveImportSpecifier(getEscapedText(typeName), importDeclaration, this.sourceFile);
1665
+ }
1666
+ if (declaration && declaration.kind === SyntaxKind.TypeParameter && declaration.parent.kind === SyntaxKind.TypeAliasDeclaration) declaration = declaration.parent;
1667
+ if (!declaration) return;
1668
+ return {
1669
+ declaration,
1670
+ importDeclaration,
1671
+ typeOnly
1672
+ };
1673
+ }
1674
+ getDeclarationVariableName(typeName) {
1675
+ if (isIdentifier(typeName)) return this.f.createIdentifier("__Ω" + getIdentifierName(typeName));
1676
+ function joinQualifiedName(name) {
1677
+ if (isIdentifier(name)) return getIdentifierName(name);
1678
+ return joinQualifiedName(name.left) + "_" + getIdentifierName(name.right);
1679
+ }
1680
+ return this.f.createIdentifier("__Ω" + joinQualifiedName(typeName));
1681
+ }
1682
+ /**
1683
+ * The semantic of isExcluded is different from checking if the fileName is part
1684
+ * of reflection config option. isExcluded checks if the file should be excluded
1685
+ * via the exclude option. mainly used to exclude globals and external libraries.
1686
+ */
1687
+ isExcluded(fileName) {
1688
+ const resolver = this.overriddenConfigResolver || getConfigResolver(this.cache.resolver, this.parseConfigHost, this.compilerOptions, this.sourceFile);
1689
+ return reflectionModeMatcher({
1690
+ reflection: "default",
1691
+ exclude: resolver.config.exclude
1692
+ }, fileName) === "never";
1693
+ }
1694
+ extractPackStructOfTypeReference(type, program) {
1695
+ const typeName = isTypeReferenceNode(type) ? type.typeName : isIdentifier(type.expression) ? type.expression : void 0;
1696
+ if (!typeName) {
1697
+ program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1698
+ return;
1699
+ }
1700
+ if (isIdentifier(typeName) && getIdentifierName(typeName) === "InlineRuntimeType" && type.typeArguments && type.typeArguments[0] && isTypeQueryNode(type.typeArguments[0])) {
1701
+ const expression = serializeEntityNameAsExpression(this.f, type.typeArguments[0].exprName);
1702
+ program.pushOp(_deepkit_type_spec.ReflectionOp.arg, program.pushStack(expression));
1703
+ return;
1704
+ }
1705
+ if (isIdentifier(typeName) && getIdentifierName(typeName) !== "constructor" && this.knownClasses[getIdentifierName(typeName)]) {
1706
+ const name = getIdentifierName(typeName);
1707
+ const op = this.knownClasses[name];
1708
+ program.pushOp(op);
1709
+ } else if (isIdentifier(typeName) && getIdentifierName(typeName) === "Promise") {
1710
+ if (type.typeArguments && type.typeArguments[0]) this.extractPackStructOfType(type.typeArguments[0], program);
1711
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1712
+ program.pushOp(_deepkit_type_spec.ReflectionOp.promise);
1713
+ } else if (isIdentifier(typeName) && getIdentifierName(typeName) === "integer") program.pushOp(_deepkit_type_spec.ReflectionOp.numberBrand, _deepkit_type_spec.TypeNumberBrand.integer);
1714
+ else if (isIdentifier(typeName) && getIdentifierName(typeName) !== "constructor" && _deepkit_type_spec.TypeNumberBrand[getIdentifierName(typeName)] !== void 0) program.pushOp(_deepkit_type_spec.ReflectionOp.numberBrand, _deepkit_type_spec.TypeNumberBrand[getIdentifierName(typeName)]);
1715
+ else {
1716
+ if (isIdentifier(typeName)) {
1717
+ const variable = program.findVariable(getIdentifierName(typeName));
1718
+ if (variable) {
1719
+ program.pushOp(_deepkit_type_spec.ReflectionOp.loads, variable.frameOffset, variable.stackIndex);
1720
+ return;
1721
+ }
1722
+ } else if (isInferTypeNode(typeName)) {
1723
+ this.extractPackStructOfType(typeName, program);
1724
+ return;
1725
+ }
1726
+ const resolved = this.resolveDeclaration(typeName);
1727
+ if (!resolved) {
1728
+ if (isQualifiedName(typeName)) {
1729
+ if (isIdentifier(typeName.left)) {
1730
+ const resolved = this.resolveDeclaration(typeName.left);
1731
+ if (resolved && isEnumDeclaration(resolved.declaration)) {
1732
+ let lastExpression;
1733
+ let indexValue = 0;
1734
+ for (const member of resolved.declaration.members) if (getNameAsString(member.name) === getNameAsString(typeName.right)) {
1735
+ if (member.initializer) program.pushOp(_deepkit_type_spec.ReflectionOp.arg, program.pushStack(this.nodeConverter.toExpression(member.initializer)));
1736
+ else if (lastExpression) {
1737
+ const exp = this.nodeConverter.toExpression(lastExpression);
1738
+ program.pushOp(_deepkit_type_spec.ReflectionOp.arg, program.pushStack(this.f.createBinaryExpression(exp, SyntaxKind.PlusToken, this.nodeConverter.toExpression(indexValue))));
1739
+ } else program.pushOp(_deepkit_type_spec.ReflectionOp.arg, program.pushStack(this.nodeConverter.toExpression(indexValue)));
1740
+ return;
1741
+ } else {
1742
+ indexValue++;
1743
+ if (member.initializer) {
1744
+ lastExpression = member.initializer;
1745
+ indexValue = 0;
1746
+ }
1747
+ }
1748
+ }
1749
+ }
1750
+ }
1751
+ program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1752
+ debug2(`Could not resolve ${getNameAsString(typeName)} in ${program.sourceFile?.fileName || "intrinsic"}`);
1753
+ return;
1754
+ }
1755
+ let declaration = resolved.declaration;
1756
+ const declarationSourceFile = findSourceFile(declaration);
1757
+ const isGlobal = !declarationSourceFile || resolved.importDeclaration === void 0 && declarationSourceFile.fileName !== this.sourceFile.fileName;
1758
+ const isFromImport = resolved.importDeclaration !== void 0;
1759
+ if (isVariableDeclaration(declaration)) {
1760
+ if (declaration.type) declaration = declaration.type;
1761
+ else if (declaration.initializer) declaration = declaration.initializer;
1762
+ }
1763
+ if (isModuleDeclaration(declaration) && resolved.importDeclaration) {
1764
+ if (isIdentifier(typeName)) ensureImportIsEmitted(resolved.importDeclaration, typeName);
1765
+ program.pushOp(_deepkit_type_spec.ReflectionOp.typeof, program.pushStack(this.f.createArrowFunction(void 0, void 0, [], void 0, void 0, serializeEntityNameAsExpression(this.f, typeName))));
1766
+ } else if (isTypeAliasDeclaration(declaration) || isInterfaceDeclaration(declaration) || isEnumDeclaration(declaration)) {
1767
+ const name = getNameAsString(typeName);
1768
+ if (name === "Array") {
1769
+ if (type.typeArguments && type.typeArguments[0]) this.extractPackStructOfType(type.typeArguments[0], program);
1770
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1771
+ program.pushOp(_deepkit_type_spec.ReflectionOp.array);
1772
+ return;
1773
+ } else if (name === "Function") {
1774
+ program.pushFrame();
1775
+ const index = program.pushStack(this.f.createArrowFunction(void 0, void 0, [], void 0, void 0, this.f.createIdentifier("Function")));
1776
+ program.pushOp(_deepkit_type_spec.ReflectionOp.functionReference, index);
1777
+ program.popFrameImplicit();
1778
+ return;
1779
+ } else if (name === "Set") {
1780
+ if (type.typeArguments && type.typeArguments[0]) this.extractPackStructOfType(type.typeArguments[0], program);
1781
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1782
+ program.pushOp(_deepkit_type_spec.ReflectionOp.set);
1783
+ return;
1784
+ } else if (name === "Map") {
1785
+ if (type.typeArguments && type.typeArguments[0]) this.extractPackStructOfType(type.typeArguments[0], program);
1786
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1787
+ if (type.typeArguments && type.typeArguments[1]) this.extractPackStructOfType(type.typeArguments[1], program);
1788
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1789
+ program.pushOp(_deepkit_type_spec.ReflectionOp.map);
1790
+ return;
1791
+ }
1792
+ const runtimeTypeName = this.getDeclarationVariableName(typeName);
1793
+ if (!this.compiledDeclarations.has(declaration) && !this.compileDeclarations.has(declaration)) {
1794
+ if (declarationSourceFile && this.isExcluded(declarationSourceFile.fileName)) {
1795
+ program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1796
+ return;
1797
+ }
1798
+ if (isGlobal) this.embedDeclarations.set(declaration, {
1799
+ name: typeName,
1800
+ sourceFile: declarationSourceFile
1801
+ });
1802
+ else if (isFromImport) {
1803
+ if (resolved.importDeclaration) {
1804
+ if (resolved.typeOnly) {
1805
+ this.resolveTypeOnlyImport(typeName, program);
1806
+ return;
1807
+ }
1808
+ if (declarationSourceFile.fileName.endsWith(".d.ts")) {
1809
+ if (!this.resolveImportSpecifier(getEscapedText(runtimeTypeName), resolved.importDeclaration, this.sourceFile)) {
1810
+ debug2(`Symbol ${runtimeTypeName.escapedText} not found in ${declarationSourceFile.fileName}`);
1811
+ this.resolveTypeOnlyImport(typeName, program);
1812
+ return;
1813
+ }
1814
+ this.addImports.push({
1815
+ identifier: runtimeTypeName,
1816
+ importDeclaration: resolved.importDeclaration
1817
+ });
1818
+ } else {
1819
+ if (this.getReflectionConfig(declarationSourceFile).mode === "never") {
1820
+ this.resolveTypeOnlyImport(typeName, program);
1821
+ return;
1822
+ }
1823
+ if (!this.isWithReflection(declarationSourceFile, declaration)) {
1824
+ this.resolveTypeOnlyImport(typeName, program);
1825
+ return;
1826
+ }
1827
+ this.addImports.push({
1828
+ identifier: runtimeTypeName,
1829
+ importDeclaration: resolved.importDeclaration
1830
+ });
1831
+ }
1832
+ }
1833
+ } else {
1834
+ if (!this.isWithReflection(program.sourceFile, declaration)) {
1835
+ this.resolveTypeOnlyImport(typeName, program);
1836
+ return;
1837
+ }
1838
+ this.compileDeclarations.set(declaration, {
1839
+ name: typeName,
1840
+ sourceFile: declarationSourceFile
1841
+ });
1842
+ }
1843
+ }
1844
+ const index = program.pushStack(program.forNode === declaration ? 0 : this.f.createArrowFunction(void 0, void 0, [], void 0, void 0, runtimeTypeName));
1845
+ if (type.typeArguments) {
1846
+ for (const argument of type.typeArguments) this.extractPackStructOfType(argument, program);
1847
+ program.pushOp(_deepkit_type_spec.ReflectionOp.inlineCall, index, type.typeArguments.length);
1848
+ } else program.pushOp(_deepkit_type_spec.ReflectionOp.inline, index);
1849
+ } else if (isClassDeclaration(declaration) || isFunctionDeclaration(declaration) || isFunctionExpression(declaration) || isArrowFunction(declaration)) {
1850
+ if (resolved.typeOnly) {
1851
+ this.resolveTypeOnlyImport(typeName, program);
1852
+ return;
1853
+ }
1854
+ if (!(declarationSourceFile?.fileName.endsWith(".d.ts") || this.isWithReflection(program.sourceFile, declaration))) {
1855
+ this.resolveTypeOnlyImport(typeName, program);
1856
+ return;
1857
+ }
1858
+ if (resolved.importDeclaration && isIdentifier(typeName)) ensureImportIsEmitted(resolved.importDeclaration, typeName);
1859
+ program.pushFrame();
1860
+ if (type.typeArguments) for (const typeArgument of type.typeArguments) this.extractPackStructOfType(typeArgument, program);
1861
+ const body = isIdentifier(typeName) ? typeName : this.createAccessorForEntityName(typeName);
1862
+ const index = program.pushStack(this.f.createArrowFunction(void 0, void 0, [], void 0, void 0, body));
1863
+ program.pushOp(isClassDeclaration(declaration) ? _deepkit_type_spec.ReflectionOp.classReference : _deepkit_type_spec.ReflectionOp.functionReference, index);
1864
+ program.popFrameImplicit();
1865
+ } else if (isTypeParameterDeclaration(declaration)) this.resolveTypeParameter(declaration, type, program);
1866
+ else this.extractPackStructOfType(declaration, program);
1867
+ }
1868
+ }
1869
+ /**
1870
+ * Returns the class declaration, function/arrow declaration, or block where type was used.
1871
+ */
1872
+ getTypeUser(type) {
1873
+ let current = type;
1874
+ while (current) {
1875
+ if (current.kind === SyntaxKind.Block) return current;
1876
+ if (current.kind === SyntaxKind.ClassDeclaration) return current;
1877
+ if (current.kind === SyntaxKind.ClassExpression) return current;
1878
+ if (current.kind === SyntaxKind.Constructor) return current.parent;
1879
+ if (current.kind === SyntaxKind.MethodDeclaration) return current.parent;
1880
+ if (current.kind === SyntaxKind.ArrowFunction || current.kind === SyntaxKind.FunctionDeclaration || current.kind === SyntaxKind.FunctionExpression) return current;
1881
+ current = current.parent;
1882
+ }
1883
+ return current;
1884
+ }
1885
+ /**
1886
+ * With this function we want to check if `type` is used in the signature itself from the parent of `declaration`.
1887
+ * If so, we do not try to infer the type from runtime values.
1888
+ *
1889
+ * Examples where we do not infer from runtime, `type` being `T` and `declaration` being `<T>` (return false):
1890
+ *
1891
+ * ```typescript
1892
+ * class User<T> {
1893
+ * config: T;
1894
+ * }
1895
+ *
1896
+ * class User<T> {
1897
+ * constructor(public config: T) {}
1898
+ * }
1899
+ *
1900
+ * function do<T>(item: T): void {}
1901
+ * function do<T>(item: T): T {}
1902
+ * ```
1903
+ *
1904
+ * Examples where we infer from runtime (return true):
1905
+ *
1906
+ * ```typescript
1907
+ * function do<T>(item: T) {
1908
+ * return typeOf<T>; //<-- because of that
1909
+ * }
1910
+ *
1911
+ * function do<T>(item: T) {
1912
+ * class A {
1913
+ * config: T; //<-- because of that
1914
+ * }
1915
+ * return A;
1916
+ * }
1917
+ *
1918
+ * function do<T>(item: T) {
1919
+ * class A {
1920
+ * doIt() {
1921
+ * class B {
1922
+ * config: T; //<-- because of that
1923
+ * }
1924
+ * return B;
1925
+ * }
1926
+ * }
1927
+ * return A;
1928
+ * }
1929
+ *
1930
+ * function do<T>(item: T) {
1931
+ * class A {
1932
+ * doIt(): T { //<-- because of that
1933
+ * }
1934
+ * }
1935
+ * return A;
1936
+ * }
1937
+ * ```
1938
+ */
1939
+ needsToBeInferred(declaration, type) {
1940
+ return this.getTypeUser(declaration) !== this.getTypeUser(type);
1941
+ }
1942
+ resolveTypeOnlyImport(entityName, program) {
1943
+ program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1944
+ const typeName = typescript.default.isIdentifier(entityName) ? getIdentifierName(entityName) : getIdentifierName(entityName.right);
1945
+ this.resolveTypeName(typeName, program);
1946
+ }
1947
+ resolveTypeName(typeName, program) {
1948
+ if (!typeName) return;
1949
+ program.pushOp(_deepkit_type_spec.ReflectionOp.typeName, program.findOrAddStackEntry(typeName));
1950
+ }
1951
+ resolveTypeParameter(declaration, type, program) {
1952
+ const isUsedInFunction = isFunctionLike(declaration.parent);
1953
+ if (isUsedInFunction && program.isResolveFunctionParameters(declaration.parent) || this.needsToBeInferred(declaration, type)) {
1954
+ const argumentName = declaration.name.escapedText;
1955
+ const foundUsers = [];
1956
+ if (isUsedInFunction) for (const parameter of declaration.parent.parameters) {
1957
+ if (!parameter.type) continue;
1958
+ let found = false;
1959
+ const searchArgument = (node) => {
1960
+ node = visitEachChild(node, searchArgument, this.context);
1961
+ if (isIdentifier(node) && node.escapedText === argumentName) {
1962
+ found = true;
1963
+ node = this.f.createInferTypeNode(declaration);
1964
+ }
1965
+ return node;
1966
+ };
1967
+ if (isIdentifier(parameter.name)) {
1968
+ const updatedParameterType = visitEachChild(parameter.type, searchArgument, this.context);
1969
+ if (found) foundUsers.push({
1970
+ type: updatedParameterType,
1971
+ parameterName: parameter.name
1972
+ });
1973
+ }
1974
+ }
1975
+ if (foundUsers.length) {
1976
+ if (foundUsers.length > 1) {}
1977
+ const isReceiveType = foundUsers.find((v) => isTypeReferenceNode(v.type) && isIdentifier(v.type.typeName) && getIdentifierName(v.type.typeName) === "ReceiveType");
1978
+ if (isReceiveType) program.pushOp(_deepkit_type_spec.ReflectionOp.inline, program.pushStack(isReceiveType.parameterName));
1979
+ else for (const foundUser of foundUsers) {
1980
+ program.pushConditionalFrame();
1981
+ program.pushOp(_deepkit_type_spec.ReflectionOp.typeof, program.pushStack(this.f.createArrowFunction(void 0, void 0, [], void 0, void 0, foundUser.parameterName)));
1982
+ this.extractPackStructOfType(foundUser.type, program);
1983
+ program.pushOp(_deepkit_type_spec.ReflectionOp.extends);
1984
+ if (program.findVariable(getIdentifierName(declaration.name))) this.extractPackStructOfType(declaration.name, program);
1985
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1986
+ this.extractPackStructOfType({ kind: SyntaxKind.NeverKeyword }, program);
1987
+ program.pushOp(_deepkit_type_spec.ReflectionOp.condition);
1988
+ program.popFrameImplicit();
1989
+ }
1990
+ if (foundUsers.length > 1) {}
1991
+ } else if (declaration.constraint) {
1992
+ if (isUsedInFunction) program.resolveFunctionParametersIncrease(declaration.parent);
1993
+ const constraint = getEffectiveConstraintOfTypeParameter(declaration);
1994
+ if (constraint) this.extractPackStructOfType(constraint, program);
1995
+ else program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1996
+ if (isUsedInFunction) program.resolveFunctionParametersDecrease(declaration.parent);
1997
+ } else program.pushOp(_deepkit_type_spec.ReflectionOp.never);
1998
+ } else program.pushOp(_deepkit_type_spec.ReflectionOp.any);
1999
+ }
2000
+ createAccessorForEntityName(e) {
2001
+ return this.f.createPropertyAccessExpression(isIdentifier(e.left) ? e.left : this.createAccessorForEntityName(e.left), e.right);
2002
+ }
2003
+ findDeclarationInFile(sourceFile, declarationName) {
2004
+ if (isNodeWithLocals(sourceFile) && sourceFile.locals) {
2005
+ const declarationSymbol = sourceFile.locals.get(declarationName);
2006
+ if (declarationSymbol && declarationSymbol.declarations && declarationSymbol.declarations[0]) return declarationSymbol.declarations[0];
2007
+ }
2008
+ }
2009
+ resolveImportSpecifier(_declarationName, importOrExport, sourceFile) {
2010
+ const declarationName = "string" === typeof _declarationName ? _declarationName : getIdentifierName(_declarationName);
2011
+ if (!importOrExport.moduleSpecifier || !isStringLiteral(importOrExport.moduleSpecifier)) return;
2012
+ const source = this.resolver.resolve(sourceFile, importOrExport);
2013
+ if (!source) {
2014
+ debug("module not found", importOrExport.moduleSpecifier.text, "Is transpileOnly enabled? It needs to be disabled.");
2015
+ return;
2016
+ }
2017
+ const declaration = this.findDeclarationInFile(source, declarationName);
2018
+ sourceFile = source;
2019
+ /**
2020
+ * declaration could also be `import {PrimaryKey} from 'xy'`, which we want to skip
2021
+ */
2022
+ if (declaration && !isImportSpecifier(declaration)) {
2023
+ if (isExportDeclaration(declaration)) return this.followExport(declarationName, declaration, sourceFile);
2024
+ return declaration;
2025
+ }
2026
+ if (isSourceFile(sourceFile)) for (const statement of sourceFile.statements) {
2027
+ if (!isExportDeclaration(statement)) continue;
2028
+ const found = this.followExport(declarationName, statement, sourceFile);
2029
+ if (found) return found;
2030
+ }
2031
+ }
2032
+ followExport(declarationName, statement, sourceFile) {
2033
+ if (statement.exportClause) {
2034
+ if (isNamedExports(statement.exportClause)) {
2035
+ for (const element of statement.exportClause.elements) if (getEscapedText(element.name) === declarationName) if (!statement.moduleSpecifier || !isStringLiteral(statement.moduleSpecifier)) {
2036
+ if (!statement.moduleSpecifier || !isStringLiteral(statement.moduleSpecifier)) {
2037
+ if (isNodeWithLocals(sourceFile) && sourceFile.locals) {
2038
+ const found = sourceFile.locals.get(declarationName);
2039
+ if (found && found.declarations && found.declarations[0]) {
2040
+ const declaration = found.declarations[0];
2041
+ if (declaration && isImportSpecifier(declaration)) {
2042
+ const importOrExport = declaration.parent.parent.parent;
2043
+ const found = this.resolveImportSpecifier(element.propertyName ? getEscapedText(element.propertyName) : declarationName, importOrExport, sourceFile);
2044
+ if (found) return found;
2045
+ } else if (declaration) {}
2046
+ return declaration;
2047
+ }
2048
+ }
2049
+ }
2050
+ } else {
2051
+ const found = this.resolveImportSpecifier(element.propertyName ? getEscapedText(element.propertyName) : declarationName, statement, sourceFile);
2052
+ if (found) return found;
2053
+ }
2054
+ }
2055
+ } else {
2056
+ const found = this.resolveImportSpecifier(declarationName, statement, sourceFile);
2057
+ if (found) return found;
2058
+ }
2059
+ }
2060
+ getTypeOfType(type) {
2061
+ if (!this.isWithReflection(this.sourceFile, type)) return;
2062
+ const program = new CompilerProgram(type, this.sourceFile);
2063
+ this.extractPackStructOfType(type, program);
2064
+ return this.packOpsAndStack(program);
2065
+ }
2066
+ packOpsAndStack(program) {
2067
+ const packStruct = program.buildPackStruct();
2068
+ if (packStruct.ops.length === 0) return;
2069
+ const packed = [...packStruct.stack, encodeOps(packStruct.ops)];
2070
+ return this.valueToExpression(packed);
2071
+ }
2072
+ /**
2073
+ * Note: We have to duplicate the expressions as it can be that incoming expression are from another file and contain wrong pos/end properties,
2074
+ * so the code generation is then broken when we simply reuse them. Wrong code like ``User.__type = [.toEqual({`` is then generated.
2075
+ * This function is probably not complete, but we add new copies when required.
2076
+ */
2077
+ valueToExpression(value) {
2078
+ return this.nodeConverter.toExpression(value);
2079
+ }
2080
+ /**
2081
+ * A class is decorated with type information by adding a static variable.
2082
+ *
2083
+ * class Model {
2084
+ * static __types = pack(ReflectionOp.string); //<-- encoded type information
2085
+ * title: string;
2086
+ * }
2087
+ */
2088
+ decorateClass(sourceFile, node) {
2089
+ if (!this.isWithReflection(sourceFile, node)) return node;
2090
+ const type = this.getTypeOfType(node);
2091
+ const __type = this.f.createPropertyDeclaration(this.f.createModifiersFromModifierFlags(ModifierFlags.Static), "__type", void 0, void 0, type);
2092
+ if (isClassDeclaration(node)) return this.f.updateClassDeclaration(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, this.f.createNodeArray([...node.members, __type]));
2093
+ return this.f.updateClassExpression(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, this.f.createNodeArray([...node.members, __type]));
2094
+ }
2095
+ /**
2096
+ * const fn = function() {}
2097
+ *
2098
+ * => const fn = __assignType(function() {}, [34])
2099
+ */
2100
+ decorateFunctionExpression(expression) {
2101
+ const encodedType = this.getTypeOfType(expression);
2102
+ if (!encodedType) return expression;
2103
+ return this.wrapWithAssignType(expression, encodedType);
2104
+ }
2105
+ /**
2106
+ * function name() {}
2107
+ *
2108
+ * => function name() {}; name.__type = 34;
2109
+ */
2110
+ decorateFunctionDeclaration(declaration) {
2111
+ const encodedType = this.getTypeOfType(declaration);
2112
+ if (!encodedType) return declaration;
2113
+ if (!declaration.name) {
2114
+ if (!declaration.body) return;
2115
+ const modifier = declaration.modifiers ? declaration.modifiers.filter((v) => v.kind !== SyntaxKind.ExportKeyword && v.kind !== SyntaxKind.DefaultKeyword && v.kind !== SyntaxKind.Decorator) : [];
2116
+ return this.f.createExportAssignment(void 0, void 0, this.wrapWithAssignType(this.f.createFunctionExpression(modifier, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, declaration.body), encodedType));
2117
+ }
2118
+ const statements = [declaration];
2119
+ statements.push(this.f.createExpressionStatement(this.f.createAssignment(this.f.createPropertyAccessExpression(serializeEntityNameAsExpression(this.f, declaration.name), "__type"), encodedType)));
2120
+ return statements;
2121
+ }
2122
+ /**
2123
+ * const fn = () => {}
2124
+ * => const fn = __assignType(() => {}, [34])
2125
+ */
2126
+ decorateArrowFunction(expression) {
2127
+ const encodedType = this.getTypeOfType(expression);
2128
+ if (!encodedType) return expression;
2129
+ return this.wrapWithAssignType(expression, encodedType);
2130
+ }
2131
+ /**
2132
+ * Object.assign(fn, {__type: []}) is much slower than a custom implementation like
2133
+ *
2134
+ * assignType(fn, [])
2135
+ *
2136
+ * where we embed assignType() at the beginning of the type.
2137
+ */
2138
+ wrapWithAssignType(fn, type) {
2139
+ this.embedAssignType = true;
2140
+ return this.f.createCallExpression(this.f.createIdentifier("__assignType"), void 0, [fn, type]);
2141
+ }
2142
+ /**
2143
+ * Emit `{ __meta?: never & [name, value] }` — the runtime shape of `TypeAnnotation<name, value>`.
2144
+ * Consumed later via `typeAnnotation.getForName(type, name)`.
2145
+ */
2146
+ emitTypeAnnotation(program, name, value) {
2147
+ program.pushFrame();
2148
+ program.pushFrame();
2149
+ program.pushOp(_deepkit_type_spec.ReflectionOp.never);
2150
+ program.pushFrame();
2151
+ program.pushOp(_deepkit_type_spec.ReflectionOp.literal, program.findOrAddStackEntry(name));
2152
+ program.pushOp(_deepkit_type_spec.ReflectionOp.literal, program.findOrAddStackEntry(value));
2153
+ program.pushOp(_deepkit_type_spec.ReflectionOp.tuple);
2154
+ program.popFrameImplicit();
2155
+ program.pushOp(_deepkit_type_spec.ReflectionOp.intersection);
2156
+ program.popFrameImplicit();
2157
+ program.pushOp(_deepkit_type_spec.ReflectionOp.propertySignature, program.findOrAddStackEntry("__meta"));
2158
+ program.pushOp(_deepkit_type_spec.ReflectionOp.optional);
2159
+ program.pushOp(_deepkit_type_spec.ReflectionOp.objectLiteral);
2160
+ program.popFrameImplicit();
2161
+ }
2162
+ collectJSDocAnnotations(node) {
2163
+ const parsed = extractJSDocTags(this.sourceFile, node);
2164
+ const annotations = [];
2165
+ const seen = /* @__PURE__ */ new Set();
2166
+ for (const tag of parsed.tags) {
2167
+ annotations.push(tag);
2168
+ seen.add(tag.name);
2169
+ }
2170
+ if (parsed.description && !seen.has("description")) annotations.unshift({
2171
+ name: "description",
2172
+ value: parsed.description
2173
+ });
2174
+ const descriptionTag = annotations.find((v) => v.name === "description");
2175
+ return {
2176
+ description: descriptionTag && typeof descriptionTag.value === "string" ? descriptionTag.value : parsed.description,
2177
+ annotations
2178
+ };
2179
+ }
2180
+ /**
2181
+ * Run `emitType()` then intersect the result with TypeAnnotations derived from JSDoc/TSDoc.
2182
+ * Also sets `ReflectionOp.description` when a description string is available (back-compat).
2183
+ *
2184
+ * @returns The resolved description string, if any.
2185
+ */
2186
+ withJSDocTypeAnnotations(program, node, emitType, options = {}) {
2187
+ const { description, annotations } = this.collectJSDocAnnotations(node);
2188
+ const applyDescriptionOp = options.applyDescriptionOp !== false;
2189
+ if (annotations.length === 0) {
2190
+ emitType();
2191
+ if (applyDescriptionOp && description) program.pushOp(_deepkit_type_spec.ReflectionOp.description, program.findOrAddStackEntry(description));
2192
+ return description;
2193
+ }
2194
+ program.pushFrame();
2195
+ emitType();
2196
+ for (const annotation of annotations) this.emitTypeAnnotation(program, annotation.name, annotation.value);
2197
+ program.pushOp(_deepkit_type_spec.ReflectionOp.intersection);
2198
+ program.popFrameImplicit();
2199
+ if (applyDescriptionOp && description) program.pushOp(_deepkit_type_spec.ReflectionOp.description, program.findOrAddStackEntry(description));
2200
+ return description;
2201
+ }
2202
+ /**
2203
+ * Checks if reflection was disabled/enabled in file via JSDoc attribute for a particular
2204
+ * Node, e.g `@reflection no`. If nothing is found, "reflection" config option needs to be used.
2205
+ */
2206
+ getExplicitReflectionMode(sourceFile, node) {
2207
+ let current = node;
2208
+ let reflectionComment = void 0;
2209
+ while ("undefined" === typeof reflectionComment && current) {
2210
+ const next = sourceFile && extractJSDocAttribute(sourceFile, current, "reflection");
2211
+ if ("undefined" !== typeof next) reflectionComment = next;
2212
+ current = current.parent;
2213
+ }
2214
+ if (reflectionComment === "" || reflectionComment === "true" || reflectionComment === "default" || reflectionComment === "enabled" || reflectionComment === "1") return true;
2215
+ if (reflectionComment === "false" || reflectionComment === "disabled" || reflectionComment === "never" || reflectionComment === "no" || reflectionComment === "0") return false;
2216
+ }
2217
+ };
2218
+ var DeclarationTransformer = class extends ReflectionTransformer {
2219
+ constructor() {
2220
+ super(...arguments);
2221
+ this.addExports = [];
2222
+ }
2223
+ transformSourceFile(sourceFile) {
2224
+ if (sourceFile.deepkitDeclarationTransformed) return sourceFile;
2225
+ this.sourceFile = sourceFile;
2226
+ this.addExports = [];
2227
+ const configResolver = this.getConfigResolver(sourceFile);
2228
+ const reflection = configResolver.match(sourceFile.fileName);
2229
+ Object.assign(this.compilerOptions, configResolver.config.compilerOptions);
2230
+ if (reflection.mode === "never") return sourceFile;
2231
+ const visitor = (node) => {
2232
+ node = visitEachChild(node, visitor, this.context);
2233
+ if ((isTypeAliasDeclaration(node) || isInterfaceDeclaration(node) || isEnumDeclaration(node)) && hasModifier(node, SyntaxKind.ExportKeyword)) {
2234
+ if (this.isWithReflection(sourceFile, node)) this.addExports.push({ identifier: getIdentifierName(this.getDeclarationVariableName(node.name)) });
2235
+ }
2236
+ return node;
2237
+ };
2238
+ this.sourceFile = visitNode(this.sourceFile, visitor);
2239
+ if (this.addExports.length) {
2240
+ const exports = [];
2241
+ const handledIdentifier = [];
2242
+ for (const imp of this.addExports) {
2243
+ if (handledIdentifier.includes(imp.identifier)) continue;
2244
+ handledIdentifier.push(imp.identifier);
2245
+ exports.push(this.f.createTypeAliasDeclaration([this.f.createModifier(SyntaxKind.ExportKeyword), this.f.createModifier(SyntaxKind.DeclareKeyword)], this.f.createIdentifier(imp.identifier), void 0, this.f.createArrayTypeNode(this.f.createKeywordTypeNode(SyntaxKind.AnyKeyword))));
2246
+ }
2247
+ this.sourceFile = this.f.updateSourceFile(this.sourceFile, [...this.sourceFile.statements, ...exports]);
2248
+ }
2249
+ this.sourceFile.deepkitDeclarationTransformed = true;
2250
+ return this.sourceFile;
2251
+ }
2252
+ };
2253
+ let loaded = false;
2254
+ const cache = new Cache();
2255
+ const transformer = function deepkitTransformer(context) {
2256
+ if (!loaded) {
2257
+ debug("@deepkit/type transformer loaded\n");
2258
+ loaded = true;
2259
+ }
2260
+ cache.tick();
2261
+ return new ReflectionTransformer(context, cache);
2262
+ };
2263
+ const declarationTransformer = function deepkitDeclarationTransformer(context) {
2264
+ return new DeclarationTransformer(context, cache);
2265
+ };
2266
+
2267
+ //#endregion
2268
+ //#region ../../../node_modules/.pnpm/@deepkit+type-compiler@1.0.19_patch_hash=bd438188cbc12e606ed4d519c25ab921a833fbc2d92357_e562d261195ccb1f28e41e80fc823414/node_modules/@deepkit/type-compiler/dist/esm/src/loader.js
2269
+ var DeepkitLoader = class {
2270
+ constructor() {
2271
+ this.options = {
2272
+ allowJs: true,
2273
+ declaration: false
2274
+ };
2275
+ this.host = typescript.default.createCompilerHost(this.options);
2276
+ this.program = typescript.default.createProgram([], this.options, this.host);
2277
+ this.printer = typescript.default.createPrinter({ newLine: typescript.default.NewLineKind.LineFeed });
2278
+ this.cache = new Cache();
2279
+ this.knownFiles = {};
2280
+ this.sourceFiles = {};
2281
+ const originReadFile = this.host.readFile;
2282
+ this.host.readFile = (fileName) => {
2283
+ if (this.knownFiles[fileName]) return this.knownFiles[fileName];
2284
+ return originReadFile.call(this.host, fileName);
2285
+ };
2286
+ this.host.writeFile = () => {};
2287
+ const originalGetSourceFile = this.host.getSourceFile;
2288
+ this.host.getSourceFile = (fileName, languageVersion, onError, shouldCreateNewSourceFile) => {
2289
+ if (this.sourceFiles[fileName]) return this.sourceFiles[fileName];
2290
+ return originalGetSourceFile.call(this.host, fileName, languageVersion, onError, shouldCreateNewSourceFile);
2291
+ };
2292
+ }
2293
+ transform(source, path) {
2294
+ this.knownFiles[path] = source;
2295
+ const sourceFile = typescript.default.createSourceFile(path, source, typescript.default.ScriptTarget.ESNext, true, path.endsWith(".tsx") ? typescript.default.ScriptKind.TSX : typescript.default.ScriptKind.TS);
2296
+ let newSource = source;
2297
+ typescript.default.transform(sourceFile, [(context) => {
2298
+ const transformer = new ReflectionTransformer(context, this.cache).forHost(this.host).withReflection({ reflection: "default" });
2299
+ return (node) => {
2300
+ const sourceFile = transformer.transformSourceFile(node);
2301
+ newSource = this.printer.printNode(typescript.default.EmitHint.SourceFile, sourceFile, sourceFile);
2302
+ return sourceFile;
2303
+ };
2304
+ }], this.options);
2305
+ return newSource;
2306
+ }
2307
+ };
2308
+
2309
+ //#endregion
2310
+ Object.defineProperty(exports, 'Cache', {
2311
+ enumerable: true,
2312
+ get: function () {
2313
+ return Cache;
2314
+ }
2315
+ });
2316
+ Object.defineProperty(exports, 'DeclarationTransformer', {
2317
+ enumerable: true,
2318
+ get: function () {
2319
+ return DeclarationTransformer;
2320
+ }
2321
+ });
2322
+ Object.defineProperty(exports, 'DeepkitLoader', {
2323
+ enumerable: true,
2324
+ get: function () {
2325
+ return DeepkitLoader;
2326
+ }
2327
+ });
2328
+ Object.defineProperty(exports, 'ReflectionTransformer', {
2329
+ enumerable: true,
2330
+ get: function () {
2331
+ return ReflectionTransformer;
2332
+ }
2333
+ });
2334
+ Object.defineProperty(exports, 'debugPackStruct', {
2335
+ enumerable: true,
2336
+ get: function () {
2337
+ return debugPackStruct;
2338
+ }
2339
+ });
2340
+ Object.defineProperty(exports, 'declarationTransformer', {
2341
+ enumerable: true,
2342
+ get: function () {
2343
+ return declarationTransformer;
2344
+ }
2345
+ });
2346
+ Object.defineProperty(exports, 'encodeOps', {
2347
+ enumerable: true,
2348
+ get: function () {
2349
+ return encodeOps;
2350
+ }
2351
+ });
2352
+ Object.defineProperty(exports, 'packSize', {
2353
+ enumerable: true,
2354
+ get: function () {
2355
+ return packSize;
2356
+ }
2357
+ });
2358
+ Object.defineProperty(exports, 'packSizeByte', {
2359
+ enumerable: true,
2360
+ get: function () {
2361
+ return packSizeByte;
2362
+ }
2363
+ });
2364
+ Object.defineProperty(exports, 'transformer', {
2365
+ enumerable: true,
2366
+ get: function () {
2367
+ return transformer;
2368
+ }
2369
+ });