-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
ast-utils.ts
719 lines (651 loc) · 18.9 KB
/
ast-utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
import * as ts from 'typescript';
import { findNodes } from 'nx/src/utils/typescript';
import { getSourceNodes } from '@nrwl/workspace/src/utilities/typescript/get-source-nodes';
import * as path from 'path';
import { names, readProjectConfiguration, Tree } from '@nrwl/devkit';
import {
getImport,
insertChange,
removeChange,
replaceChange,
} from '@nrwl/workspace/src/utilities/ast-utils';
function _angularImportsFromNode(
node: ts.ImportDeclaration,
_sourceFile: ts.SourceFile
): { [name: string]: string } {
const ms = node.moduleSpecifier;
let modulePath: string;
switch (ms.kind) {
case ts.SyntaxKind.StringLiteral:
modulePath = (ms as ts.StringLiteral).text;
break;
default:
return {};
}
if (!modulePath.startsWith('@angular/')) {
return {};
}
if (node.importClause) {
if (node.importClause.name) {
// This is of the form `import Name from 'path'`. Ignore.
return {};
} else if (node.importClause.namedBindings) {
const nb = node.importClause.namedBindings;
if (nb.kind == ts.SyntaxKind.NamespaceImport) {
// This is of the form `import * as name from 'path'`. Return `name.`.
return {
[`${(nb as ts.NamespaceImport).name.text}.`]: modulePath,
};
} else {
// This is of the form `import {a,b,c} from 'path'`
const namedImports = nb as ts.NamedImports;
return namedImports.elements
.map((is: ts.ImportSpecifier) =>
is.propertyName ? is.propertyName.text : is.name.text
)
.reduce((acc: { [name: string]: string }, curr: string) => {
acc[curr] = modulePath;
return acc;
}, {});
}
}
return {};
} else {
// This is of the form `import 'path';`. Nothing to do.
return {};
}
}
export function getDecoratorMetadata(
source: ts.SourceFile,
identifier: string,
module: string
): ts.Node[] {
const angularImports: { [name: string]: string } = findNodes(
source,
ts.SyntaxKind.ImportDeclaration
)
.map((node: ts.ImportDeclaration) => _angularImportsFromNode(node, source))
.reduce(
(
acc: { [name: string]: string },
current: { [name: string]: string }
) => {
for (const key of Object.keys(current)) {
acc[key] = current[key];
}
return acc;
},
{}
);
return getSourceNodes(source)
.filter((node) => {
return (
node.kind == ts.SyntaxKind.Decorator &&
(node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression
);
})
.map((node) => (node as ts.Decorator).expression as ts.CallExpression)
.filter((expr) => {
if (expr.expression.kind == ts.SyntaxKind.Identifier) {
const id = expr.expression as ts.Identifier;
return (
id.getFullText(source) == identifier &&
angularImports[id.getFullText(source)] === module
);
} else if (
expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression
) {
// This covers foo.NgModule when importing * as foo.
const paExpr = expr.expression as ts.PropertyAccessExpression;
// If the left expression is not an identifier, just give up at that point.
if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) {
return false;
}
const id = paExpr.name.text;
const moduleId = (paExpr.expression as ts.Identifier).getText(source);
return id === identifier && angularImports[`${moduleId}.`] === module;
}
return false;
})
.filter(
(expr) =>
expr.arguments[0] &&
expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression
)
.map((expr) => expr.arguments[0] as ts.ObjectLiteralExpression);
}
function _addSymbolToNgModuleMetadata(
host: Tree,
source: ts.SourceFile,
ngModulePath: string,
metadataField: string,
expression: string
): ts.SourceFile {
const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
let node: any = nodes[0]; // tslint:disable-line:no-any
// Find the decorator declaration.
if (!node) {
return source;
}
// Get all the children property assignment of object literals.
const matchingProperties: ts.ObjectLiteralElement[] = (
node as ts.ObjectLiteralExpression
).properties
.filter((prop) => prop.kind == ts.SyntaxKind.PropertyAssignment)
// Filter out every fields that's not "metadataField". Also handles string literals
// (but not expressions).
.filter((prop: ts.PropertyAssignment) => {
const name = prop.name;
switch (name.kind) {
case ts.SyntaxKind.Identifier:
return (name as ts.Identifier).getText(source) == metadataField;
case ts.SyntaxKind.StringLiteral:
return (name as ts.StringLiteral).text == metadataField;
}
return false;
});
// Get the last node of the array literal.
if (!matchingProperties) {
return source;
}
if (matchingProperties.length == 0) {
// We haven't found the field in the metadata declaration. Insert a new field.
const expr = node as ts.ObjectLiteralExpression;
let position: number;
let toInsert: string;
if (expr.properties.length == 0) {
position = expr.getEnd() - 1;
toInsert = ` ${metadataField}: [${expression}]\n`;
} else {
node = expr.properties[expr.properties.length - 1];
position = node.getEnd();
// Get the indentation of the last element, if any.
const text = node.getFullText(source);
if (text.match('^\r?\r?\n')) {
toInsert = `,${
text.match(/^\r?\n\s+/)[0]
}${metadataField}: [${expression}]`;
} else {
toInsert = `, ${metadataField}: [${expression}]`;
}
}
return insertChange(host, source, ngModulePath, position, toInsert);
}
const assignment = matchingProperties[0] as ts.PropertyAssignment;
// If it's not an array, nothing we can do really.
if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
return source;
}
const arrLiteral = assignment.initializer as ts.ArrayLiteralExpression;
if (arrLiteral.elements.length == 0) {
// Forward the property.
node = arrLiteral;
} else {
node = arrLiteral.elements;
}
if (!node) {
console.log(
'No app module found. Please add your new class to your component.'
);
return source;
}
const isArray = Array.isArray(node);
if (isArray) {
const nodeArray = node as {} as Array<ts.Node>;
const symbolsArray = nodeArray.map((node) => node.getText());
if (symbolsArray.includes(expression)) {
return source;
}
node = node[node.length - 1];
}
let toInsert: string;
let position = node.getEnd();
if (!isArray && node.kind == ts.SyntaxKind.ObjectLiteralExpression) {
// We haven't found the field in the metadata declaration. Insert a new
// field.
const expr = node as ts.ObjectLiteralExpression;
if (expr.properties.length == 0) {
position = expr.getEnd() - 1;
toInsert = ` ${metadataField}: [${expression}]\n`;
} else {
node = expr.properties[expr.properties.length - 1];
position = node.getEnd();
// Get the indentation of the last element, if any.
const text = node.getFullText(source);
if (text.match('^\r?\r?\n')) {
toInsert = `,${
text.match(/^\r?\n\s+/)[0]
}${metadataField}: [${expression}]`;
} else {
toInsert = `, ${metadataField}: [${expression}]`;
}
}
} else if (!isArray && node.kind == ts.SyntaxKind.ArrayLiteralExpression) {
// We found the field but it's empty. Insert it just before the `]`.
position--;
toInsert = `${expression}`;
} else {
// Get the indentation of the last element, if any.
const text = node.getFullText(source);
if (text.match(/^\r?\n/)) {
toInsert = `,${text.match(/^\r?\n(\r?)\s+/)[0]}${expression}`;
} else {
toInsert = `, ${expression}`;
}
}
return insertChange(host, source, ngModulePath, position, toInsert);
}
export function removeFromNgModule(
host: Tree,
source: ts.SourceFile,
modulePath: string,
property: string
): ts.SourceFile {
const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
let node: any = nodes[0]; // tslint:disable-line:no-any
// Find the decorator declaration.
if (!node) {
return source;
}
// Get all the children property assignment of object literals.
const matchingProperty = getMatchingProperty(
source,
property,
'NgModule',
'@angular/core'
);
if (matchingProperty) {
return removeChange(
host,
source,
modulePath,
matchingProperty.getStart(source),
matchingProperty.getFullText(source)
);
}
}
export function addImportToModule(
host: Tree,
source: ts.SourceFile,
modulePath: string,
symbolName: string
): ts.SourceFile {
return _addSymbolToNgModuleMetadata(
host,
source,
modulePath,
'imports',
symbolName
);
}
export function addImportToTestBed(
host: Tree,
source: ts.SourceFile,
specPath: string,
symbolName: string
): ts.SourceFile {
const allCalls: ts.CallExpression[] = <any>(
findNodes(source, ts.SyntaxKind.CallExpression)
);
const configureTestingModuleObjectLiterals = allCalls
.filter((c) => c.expression.kind === ts.SyntaxKind.PropertyAccessExpression)
.filter(
(c: any) => c.expression.name.getText(source) === 'configureTestingModule'
)
.map((c) =>
c.arguments[0].kind === ts.SyntaxKind.ObjectLiteralExpression
? c.arguments[0]
: null
);
if (configureTestingModuleObjectLiterals.length > 0) {
const startPosition = configureTestingModuleObjectLiterals[0]
.getFirstToken(source)
.getEnd();
return insertChange(
host,
source,
specPath,
startPosition,
`imports: [${symbolName}], `
);
}
return source;
}
export function addDeclarationsToTestBed(
host: Tree,
source: ts.SourceFile,
specPath: string,
symbolName: string[]
): ts.SourceFile {
const allCalls: ts.CallExpression[] = <any>(
findNodes(source, ts.SyntaxKind.CallExpression)
);
const configureTestingModuleObjectLiterals = allCalls
.filter((c) => c.expression.kind === ts.SyntaxKind.PropertyAccessExpression)
.filter(
(c: any) => c.expression.name.getText(source) === 'configureTestingModule'
)
.map((c) =>
c.arguments[0].kind === ts.SyntaxKind.ObjectLiteralExpression
? c.arguments[0]
: null
);
if (configureTestingModuleObjectLiterals.length > 0) {
const startPosition = configureTestingModuleObjectLiterals[0]
.getFirstToken(source)
.getEnd();
return insertChange(
host,
source,
specPath,
startPosition,
`declarations: [${symbolName.join(',')}], `
);
}
return source;
}
export function replaceIntoToTestBed(
host: Tree,
source: ts.SourceFile,
specPath: string,
newSymbol: string,
previousSymbol: string
): ts.SourceFile {
const allCalls: ts.CallExpression[] = <any>(
findNodes(source, ts.SyntaxKind.CallExpression)
);
const configureTestingModuleObjectLiterals = allCalls
.filter((c) => c.expression.kind === ts.SyntaxKind.PropertyAccessExpression)
.filter(
(c: any) => c.expression.name.getText(source) === 'configureTestingModule'
)
.map((c) =>
c.arguments[0].kind === ts.SyntaxKind.ObjectLiteralExpression
? c.arguments[0]
: null
);
if (configureTestingModuleObjectLiterals.length > 0) {
const startPosition = configureTestingModuleObjectLiterals[0]
.getFirstToken(source)
.getEnd();
return replaceChange(
host,
source,
specPath,
startPosition,
newSymbol,
previousSymbol
);
}
return source;
}
export function getBootstrapComponent(
source: ts.SourceFile,
moduleClassName: string
): string {
const bootstrap = getMatchingProperty(
source,
'bootstrap',
'NgModule',
'@angular/core'
);
if (!bootstrap) {
throw new Error(`Cannot find bootstrap components in '${moduleClassName}'`);
}
const c = bootstrap.getChildren();
const nodes = c[c.length - 1].getChildren();
const bootstrapComponent = nodes.slice(1, nodes.length - 1)[0];
if (!bootstrapComponent) {
throw new Error(`Cannot find bootstrap components in '${moduleClassName}'`);
}
return bootstrapComponent.getText();
}
function getMatchingProperty(
source: ts.SourceFile,
property: string,
identifier: string,
module: string
): ts.ObjectLiteralElement {
const nodes = getDecoratorMetadata(source, identifier, module);
let node: any = nodes[0]; // tslint:disable-line:no-any
if (!node) return null;
// Get all the children property assignment of object literals.
return getMatchingObjectLiteralElement(node, source, property);
}
export function addRouteToNgModule(
host: Tree,
ngModulePath: string,
source: ts.SourceFile,
route: string
): ts.SourceFile {
const routes = getListOfRoutes(source);
if (!routes) return source;
if (routes.hasTrailingComma || routes.length === 0) {
return insertChange(host, source, ngModulePath, routes.end, route);
} else {
return insertChange(host, source, ngModulePath, routes.end, `, ${route}`);
}
}
function getListOfRoutes(
source: ts.SourceFile
): ts.NodeArray<ts.Expression> | null {
const imports: any = getMatchingProperty(
source,
'imports',
'NgModule',
'@angular/core'
);
if (imports?.initializer.kind === ts.SyntaxKind.ArrayLiteralExpression) {
const a = imports.initializer as ts.ArrayLiteralExpression;
for (const e of a.elements) {
if (e.kind === ts.SyntaxKind.CallExpression) {
const ee = e as ts.CallExpression;
const text = ee.expression.getText(source);
if (
(text === 'RouterModule.forRoot' ||
text === 'RouterModule.forChild') &&
ee.arguments.length > 0
) {
const routes = ee.arguments[0];
if (routes.kind === ts.SyntaxKind.ArrayLiteralExpression) {
return (routes as ts.ArrayLiteralExpression).elements;
} else if (routes.kind === ts.SyntaxKind.Identifier) {
// find the array expression
const variableDeclarations = findNodes(
source,
ts.SyntaxKind.VariableDeclaration
) as ts.VariableDeclaration[];
const routesDeclaration = variableDeclarations.find((x) => {
return x.name.getText() === routes.getText();
});
if (routesDeclaration) {
return (
routesDeclaration.initializer as ts.ArrayLiteralExpression
).elements;
}
}
}
}
}
}
return null;
}
export function addProviderToModule(
host: Tree,
source: ts.SourceFile,
modulePath: string,
symbolName: string
): ts.SourceFile {
return _addSymbolToNgModuleMetadata(
host,
source,
modulePath,
'providers',
symbolName
);
}
export function addDeclarationToModule(
host: Tree,
source: ts.SourceFile,
modulePath: string,
symbolName: string
): ts.SourceFile {
return _addSymbolToNgModuleMetadata(
host,
source,
modulePath,
'declarations',
symbolName
);
}
export function addEntryComponents(
host: Tree,
source: ts.SourceFile,
modulePath: string,
symbolName: string
): ts.SourceFile {
return _addSymbolToNgModuleMetadata(
host,
source,
modulePath,
'entryComponents',
symbolName
);
}
export function readBootstrapInfo(
host: Tree,
app: string
): {
moduleSpec: string;
modulePath: string;
mainPath: string;
moduleClassName: string;
moduleSource: ts.SourceFile;
bootstrapComponentClassName: string;
bootstrapComponentFileName: string;
} {
const config = readProjectConfiguration(host, app);
let mainPath;
try {
mainPath = config.targets.build.options.main;
} catch (e) {
throw new Error('Main file cannot be located');
}
if (!host.exists(mainPath)) {
throw new Error('Main file cannot be located');
}
const mainSource = host.read(mainPath)!.toString('utf-8');
const main = ts.createSourceFile(
mainPath,
mainSource,
ts.ScriptTarget.Latest,
true
);
const moduleImports = getImport(
main,
(s: string) => s.indexOf('.module') > -1
);
if (moduleImports.length !== 1) {
throw new Error(`main.ts can only import a single module`);
}
const moduleImport = moduleImports[0];
const moduleClassName = moduleImport.bindings.filter((b) =>
b.endsWith('Module')
)[0];
const modulePath = `${path.join(
path.dirname(mainPath),
moduleImport.moduleSpec
)}.ts`;
if (!host.exists(modulePath)) {
throw new Error(`Cannot find '${modulePath}'`);
}
const moduleSourceText = host.read(modulePath)!.toString('utf-8');
const moduleSource = ts.createSourceFile(
modulePath,
moduleSourceText,
ts.ScriptTarget.Latest,
true
);
const bootstrapComponentClassName = getBootstrapComponent(
moduleSource,
moduleClassName
);
const bootstrapComponentFileName = `./${path.join(
path.dirname(moduleImport.moduleSpec),
`${
names(
bootstrapComponentClassName.substring(
0,
bootstrapComponentClassName.length - 9
)
).fileName
}.component`
)}`;
return {
moduleSpec: moduleImport.moduleSpec,
mainPath,
modulePath,
moduleSource,
moduleClassName,
bootstrapComponentClassName,
bootstrapComponentFileName,
};
}
export function getDecoratorPropertyValueNode(
host: Tree,
modulePath: string,
identifier: string,
property: string,
module: string
) {
const moduleSourceText = host.read(modulePath)!.toString('utf-8');
const moduleSource = ts.createSourceFile(
modulePath,
moduleSourceText,
ts.ScriptTarget.Latest,
true
);
const templateNode = getMatchingProperty(
moduleSource,
property,
identifier,
module
);
return templateNode.getChildAt(templateNode.getChildCount() - 1);
}
function getMatchingObjectLiteralElement(
node: any,
source: ts.SourceFile,
property: string
) {
return (
(node as ts.ObjectLiteralExpression).properties
.filter((prop) => prop.kind == ts.SyntaxKind.PropertyAssignment)
// Filter out every fields that's not "metadataField". Also handles string literals
// (but not expressions).
.filter((prop: ts.PropertyAssignment) => {
const name = prop.name;
switch (name.kind) {
case ts.SyntaxKind.Identifier:
return (name as ts.Identifier).getText(source) === property;
case ts.SyntaxKind.StringLiteral:
return (name as ts.StringLiteral).text === property;
}
return false;
})[0]
);
}
export function getTsSourceFile(host: Tree, path: string): ts.SourceFile {
const buffer = host.read(path);
if (!buffer) {
throw new Error(`Could not read TS file (${path}).`);
}
const content = buffer.toString();
const source = ts.createSourceFile(
path,
content,
ts.ScriptTarget.Latest,
true
);
return source;
}