@runtyped/type-compiler 1.0.20-alpha.3 → 1.0.20-alpha.5

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