/
ast-utils.ts
568 lines (514 loc) · 14.2 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
import * as ts from 'typescript';
import { findNodes } from '@nrwl/workspace/src/utilities/typescript/find-nodes';
import {
ChangeType,
logger,
StringChange,
StringInsertion,
} from '@nrwl/devkit';
export function addImport(
source: ts.SourceFile,
statement: string
): StringChange[] {
const allImports = findNodes(source, ts.SyntaxKind.ImportDeclaration);
if (allImports.length > 0) {
const lastImport = allImports[allImports.length - 1];
return [
{
type: ChangeType.Insert,
index: lastImport.end + 1,
text: `\n${statement}\n`,
},
];
} else {
return [
{
type: ChangeType.Insert,
index: 0,
text: `\n${statement}\n`,
},
];
}
}
export function findMainRenderStatement(
source: ts.SourceFile
): ts.CallExpression | null {
// 1. Try to find ReactDOM.render.
const calls = findNodes(
source,
ts.SyntaxKind.CallExpression
) as ts.CallExpression[];
for (const expr of calls) {
const inner = expr.expression;
// React 17 and below
if (
ts.isPropertyAccessExpression(inner) &&
/ReactDOM/i.test(inner.expression.getText()) &&
inner.name.getText() === 'render'
) {
return expr;
}
// React 18
if (
ts.isPropertyAccessExpression(inner) &&
/root/.test(inner.expression.getText()) &&
inner.name.getText() === 'render'
) {
return expr;
}
}
// 2. Try to find render from 'react-dom'.
const imports = findNodes(
source,
ts.SyntaxKind.ImportDeclaration
) as ts.ImportDeclaration[];
const hasRenderImport = imports.some(
(i) =>
i.moduleSpecifier.getText().includes('react-dom') &&
/\brender\b/.test(i.importClause.namedBindings.getText())
);
if (hasRenderImport) {
const calls = findNodes(
source,
ts.SyntaxKind.CallExpression
) as ts.CallExpression[];
for (const expr of calls) {
if (expr.expression.getText() === 'render') {
return expr;
}
}
}
return null;
}
export function findDefaultExport(source: ts.SourceFile): ts.Node | null {
return (
findDefaultExportDeclaration(source) || findDefaultClassOrFunction(source)
);
}
export function findDefaultExportDeclaration(
source: ts.SourceFile
): ts.Node | null {
const identifier = findDefaultExportIdentifier(source);
if (identifier) {
const variables = findNodes(source, ts.SyntaxKind.VariableDeclaration);
const fns = findNodes(source, ts.SyntaxKind.FunctionDeclaration);
const cls = findNodes(source, ts.SyntaxKind.ClassDeclaration);
const all = [...variables, ...fns, ...cls] as Array<
ts.VariableDeclaration | ts.FunctionDeclaration | ts.ClassDeclaration
>;
const exported = all
.filter((x) => x.name.kind === ts.SyntaxKind.Identifier)
.find((x) => (x.name as ts.Identifier).text === identifier.text);
return exported || null;
} else {
return null;
}
}
export function findDefaultExportIdentifier(
source: ts.SourceFile
): ts.Identifier | null {
const exports = findNodes(
source,
ts.SyntaxKind.ExportAssignment
) as ts.ExportAssignment[];
const identifier = exports
.map((x) => x.expression)
.find((x) => x.kind === ts.SyntaxKind.Identifier) as ts.Identifier;
return identifier || null;
}
export function findDefaultClassOrFunction(
source: ts.SourceFile
): ts.FunctionDeclaration | ts.ClassDeclaration | null {
const fns = findNodes(
source,
ts.SyntaxKind.FunctionDeclaration
) as ts.FunctionDeclaration[];
const cls = findNodes(
source,
ts.SyntaxKind.ClassDeclaration
) as ts.ClassDeclaration[];
return (
fns.find(hasDefaultExportModifier) ||
cls.find(hasDefaultExportModifier) ||
null
);
}
function hasDefaultExportModifier(
x: ts.ClassDeclaration | ts.FunctionDeclaration
) {
return (
x.modifiers &&
x.modifiers.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) &&
x.modifiers.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)
);
}
export function findComponentImportPath(
componentName: string,
source: ts.SourceFile
) {
const allImports = findNodes(
source,
ts.SyntaxKind.ImportDeclaration
) as ts.ImportDeclaration[];
const matching = allImports.filter((i: ts.ImportDeclaration) => {
return (
i.importClause &&
i.importClause.name &&
i.importClause.name.getText() === componentName
);
});
if (matching.length === 0) {
return null;
}
const appImport = matching[0];
return appImport.moduleSpecifier.getText().replace(/['"]/g, '');
}
export function findElements(source: ts.SourceFile, tagName: string) {
const nodes = findNodes(source, [
ts.SyntaxKind.JsxSelfClosingElement,
ts.SyntaxKind.JsxOpeningElement,
]);
return nodes.filter((node) => isTag(tagName, node));
}
export function findClosestOpening(tagName: string, node: ts.Node) {
if (!node) {
return null;
}
if (isTag(tagName, node)) {
return node;
} else {
return findClosestOpening(tagName, node.parent);
}
}
export function isTag(tagName: string, node: ts.Node) {
if (ts.isJsxOpeningLikeElement(node)) {
return (
node.tagName.kind === ts.SyntaxKind.Identifier &&
node.tagName.text === tagName
);
}
if (ts.isJsxElement(node) && node.openingElement) {
return (
node.openingElement.tagName.kind === ts.SyntaxKind.Identifier &&
node.openingElement.tagName.getText() === tagName
);
}
return false;
}
export function addInitialRoutes(
sourcePath: string,
source: ts.SourceFile
): StringChange[] {
const jsxClosingElements = findNodes(source, [
ts.SyntaxKind.JsxClosingElement,
ts.SyntaxKind.JsxClosingFragment,
]);
const outerMostJsxClosing = jsxClosingElements[jsxClosingElements.length - 1];
if (!outerMostJsxClosing) {
logger.warn(
`Could not find JSX elements in ${sourcePath}; Skipping insert routes`
);
return [];
}
const insertRoutes: StringInsertion = {
type: ChangeType.Insert,
index: outerMostJsxClosing.getStart(),
text: `
{/* START: routes */}
{/* These routes and navigation have been generated for you */}
{/* Feel free to move and update them to fit your needs */}
<br/>
<hr/>
<br/>
<div role="navigation">
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/page-2">Page 2</Link></li>
</ul>
</div>
<Route
path="/"
exact
render={() => (
<div>This is the generated root route. <Link to="/page-2">Click here for page 2.</Link></div>
)}
/>
<Route
path="/page-2"
exact
render={() => (
<div><Link to="/">Click here to go back to root page.</Link></div>
)}
/>
{/* END: routes */}
`,
};
return [
...addImport(source, `import { Route, Link } from 'react-router-dom';`),
insertRoutes,
];
}
export function addRoute(
sourcePath: string,
source: ts.SourceFile,
options: {
routePath: string;
componentName: string;
moduleName: string;
}
): StringChange[] {
const routes = findElements(source, 'Route');
const links = findElements(source, 'Link');
if (routes.length === 0) {
logger.warn(
`Could not find <Route/> components in ${sourcePath}; Skipping add route`
);
return [];
} else {
const changes: StringChange[] = [];
const firstRoute = routes[0];
const firstLink = links[0];
changes.push(
...addImport(
source,
`import { ${options.componentName} } from '${options.moduleName}';`
)
);
changes.push({
type: ChangeType.Insert,
index: firstRoute.getEnd(),
text: `<Route path="${options.routePath}" component={${options.componentName}} />`,
});
if (firstLink) {
const parentLi = findClosestOpening('li', firstLink);
if (parentLi) {
changes.push({
type: ChangeType.Insert,
index: parentLi.getEnd(),
text: `<li><Link to="${options.routePath}">${options.componentName}</Link></li>`,
});
} else {
changes.push({
type: ChangeType.Insert,
index: firstLink.parent.getEnd(),
text: `<Link to="${options.routePath}">${options.componentName}</Link>`,
});
}
}
return changes;
}
}
export function addBrowserRouter(
sourcePath: string,
source: ts.SourceFile
): StringChange[] {
const app = findElements(source, 'App')[0];
if (app) {
return [
...addImport(source, `import { BrowserRouter } from 'react-router-dom';`),
{
type: ChangeType.Insert,
index: app.getStart(),
text: `<BrowserRouter>`,
},
{
type: ChangeType.Insert,
index: app.getEnd(),
text: `</BrowserRouter>`,
},
];
} else {
logger.warn(
`Could not find App component in ${sourcePath}; Skipping add <BrowserRouter>`
);
return [];
}
}
export function addReduxStoreToMain(
sourcePath: string,
source: ts.SourceFile
): StringChange[] {
const renderStmt = findMainRenderStatement(source);
if (!renderStmt) {
logger.warn(`Could not find render(...) in ${sourcePath}`);
return [];
}
const jsx = renderStmt.arguments[0];
return [
...addImport(
source,
`import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';`
),
{
type: ChangeType.Insert,
index: renderStmt.getStart(),
text: `
const store = configureStore({
reducer: {},
// Additional middleware can be passed to this array
middleware: getDefaultMiddleware => getDefaultMiddleware(),
devTools: process.env.NODE_ENV !== 'production',
// Optional Redux store enhancers
enhancers: [],
});
`,
},
{
type: ChangeType.Insert,
index: jsx.getStart(),
text: `<Provider store={store}>`,
},
{
type: ChangeType.Insert,
index: jsx.getEnd(),
text: `</Provider>`,
},
];
}
export function updateReduxStore(
sourcePath: string,
source: ts.SourceFile,
feature: {
keyName: string;
reducerName: string;
modulePath: string;
}
): StringChange[] {
const calls = findNodes(
source,
ts.SyntaxKind.CallExpression
) as ts.CallExpression[];
let reducerDescriptor: ts.ObjectLiteralExpression;
// Look for configureStore call
for (const expr of calls) {
if (!expr.expression.getText().includes('configureStore')) {
continue;
}
const arg = expr.arguments[0];
if (ts.isObjectLiteralExpression(arg)) {
let found: ts.ObjectLiteralExpression;
for (const prop of arg.properties) {
if (
ts.isPropertyAssignment(prop) &&
prop.name.getText() === 'reducer' &&
ts.isObjectLiteralExpression(prop.initializer)
) {
found = prop.initializer;
break;
}
}
if (found) {
reducerDescriptor = found;
break;
}
}
}
// Look for combineReducer call
if (!reducerDescriptor) {
for (const expr of calls) {
if (!expr.expression.getText().includes('combineReducer')) {
continue;
}
const arg = expr.arguments[0];
if (ts.isObjectLiteralExpression(arg)) {
reducerDescriptor = arg;
break;
}
}
}
if (!reducerDescriptor) {
logger.warn(
`Could not find configureStore/combineReducer call in ${sourcePath}`
);
return [];
}
return [
...addImport(
source,
`import { ${feature.keyName}, ${feature.reducerName} } from '${feature.modulePath}';`
),
{
type: ChangeType.Insert,
index: reducerDescriptor.getStart() + 1,
text: `[${feature.keyName}]: ${feature.reducerName}${
reducerDescriptor.properties.length > 0 ? ',' : ''
}`,
},
];
}
export function getComponentName(sourceFile: ts.SourceFile): ts.Node | null {
const defaultExport = findDefaultExport(sourceFile);
if (
!(
defaultExport &&
(findNodes(defaultExport, ts.SyntaxKind.JsxElement).length > 0 ||
findNodes(defaultExport, ts.SyntaxKind.JsxSelfClosingElement).length >
0)
)
) {
return null;
}
return defaultExport;
}
export function getComponentPropsInterface(
sourceFile: ts.SourceFile
): ts.InterfaceDeclaration | null {
const cmpDeclaration = getComponentName(sourceFile);
let propsTypeName: string = null;
if (ts.isFunctionDeclaration(cmpDeclaration)) {
const propsParam: ts.ParameterDeclaration = cmpDeclaration.parameters.find(
(x) => ts.isParameter(x) && (x.name as ts.Identifier).text === 'props'
);
if (propsParam && propsParam.type) {
propsTypeName = (
(propsParam.type as ts.TypeReferenceNode).typeName as ts.Identifier
).text;
}
} else if (
(cmpDeclaration as ts.VariableDeclaration).initializer &&
ts.isArrowFunction((cmpDeclaration as ts.VariableDeclaration).initializer)
) {
const arrowFn = (cmpDeclaration as ts.VariableDeclaration)
.initializer as ts.ArrowFunction;
const propsParam: ts.ParameterDeclaration = arrowFn.parameters.find(
(x) => ts.isParameter(x) && (x.name as ts.Identifier).text === 'props'
);
if (propsParam && propsParam.type) {
propsTypeName = (
(propsParam.type as ts.TypeReferenceNode).typeName as ts.Identifier
).text;
}
} else if (
// do we have a class component extending from React.Component
ts.isClassDeclaration(cmpDeclaration) &&
cmpDeclaration.heritageClauses &&
cmpDeclaration.heritageClauses.length > 0
) {
const heritageClause = cmpDeclaration.heritageClauses[0];
if (heritageClause) {
const propsTypeExpression = heritageClause.types.find((x) => {
const name =
(x.expression as ts.Identifier).escapedText ||
(x.expression as ts.PropertyAccessExpression).name.text;
return name === 'Component' || name === 'PureComponent';
});
if (propsTypeExpression && propsTypeExpression.typeArguments) {
propsTypeName = (
propsTypeExpression.typeArguments[0] as ts.TypeReferenceNode
).typeName.getText();
}
}
} else {
return null;
}
if (propsTypeName) {
return findNodes(sourceFile, ts.SyntaxKind.InterfaceDeclaration).find(
(x: ts.InterfaceDeclaration) => {
return (x.name as ts.Identifier).getText() === propsTypeName;
}
) as ts.InterfaceDeclaration;
} else {
return null;
}
}