@runtyped/type-compiler 1.0.20-alpha.1

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