-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathts-utils.ts
663 lines (562 loc) · 21 KB
/
ts-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
import { dirname } from 'path';
import {
addImportToModule,
addBootstrapToModule,
addSymbolToNgModuleMetadata,
findNodes,
} from '@schematics/angular/utility/ast-utils';
import { InsertChange, Change } from '@schematics/angular/utility/change';
import { SchematicsException, Rule, Tree } from '@angular-devkit/schematics';
import * as ts from 'typescript';
import { toComponentClassName, Node, removeNode, getFileContents, getJsonFile } from './utils';
class RemoveContent implements Node {
constructor(private pos: number, private end: number) {
}
getStart() {
return this.pos;
}
getFullStart() {
return this.pos;
}
getEnd() {
return this.end;
}
}
export function getSymbolsToAddToObject(path: string, node: any, metadataField: string, symbolName: string) {
// Get all the children property assignment of object literals.
const matchingProperties: Array<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() === 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 [];
}
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 pos: number;
let textToInsert: string;
if (expr.properties.length === 0) {
pos = expr.getEnd() - 1;
textToInsert = ` ${metadataField}: [${symbolName}],\n`;
} else {
node = expr.properties[expr.properties.length - 1];
pos = node.getEnd();
// Get the indentation of the last element, if any.
const text = node.getFullText();
const matches = text.match(/^\r?\n\s*/);
if (matches && matches.length > 0) {
textToInsert = `,${matches[0]}${metadataField}: ${symbolName},`;
} else {
textToInsert = `, ${metadataField}: ${symbolName},`;
}
}
return [new InsertChange(path, pos, textToInsert)];
}
const assignment = matchingProperties[0] as ts.PropertyAssignment;
// If it's not an array, keep the original value.
if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
return [];
}
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 [];
}
if (Array.isArray(node)) {
const nodeArray = node as {} as Array<ts.Node>;
const symbolsArray = nodeArray.map((n) => n.getText());
if (symbolsArray.indexOf(symbolName) !== -1) {
return [];
}
node = node[node.length - 1];
}
let toInsert: string;
let position = node.getEnd();
if (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}: [${symbolName}],\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();
if (text.match('^\r?\r?\n')) {
toInsert = `,${text.match(/^\r?\n\s+/)[0]}${metadataField}: [${symbolName},]`;
} else {
toInsert = `, ${metadataField}: [${symbolName},]`;
}
}
} else if (node.kind === ts.SyntaxKind.ArrayLiteralExpression) {
// We found the field but it's empty. Insert it just before the `]`.
position--;
toInsert = `${symbolName}`;
} else {
// Get the indentation of the last element, if any.
const text = node.getFullText();
if (text.match(/^\r?\n/)) {
toInsert = `,${text.match(/^\r?\n(\r?)\s+/)[0]}${symbolName},`;
} else {
toInsert = `, ${symbolName},`;
}
}
return [new InsertChange(path, position, toInsert)];
}
export function findFullImports(importName: string, source: ts.SourceFile):
Array<ts.ImportDeclaration | ts.ImportSpecifier | RemoveContent> {
const allImports = collectDeepNodes<ts.ImportDeclaration>(source, ts.SyntaxKind.ImportDeclaration);
return allImports
// Filter out import statements that are either `import 'XYZ'` or `import * as X from 'XYZ'`.
.filter(({ importClause: clause }) =>
clause && !clause.name && clause.namedBindings &&
clause.namedBindings.kind === ts.SyntaxKind.NamedImports,
)
.reduce((
imports: Array<ts.ImportDeclaration | ts.ImportSpecifier | RemoveContent>,
importDecl: ts.ImportDeclaration,
) => {
const importClause = importDecl.importClause as ts.ImportClause;
const namedImports = importClause.namedBindings as ts.NamedImports;
namedImports.elements.forEach((importSpec: ts.ImportSpecifier) => {
const importId = importSpec.name;
if (!(importId.text === importName)) {
return;
}
if (namedImports.elements.length === 1) {
imports.push(importDecl);
} else {
const toRemove = normalizeNodeToRemove<ts.ImportSpecifier>(importSpec, source);
imports.push(toRemove);
}
});
return imports;
}, []);
}
export function findImports(importName: string, source: ts.SourceFile):
Array<ts.ImportDeclaration> {
const allImports = collectDeepNodes<ts.ImportDeclaration>(source, ts.SyntaxKind.ImportDeclaration);
return allImports
.filter(({ importClause: clause }) =>
clause && !clause.name && clause.namedBindings &&
clause.namedBindings.kind === ts.SyntaxKind.NamedImports,
)
.reduce((
imports: Array<ts.ImportDeclaration>,
importDecl: ts.ImportDeclaration,
) => {
const importClause = importDecl.importClause as ts.ImportClause;
const namedImports = importClause.namedBindings as ts.NamedImports;
namedImports.elements.forEach((importSpec: ts.ImportSpecifier) => {
const importId = importSpec.name;
if (importId.text === importName) {
imports.push(importDecl);
}
});
return imports;
}, []);
}
export function findMetadataValueInArray(source: ts.Node, property: string, value: string):
Array<ts.Node | RemoveContent> {
const decorators = collectDeepNodes<ts.Decorator>(source, ts.SyntaxKind.Decorator);
return getNodesToRemoveFromNestedArray(decorators, property, value);
}
export function getNodesToRemoveFromNestedArray(nodes: Array<ts.Node>, property: string, value: string) {
const valuesNode = nodes
.reduce(
(allNodes, current) => [
...allNodes,
...collectDeepNodes<ts.PropertyAssignment>(current, ts.SyntaxKind.PropertyAssignment),
], [])
.find((assignment) => {
let isValueForProperty = false;
ts.forEachChild(assignment, (child: ts.Node) => {
if (child.kind === ts.SyntaxKind.Identifier && child.getText() === property) {
isValueForProperty = true;
}
});
return isValueForProperty;
});
if (!valuesNode) {
return [];
}
let arrayLiteral;
ts.forEachChild(valuesNode, (child: ts.Node) => {
if (child.kind === ts.SyntaxKind.ArrayLiteralExpression) {
arrayLiteral = child;
}
});
if (!arrayLiteral) {
return [];
}
const values: Array<ts.Node | RemoveContent> = [];
ts.forEachChild(arrayLiteral, (child: ts.Node) => {
if (child.getText() === value) {
const toRemove = normalizeNodeToRemove(child, arrayLiteral);
values.push(toRemove);
}
});
return values;
}
/**
*
* @param node The node that should be removed
* @param source The source file that we are removing from
* This method ensures that if there's a comma before or after the node,
* it will be removed, too.
*/
function normalizeNodeToRemove<T extends ts.Node>(node: T, source: ts.Node)
: (T | RemoveContent) {
const content = source.getText();
const nodeStart = node.getFullStart();
const nodeEnd = node.getEnd();
const start = nodeStart - source.getFullStart();
const symbolBefore = content.substring(start - 1, start);
if (symbolBefore === ',') {
return new RemoveContent(nodeStart - 1, nodeEnd);
} else {
return new RemoveContent(nodeStart, nodeEnd + 1);
}
}
export function addBootstrapToNgModule(modulePath: string, rootComponentName: string): Rule {
return (host: Tree) => {
const content = host.read(modulePath);
if (!content) {
throw new SchematicsException(`File ${modulePath} does not exist.`);
}
const sourceText = content.toString('utf-8');
const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
const componentModule = `./${rootComponentName}.component`;
const rootComponentClassName = toComponentClassName(rootComponentName);
const importChanges = addImportToModule(<any>source,
modulePath,
'NativeScriptModule',
'@nativescript/angular');
const bootstrapChanges = addBootstrapToModule(<any>source,
modulePath,
rootComponentClassName,
componentModule);
const declarationChanges = addSymbolToNgModuleMetadata(
<any>source,
modulePath,
'declarations',
rootComponentClassName,
);
const changes = [
...importChanges,
...bootstrapChanges,
...declarationChanges,
];
const recorder = host.beginUpdate(modulePath);
for (const change of changes) {
if (change instanceof InsertChange) {
recorder.insertLeft(change.pos, change.toAdd);
}
}
host.commitUpdate(recorder);
return host;
};
}
export function collectDeepNodes<T extends ts.Node>(node: ts.Node, kind: ts.SyntaxKind): Array<T> {
const nodes: Array<T> = [];
const helper = (child: ts.Node) => {
if (child.kind === kind) {
nodes.push(child as T);
}
ts.forEachChild(child, helper);
};
ts.forEachChild(node, helper);
return nodes;
}
export function filterByChildNode(
root: ts.Node,
condition: (node: ts.Node) => boolean,
): boolean {
let matches = false;
const helper = (child: ts.Node) => {
if (condition(child)) {
matches = true;
return;
}
};
ts.forEachChild(root, helper);
return matches;
}
export const getDecoratedClass = (tree: Tree, filePath: string, decoratorName: string, className: string) => {
return getDecoratedClasses(tree, filePath, decoratorName)
.find((c) => !!(c.name && c.name.getText() === className));
};
export const getDecoratedClasses = (tree: Tree, filePath: string, decoratorName: string) => {
const moduleSource = getSourceFile(tree, filePath);
const classes = collectDeepNodes<ts.ClassDeclaration>(moduleSource, ts.SyntaxKind.ClassDeclaration);
return classes.filter((c) => !!getDecorator(c, decoratorName));
};
export const getDecoratorMetadataFromClass = (classNode: ts.Node, decoratorName: string) => {
const decorator = getDecorator(classNode, decoratorName);
if (!decorator) {
return;
}
return (<ts.CallExpression>decorator.expression).arguments[0];
};
const getDecorator = (node: ts.Node, name: string) => {
return node.decorators && node.decorators.find((decorator: ts.Decorator) =>
decorator.expression.kind === ts.SyntaxKind.CallExpression &&
(<ts.CallExpression>decorator.expression).expression.getText() === name,
);
};
export const removeMetadataArrayValue = (tree: Tree, filePath: string, property: string, value: string) => {
const source = getSourceFile(tree, filePath);
const nodesToRemove = findMetadataValueInArray(source, property, value);
nodesToRemove.forEach((declaration) =>
removeNode(declaration, filePath, tree),
);
};
export const removeImport = (tree: Tree, filePath: string, importName: string) => {
const source = getSourceFile(tree, filePath);
const importsToRemove = findFullImports(importName, source);
importsToRemove.forEach((declaration) =>
removeNode(declaration, filePath, tree),
);
};
/**
* Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`
* or after the last of occurence of `syntaxKind` if the last occurence is a sub child
* of ts.SyntaxKind[nodes[i].kind] and save the changes in file.
*
* @param nodes insert after the last occurence of nodes
* @param toInsert string to insert
* @param file file to insert changes into
* @param fallbackPos position to insert if toInsert happens to be the first occurence
* @param syntaxKind the ts.SyntaxKind of the subchildren to insert after
* @return Change instance
* @throw Error if toInsert is first occurence but fall back is not set
*/
export function insertBeforeFirstOccurence(nodes: Array<ts.Node>,
toInsert: string,
file: string,
fallbackPos: number,
syntaxKind?: ts.SyntaxKind): Change {
let firstItem: any = nodes.sort(nodesByPosition).shift();
if (!firstItem) {
throw new Error();
}
if (syntaxKind) {
firstItem = findNodes(<any>firstItem, syntaxKind).sort(<any>nodesByPosition).shift();
}
if (!firstItem && fallbackPos === undefined) {
throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`);
}
const firstItemPosition: number = firstItem ? firstItem.getStart() : fallbackPos;
return new InsertChange(file, firstItemPosition, toInsert);
}
/**
* Helper for sorting nodes.
* @return function to sort nodes in increasing order of position in sourceFile
*/
function nodesByPosition(first: ts.Node, second: ts.Node): number {
return first.getStart() - second.getStart();
}
export interface SearchParam {
name?: string;
kind: ts.SyntaxKind;
}
export function findNode<T extends ts.Node>(node: ts.Node, searchParams: Array<SearchParam>, filter: string = ''): T {
const matchingNodes = findMatchingNodes<T>(node, searchParams);
if (matchingNodes.length === 0) {
// TODO: This might require a better error message.
const nodesText = searchParams
.map((item) => item.name || item.kind)
.reduce((name, currentResult) => name + ' => ' + currentResult);
throw new SchematicsException(`Failed to find ${nodesText} in ${node.getSourceFile().fileName}.`);
}
const result = matchingNodes
.filter((n) => n.getText()
.includes(filter));
if (result.length !== 1) {
const nodesText = searchParams
.map((item) => item.name)
.reduce((name, concatNames) => name + ' => ' + concatNames);
if (result.length === 0) {
if (filter !== '') {
throw new SchematicsException(`Failed to find ${filter} for ${nodesText} in ${node.getSourceFile().fileName}.`);
} else {
throw new SchematicsException(`Failed to find ${nodesText} in ${node.getSourceFile().fileName}.`);
}
} else {
throw new SchematicsException(
`Found too many [${result.length} / expected 1] ${nodesText} in ${node.getSourceFile().fileName}.`,
);
}
}
return result[0];
}
export function findMatchingNodes<T extends ts.Node>(
node: ts.Node,
searchParams: Array<SearchParam>,
index = 0,
): Array<T> {
const searchParam = searchParams[index];
const nodes: Array<T> = [];
const helper = (child: ts.Node) => {
if (isMatchingNode(child, searchParam)) {
if (index === searchParams.length - 1) {
nodes.push(child as T);
} else {
nodes.push(...findMatchingNodes<T>(child, searchParams, index + 1));
}
} else {
if (child.getChildCount() > 0) {
ts.forEachChild(child, helper);
}
}
};
ts.forEachChild(node, helper);
return nodes;
}
/**
* Check if the node.kind matches the searchParam.kind
* Also, if name provided, then check if we got the node with the right param name
*/
function isMatchingNode(node: ts.Node, searchParam: SearchParam) {
if (node.kind !== searchParam.kind) {
return false;
}
// If name provided the run it through checkNameForKind check
// otherwise just return true
return (searchParam.name) ? checkNameForKind(node, searchParam) : true;
}
function checkNameForKind(node: ts.Node, searchParam: SearchParam): boolean {
if (!searchParam.name) {
throw new SchematicsException(
`checkNameForKind shouldn't be called without a name. Object => ${JSON.stringify(searchParam)}`,
);
}
let child: ts.Node;
switch (searchParam.kind) {
case ts.SyntaxKind.VariableDeclaration:
case ts.SyntaxKind.PropertyAssignment:
child = node.getChildAt(0);
break;
case ts.SyntaxKind.CallExpression:
const callExpression = node as ts.CallExpression;
const expression = callExpression.expression;
// if function is an object's property - i.e. parent.fname()
if (ts.isPropertyAccessExpression(expression)) {
child = expression.name;
} else {
child = expression;
}
break;
case ts.SyntaxKind.Identifier:
child = node;
break;
case ts.SyntaxKind.NewExpression:
const newExpression = node as ts.NewExpression;
child = newExpression.expression;
break;
case ts.SyntaxKind.ImportDeclaration:
const importDeclaration = node as ts.ImportDeclaration;
if (!importDeclaration.importClause || !importDeclaration.importClause.namedBindings) {
return false;
}
const namedBindings = importDeclaration.importClause.namedBindings;
// for imports like: import { a, b } from 'path'
// import names [a,b] are at: node.importClause.namedBindings.elements
if (ts.isNamedImports(namedBindings)) {
const elements = namedBindings.elements;
return elements.some((element) => element.getText() === searchParam.name);
}
// otherwise, it is an import like: import * as abc from 'path'
// import name [abc] is at: node.importClause.namedBindings.name
child = namedBindings.name;
break;
case ts.SyntaxKind.ClassDeclaration:
const classDeclaration = node as ts.ClassDeclaration;
if (!classDeclaration.name) {
return false;
}
child = classDeclaration.name;
break;
case ts.SyntaxKind.Decorator:
const decorator = node as ts.Decorator;
const decoratorCallExpression = decorator.expression as ts.CallExpression;
child = decoratorCallExpression.expression;
break;
default:
throw new SchematicsException(`compareNameForKind: not prepared for this [${node.kind}] ts.SyntaxKind`);
}
return child.getText() === searchParam.name;
}
export function findImportPath(source: ts.Node, name) {
const node = findNode<ts.ImportDeclaration>(source, [
{ kind: ts.SyntaxKind.ImportDeclaration, name },
]);
const moduleSpecifier = node.moduleSpecifier as ts.StringLiteral;
return moduleSpecifier.text;
}
export const updateNodeText = (tree: Tree, node: ts.Node, newText: string) => {
const recorder = tree.beginUpdate(node.getSourceFile().fileName);
recorder.remove(node.getStart(), node.getText().length);
recorder.insertLeft(node.getStart(), newText);
tree.commitUpdate(recorder);
};
export const replaceTextInNode = (tree: Tree, node: ts.Node, oldText: string, newText: string) => {
const index = node.getStart() + node.getText().indexOf(oldText);
const recorder = tree.beginUpdate(node.getSourceFile().fileName);
recorder.remove(index, oldText.length);
recorder.insertLeft(index, newText);
tree.commitUpdate(recorder);
};
export const getSourceFile = (host: Tree, path: string): ts.SourceFile => {
const buffer = host.read(path);
if (!buffer) {
throw new SchematicsException(
`Could not find file at ${path}. See https://github.com/NativeScript/nativescript-schematics/issues/172.`,
);
}
const content = buffer.toString();
const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true);
return source;
};
export function getCompilerOptions(tree: Tree, tsConfigPath: string)
: ts.CompilerOptions | undefined {
const tsConfigObject = parseTsConfigFile(tree, tsConfigPath);
if (!tsConfigObject) {
return;
}
const compilerOptions = tsConfigObject.options;
return compilerOptions;
}
function parseTsConfigFile(tree: Tree, tsConfigPath: string): ts.ParsedCommandLine {
const config = getJsonFile(tree, tsConfigPath);
const host: ts.ParseConfigHost = {
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
readDirectory: ts.sys.readDirectory,
fileExists: (file: string) => tree.exists(file),
readFile: (file: string) => getFileContents(tree, file),
};
const basePath = dirname(tsConfigPath);
const tsConfigObject = ts.parseJsonConfigFileContent(config, host, basePath);
return tsConfigObject;
}