-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.js
852 lines (798 loc) · 27.8 KB
/
transform.js
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
const generate = require('@babel/generator').default;
const parser = require('@babel/parser');
const template = require('@babel/template').default;
const traverse = require('@babel/traverse').default;
const types = require('@babel/types');
const staticBlockPlugin = require('@babel/plugin-transform-class-static-block').default;
const { sha256 } = require('./utils.js');
// TODO: const hoistVariables = require('@babel/helper-hoist-variables').default;
// Parse JS code into a babel ast.
const parse = (code) => parser.parse(code, { sourceType: 'module' });
// ## AST transformation visitors
const copyLocation = (fromNode, toNode) => {
toNode.start = fromNode.start;
toNode.end = fromNode.end;
toNode.loc = fromNode.loc;
};
const getEnclosingFunction = path => path.findParent((path) => path.isFunction());
const getEnclosingVariableDeclarator = path => path.findParent((path) => path.isVariableDeclarator());
const findNestedIdentifierValues = (node) => {
const identifierValuesFound = [];
if (types.isObjectPattern(node)) {
for (const property of node.properties) {
if (types.isIdentifier(property.value)) {
identifierValuesFound.push(property.value.name);
} else {
const moreValuesFound = findNestedIdentifierValues(property.value);
identifierValuesFound.push(...moreValuesFound);
}
}
} else if (types.isArrayPattern(node)) {
for (const element of node.elements) {
if (types.isIdentifier(element)) {
identifierValuesFound.push(element.name);
} else {
const moreValuesFound = findNestedIdentifierValues(element);
identifierValuesFound.push(...moreValuesFound);
}
}
} else if (types.isIdentifier(node)) {
identifierValuesFound.push(node.name);
}
return identifierValuesFound;
};
const handleAwaitExpression = (path) => {
if (getEnclosingFunction(path)) {
return;
}
const topPath = path.find((path) => path.parentPath.isProgram());
topPath.node._topLevelAwait = true;
const declarator = getEnclosingVariableDeclarator(path);
if (declarator) {
if (!types.isProgram(declarator.parentPath.parentPath)) {
return;
}
const identifierNames = findNestedIdentifierValues(declarator.node.id);
const syncDeclarator = template.ast(`var ${identifierNames.join(', ')};`);
copyLocation(declarator.node, syncDeclarator);
// TODO: Make more precise by pointing to individual identifiers:
for (const declaration of syncDeclarator.declarations) {
copyLocation(declarator.node, declaration);
copyLocation(declarator.node, declaration.id);
}
const asyncAssignment = {
type: 'ExpressionStatement',
expression: {
type: 'AssignmentExpression',
operator: '=',
left: declarator.node.id,
right: declarator.node.init
}
};
copyLocation(declarator.node, asyncAssignment);
const outputs = [
syncDeclarator,
asyncAssignment
];
declarator.parentPath.replaceWithMultiple(outputs);
}
};
const handleForOfStatement = (path) => {
if (getEnclosingFunction(path)) {
return;
}
if (path.node.await) {
const topPath = path.find((path) => path.parentPath.isProgram());
topPath.node._topLevelForOfAwait = true;
}
};
const awaitVisitor = {
AwaitExpression (path) {
handleAwaitExpression(path);
},
ForOfStatement (path) {
handleForOfStatement(path);
}
};
const handleVariableDeclarationEnter = (path) => {
if (!types.isProgram(path.parentPath)) {
return;
}
if (path.node.kind !== 'var' || path.node.declarations.length > 1) {
const outputNodes = path.node.declarations.map(
d => types.variableDeclaration('var', [d]));
for (let i = 0; i < path.node.declarations.length; ++i) {
copyLocation(path.node.declarations[i], outputNodes[i]);
}
path.replaceWithMultiple(outputNodes);
}
};
const handleVariableDeclarationExit = (path) => {
if (!types.isProgram(path.parentPath)) {
return;
}
const identifierValues = [];
for (const declarator of path.node.declarations) {
identifierValues.push(...findNestedIdentifierValues(declarator.id));
}
path.node._definedVars = identifierValues;
path.node._removeCode = identifierValues
.map(identifier => `${identifier} = undefined;`)
.join('\n');
};
const handleCallExpressionWithRequireOrImport = (path) => {
if (path.node.callee && types.isImport(path.node.callee)) {
path.node.callee.type = 'Identifier';
path.node.callee.name = '__import';
}
if (getEnclosingFunction(path)) {
return;
}
const topPath = path.find((path) => path.parentPath.isProgram());
if (path.node.callee && path.node.arguments[0]) {
const firstArgument = path.node.arguments[0].value;
if (path.node.callee.name === '__import') {
topPath.node._topLevelImport = firstArgument;
}
if (path.node.callee.name === 'require') {
topPath.node._topLevelRequire = firstArgument;
}
}
};
const varVisitor = {
VariableDeclaration: {
enter (path) {
handleVariableDeclarationEnter(path);
},
exit (path) {
handleVariableDeclarationExit(path);
}
},
CallExpression: {
exit (path) {
handleCallExpressionWithRequireOrImport(path);
}
}
};
const handleImportDotMeta = (path) => {
if (path.node.meta.name === 'import') {
const originalPathNode = path.node;
path.replaceWith(template.ast('__import.meta'));
copyLocation(originalPathNode, path.node);
copyLocation(originalPathNode.meta, path.node.object);
copyLocation(originalPathNode.property, path.node.property);
}
};
const handleImportDeclaration = (path) => {
const source = path.node.source.value;
const specifiers = [];
let namespaceId;
for (const specifier of path.node.specifiers) {
if (specifier.type === 'ImportDefaultSpecifier') {
specifiers.push(`default: ${specifier.local.name}`);
} else if (specifier.type === 'ImportSpecifier') {
if (specifier.imported.type === 'Identifier' &&
specifier.imported.name !== specifier.local.name) {
specifiers.push(
`${specifier.imported.name}: ${specifier.local.name}`);
} else if (specifier.imported.type === 'StringLiteral' &&
specifier.imported.value !== specifier.local.name) {
specifiers.push(
`'${specifier.imported.value}': ${specifier.local.name}`);
} else {
specifiers.push(specifier.local.name);
}
} else if (specifier.type === 'ImportNamespaceSpecifier') {
namespaceId = specifier.local.name;
}
}
const sourceString = `await __import('${source}')`;
let line = '';
if (namespaceId !== undefined) {
line += `const ${namespaceId} = ${sourceString};`;
}
if (specifiers.length > 0) {
line += `const {${specifiers.join(', ')}} = ${namespaceId ?? sourceString};`;
}
if (namespaceId === undefined && specifiers.length === 0) {
line = sourceString;
}
const newAst = template.ast(line);
if (namespaceId && specifiers.length > 0) {
copyLocation(path.node, newAst[0]);
path.replaceWithMultiple(newAst);
} else {
copyLocation(path.node, newAst);
if (newAst.declarations) {
for (let i = 0; i < newAst.declarations.length; ++i) {
copyLocation(path.node.specifiers[i], newAst.declarations[i]);
}
}
path.replaceWith(newAst);
}
};
const importVisitor = {
MetaProperty (path) {
handleImportDotMeta(path);
},
ImportDeclaration (path) {
handleImportDeclaration(path);
}
};
const getEnclosingClass = path => path.findParent((path) => path.isClassDeclaration());
const getEnclosingSuperClassName = path => getEnclosingClass(path).node.superClass.name;
const getEnclosingMethod = path => path.findParent((path) => path.isMethod());
const getEnclosingProperty = path => path.findParent((path) => path.isProperty());
const isTopLevelDeclaredObject = (path) =>
types.isVariableDeclarator(path.parentPath) &&
types.isVariableDeclaration(path.parentPath.parentPath) &&
types.isProgram(path.parentPath.parentPath.parentPath);
const handleCallExpressionEnter = (path) => {
if (path.node.callee.type !== 'MemberExpression' ||
path.node.callee.object.type !== 'Super') {
return;
}
const methodPath = getEnclosingMethod(path);
if (!methodPath || methodPath.kind === 'constructor') {
return;
}
// if (TODO: !isTopLevelDeclaredObject(getEnclosingClass(path))) {
// return;
// }
const methodName = path.node.callee.property.name;
const isStatic = methodPath.node.static;
const superClassName = getEnclosingSuperClassName(path);
const ast = template.ast(`${superClassName}${isStatic ? '' : '.prototype'}.${methodName}.call(${isStatic ? '' : 'this'})`);
copyLocation(path.node, ast);
const expressionAST = ast.expression;
expressionAST.arguments = expressionAST.arguments.concat(path.node.arguments);
path.replaceWith(expressionAST);
};
const handleMemberExpression = (path) => {
const object = path.node.object;
if (object.type !== 'Super') { // ||
// TODO: !isTopLevelDeclaredObject(getEnclosingClass(path))) {
return;
}
const enclosure = getEnclosingProperty(path) ?? getEnclosingMethod(path);
const superClassName = getEnclosingSuperClassName(path);
if (enclosure.node.static) {
object.type = 'Identifier';
object.name = superClassName;
} else {
path.replaceWith(template.ast('undefined'));
// throw new Error('super found in the wrong place!');
}
};
// Convert private methods and fields to public methods
// and fields with a `_PRIVATE_` prefix.
const handlePrivateProperty = (path, propertyType) => {
path.node.type = propertyType;
path.node.key.type = 'Identifier';
path.node.key.name = '_PRIVATE_' + path.node.key.id.name;
path.node.key.id = undefined;
};
const nodesForClass = ({ className, classBodyNodes }) => {
const outputNodes = []; const retainedNodes = [];
for (const classBodyNode of classBodyNodes) {
let templateAST;
// Convert methods and fields declarations to separable
// assignment statements.
if (classBodyNode.type === 'ClassMethod') {
if (classBodyNode.kind === 'constructor') {
retainedNodes.push(classBodyNode);
} else if (classBodyNode.kind === 'method') {
templateAST = template.ast(
`${className}.${classBodyNode.static ? '' : 'prototype.'}${classBodyNode.key.name} = ${classBodyNode.async ? 'async ' : ''}function${classBodyNode.generator ? '*' : ''} () {}`
);
copyLocation(classBodyNode, templateAST);
const fun = templateAST.expression.right;
fun.body = classBodyNode.body;
fun.params = classBodyNode.params;
templateAST._removeCode = `if (${className}) { delete ${className}.${classBodyNode.static ? '' : 'prototype.'}${classBodyNode.key.name} };`;
} else if (classBodyNode.kind === 'get' ||
classBodyNode.kind === 'set') {
const keyName = classBodyNode.key.name;
templateAST = template.ast(
`Object.defineProperty(${className}.prototype, "${keyName}", {
${classBodyNode.kind}: function () { },
configurable: true
});`
);
copyLocation(classBodyNode, templateAST);
const fun = templateAST.expression.arguments[2].properties[0].value;
fun.body = classBodyNode.body;
fun.params = classBodyNode.params;
const getter = classBodyNode.kind === 'get';
templateAST._removeCode = `if (${className}) Object.defineProperty(${className}.prototype, "${keyName}", {
${classBodyNode.kind}: function (${getter ? '' : 'value'}) {
return this._PROPERTY_${keyName} ${getter ? '' : '= value'};
},
configurable: true
});`;
} else {
throw new Error(`Unexpected ClassMethod kind ${classBodyNode.kind}`);
}
} else if (classBodyNode.type === 'ClassProperty') {
templateAST = template.ast(
`${className}.${classBodyNode.static ? '' : 'prototype.'}${classBodyNode.key.name} = undefined;`
);
copyLocation(classBodyNode, templateAST);
if (classBodyNode.value !== null) {
templateAST.expression.right = classBodyNode.value;
}
templateAST._removeCode = `if (${className}) { delete ${className}.${classBodyNode.static ? '' : 'prototype.'}${classBodyNode.key.name} }`;
} else {
throw new Error(`Unexpected ClassBody node type ${classBodyNode.type}`);
}
if (templateAST !== undefined) {
outputNodes.push(templateAST);
}
}
outputNodes.forEach(function (outputNode) {
outputNode._parentLabel = className;
});
return { retainedNodes, outputNodes };
};
const handleClassExpression = (path) => {
// Only do top-level class variable declarations.
if (!isTopLevelDeclaredObject(path)) {
return;
}
const classNode = path.node;
let className, classBodyNodes;
if (types.isVariableDeclarator(path.parentPath)) {
className = path.parentPath.node.id.name;
}
if (types.isClassBody(classNode.body)) {
classBodyNodes = classNode.body.body;
}
const { retainedNodes, outputNodes } = nodesForClass(
{ classNode, className, classBodyNodes });
classNode.body.body = retainedNodes;
path.parentPath.parentPath.node._segmentLabel = className;
for (const outputNode of outputNodes) {
path.parentPath.parentPath.insertAfter(outputNode);
}
};
const handleClassDeclaration = (path) => {
// Only modify top-level class declarations.
if (!types.isProgram(path.parentPath)) {
return;
}
// Convert a class declaration into a class expression bound to a var.
const classNode = path.node;
const expression = template.ast('var AClass = class AClass { }');
const declaration = expression.declarations[0];
declaration.id.name = classNode.id.name;
declaration.init.id.name = classNode.id.name;
declaration.init.body = classNode.body;
declaration.init.superClass = classNode.superClass;
copyLocation(classNode, expression);
copyLocation(classNode, declaration.init);
copyLocation(classNode.id, declaration.id);
path.replaceWith(expression);
};
const handlePrivateName = (path) => {
path.replaceWith(path.node.id);
path.node.name = '_PRIVATE_' + path.node.name;
};
// Make class declarations mutable by transforming to class
// expressions assigned to a var, with member declarations
// hoisted out of the class body.
const classVisitor = {
PrivateName: {
enter (path) {
handlePrivateName(path);
}
},
ClassPrivateMethod (path) {
handlePrivateProperty(path, 'ClassMethod');
},
ClassPrivateProperty (path) {
handlePrivateProperty(path, 'ClassProperty');
},
ClassExpression: {
exit (path) {
handleClassExpression(path);
}
},
ClassDeclaration: {
enter (path) {
handleClassDeclaration(path);
}
}
};
const handleFunctionDeclaration = (path) => {
if (!types.isProgram(path.parentPath)) {
return;
}
const functionNode = path.node;
const expression = template.ast('var aFunction = function aFunction () {}');
const declaration = expression.declarations[0];
declaration.id.name = functionNode.id.name;
declaration.init.id.name = functionNode.id.name;
declaration.init.body = functionNode.body;
declaration.init.async = functionNode.async;
declaration.init.generator = functionNode.generator;
declaration.init.params = functionNode.params;
copyLocation(functionNode, expression);
copyLocation(functionNode, declaration);
copyLocation(functionNode.id, declaration.id);
copyLocation(functionNode, declaration.init);
path.replaceWith(expression);
};
const handleFunctionExpression = (path) => {
const grandparentPath = path.parentPath.parentPath;
if (!types.isVariableDeclaration(grandparentPath) ||
!types.isProgram(grandparentPath.parentPath)) {
return;
}
const name = path.parentPath.node.id.name;
if (grandparentPath.node._dontWrap) {
return;
}
const implName = name + '_hakk_';
path.parentPath.node.id.name = implName;
const wrapperAST = template.ast(
`var ${name} = (...args) => ${implName}(...args);`);
wrapperAST._dontWrap = true;
copyLocation(path.parentPath.node, wrapperAST.declarations[0]);
grandparentPath.insertAfter(wrapperAST);
};
const functionVisitor = {
FunctionDeclaration: {
enter (path) {
handleFunctionDeclaration(path);
}
},
FunctionExpression: {
enter (path) {
handleFunctionExpression(path);
}
},
ArrowFunctionExpression: {
enter (path) {
handleFunctionExpression(path);
}
}
};
const superVisitor = {
CallExpression: {
enter (path) {
handleCallExpressionEnter(path);
}
},
MemberExpression (path) {
handleMemberExpression(path);
}
};
const staticBlockVisitor = staticBlockPlugin({
types, template, assertVersion: () => undefined, version: [8]
}).visitor;
const handleObjectExpression = (path) => {
if (!isTopLevelDeclaredObject(path)) {
return;
}
const originalProperties = path.node.properties;
const name = path.parentPath.node.id.name;
const outputASTs = [];
let identifierNames = [];
if (name !== undefined) {
path.node.properties = [];
} else {
identifierNames = findNestedIdentifierValues(path.parentPath.node.id);
const declarator = template.ast(`var ${identifierNames.join(', ')};`);
path.parentPath.node.init = undefined;
path.parentPath.parentPath.replaceWith(declarator);
}
for (const property of originalProperties) {
const key = property.key;
let ast;
if (types.isObjectProperty(property)) {
if (types.isIdentifier(key)) {
if (name === undefined) {
if (identifierNames.includes(key.name)) {
ast = template.ast(`${key.name} = undefined;`);
}
} else {
ast = template.ast(`${name}.${key.name} = undefined;`);
}
if (ast) {
copyLocation(property, ast);
}
}
if (types.isStringLiteral(key)) {
if (name === undefined) {
if (identifierNames.includes(key.value)) {
ast = template.ast(`${key.value} = undefined;`);
}
} else {
ast = template.ast(`${name}['${key.value}'] = undefined;`);
}
if (ast) {
copyLocation(property, ast);
}
}
if (ast) {
ast.expression.right = property.value;
copyLocation(property, ast.expression);
copyLocation(property.key, ast.expression.left);
}
} else if (types.isObjectMethod(property)) {
if (types.isIdentifier(key)) {
if (name === undefined) {
if (identifierNames.includes(key.name)) {
ast = template.ast(`${key.name} = function () { };`);
}
} else {
ast = template.ast(`${name}.${key.name} = function () { };`);
}
if (ast) {
copyLocation(property, ast);
const expressionRight = ast.expression.right;
expressionRight.params = property.params;
expressionRight.async = property.async;
expressionRight.generator = property.generator;
expressionRight.body = property.body;
copyLocation(property.body, ast.expression);
copyLocation(property.key, ast.expression.left);
}
} else {
throw new Error(`Unexpected key type '${key.type}'.`);
}
} else {
throw new Error(`Unexpected object member '${property.type}'.`);
}
if (ast) {
ast._removeCode = `delete ${name}['${key.name}']`;
outputASTs.push(ast);
}
}
for (const outputAST of outputASTs.reverse()) {
path.parentPath.parentPath.insertAfter(outputAST);
}
};
const objectVisitor = {
ObjectExpression (path) {
handleObjectExpression(path);
}
};
const astCodeToAddToModuleExports = (identifier, localName) =>
types.isStringLiteral(identifier)
? template.ast(`module.exports['${identifier.value}'] = ${localName}`)
: template.ast(`module.exports.${identifier.name} = ${localName}`);
const wildcardExport = (namespaceIdentifier) => {
const namespaceAccessorString = namespaceIdentifier
? (types.isStringLiteral(namespaceIdentifier)
? `['${namespaceIdentifier.value}']`
: `.${namespaceIdentifier.name}`)
: '';
return template.ast(
`const propertyNames = Object.getOwnPropertyNames(importedObject);
for (const propertyName of propertyNames) {
if (propertyName !== 'default') {
module.exports${namespaceAccessorString}[propertyName] = importedObject[propertyName];
}
}`);
};
const wrapImportedObject = (moduleName, asts) => {
const resultAST = template.ast(
`await (async function () {
const importedObject = await __import('${moduleName}');
})();`);
resultAST.expression.argument.callee.body.body.push(...asts);
return resultAST;
};
const handleExportNameDeclaration = (path) => {
const outputASTs = [];
const specifiers = path.node.specifiers;
const declaration = path.node.declaration;
if (specifiers && specifiers.length > 0 && (declaration === null || declaration === undefined)) {
const specifierASTs = [];
const source = path.node.source;
for (const specifier of specifiers) {
if (types.isExportSpecifier(specifier)) {
const localName = `${source ? 'importedObject.' : ''}${specifier.local.name}`;
const resultsAST = astCodeToAddToModuleExports(specifier.exported, localName);
copyLocation(specifier, resultsAST);
specifierASTs.push(resultsAST);
} else if (types.isExportNamespaceSpecifier(specifier)) {
specifierASTs.push(...wildcardExport(specifier.exported));
copyLocation(specifier, specifiers);
}
}
if (source) {
const moduleName = path.node.source.value;
const resultAST = wrapImportedObject(moduleName, specifierASTs);
outputASTs.push(resultAST);
} else {
outputASTs.push(...specifierASTs);
}
} else if (specifiers.length === 0 && declaration !== null) {
outputASTs.push(declaration);
if (types.isVariableDeclaration(declaration)) {
for (const declarator of declaration.declarations) {
if (types.isObjectPattern(declarator.id)) {
const objectName = declarator.init.name;
for (const property of declarator.id.properties) {
const resultsAST = astCodeToAddToModuleExports(property.value, `${objectName}.${property.key.name}`);
copyLocation(property, resultsAST);
outputASTs.push(resultsAST);
}
} else if (types.isArrayPattern(declarator.id)) {
let i = 0;
const arrayName = declarator.init.name;
for (const element of declarator.id.elements) {
const resultsAST = astCodeToAddToModuleExports(element, `${arrayName}[${i}]`);
copyLocation(element, resultsAST);
outputASTs.push(resultsAST);
++i;
}
} else if (types.isIdentifier(declarator.id)) {
const resultsAST = astCodeToAddToModuleExports(declarator.id, declarator.id.name);
copyLocation(declarator, resultsAST);
outputASTs.push(resultsAST);
}
}
}
if (types.isFunctionDeclaration(declaration) ||
types.isClassDeclaration(declaration)) {
const identifier = declaration.id;
const resultsAST = astCodeToAddToModuleExports(identifier, identifier.name);
copyLocation(declaration, resultsAST);
outputASTs.push(resultsAST);
}
}
if (outputASTs.length > 0) {
copyLocation(path.node, outputASTs[0]);
}
path.replaceWithMultiple(outputASTs);
};
const handleExportDefaultDeclaration = (path) => {
const outputAST = template.ast('module.exports.default = undefined');
outputAST.expression.right = path.node.declaration;
copyLocation(path.node, outputAST);
path.replaceWith(outputAST);
};
const handleExportAllDeclaration = (path) => {
const moduleName = path.node.source.value;
const lines = wildcardExport(null);
path.replaceWith(wrapImportedObject(moduleName, lines));
};
const exportVisitor = {
ExportNamedDeclaration: {
exit (path) {
handleExportNameDeclaration(path);
}
},
ExportDefaultDeclaration: {
exit (path) {
handleExportDefaultDeclaration(path);
}
},
ExportAllDeclaration: {
exit (path) {
handleExportAllDeclaration(path);
}
}
};
const transform = (ast, visitors) => {
for (const visitor of visitors) {
traverse(ast, visitor);
}
return ast;
};
const functionDeclarationsFirst = (nodes) => {
const head = [];
const tail = [];
for (const node of nodes) {
if (types.isFunctionDeclaration(node)) {
head.push(node);
} else {
tail.push(node);
}
}
return [...head, ...tail];
};
const prepareAST = (code) => {
if (code.trim().length === 0) {
return '';
}
const ast = parse(code);
ast.program.body = functionDeclarationsFirst(ast.program.body);
return transform(ast,
[importVisitor, exportVisitor, superVisitor, staticBlockVisitor,
objectVisitor, classVisitor,
awaitVisitor, functionVisitor, varVisitor]);
};
const prepareCode = (code) => {
if (code.length === 0) {
return '';
} else {
return generate(prepareAST(code)).code;
}
};
const prepareAstNodes = (code) => {
if (code.length === 0) {
return [];
} else {
const program = prepareAST(code).program;
return program ? program.body : [];
}
};
const findCodeToRemove = (previousNodes, addedOrChangedVarsSeen) => {
// Removal code for previousNodes that haven't been found in new version.
const toRemove = [];
for (const node of previousNodes.values()) {
if (node._removeCode) {
const deletedVars = node._definedVars ? node._definedVars.filter(v => !addedOrChangedVarsSeen.includes(v)) : undefined;
// Remove in reverse order:
toRemove.unshift({ code: node._removeCode, isAsync: false, deletedVars });
}
}
return toRemove;
};
const findVarsToDeclare = (addedOrChangedVarsSeen) => {
// Any defined variables should be declared at the top because sometimes
// vars are referenced forward.
const toDeclare = [];
if (addedOrChangedVarsSeen.length > 0) {
const declareFirstFragment = {
code: `var ${addedOrChangedVarsSeen.join(', ')};`,
isAsync: false
};
toDeclare.unshift(declareFirstFragment);
}
return toDeclare;
};
const getCodeAndOriginalOffset = (node, filePath) => {
const { code: codeRaw, rawMappings } = generate(node, {
comments: true, retainLines: true, sourceMaps: true, sourceFileName: filePath
}, '');
const code = codeRaw.trim();
let originalOffset;
try {
originalOffset = rawMappings[0].original.line;
} catch (e) {
console.log('Failed to compute offset: ', code, node);
originalOffset = 0;
}
return { code, originalOffset };
};
const changedNodesToCodeFragments = (previousNodes, nodes, filePath) => {
const currentNodes = new Map();
const updatedParentLabels = new Set();
const toWrite = [];
const addedOrChangedVarsSeen = [];
const offsetsMap = {};
for (const node of nodes) {
const { code, originalOffset } = getCodeAndOriginalOffset(node, filePath);
const codeNormalized = code.replace(/\s+/g, ' ');
const codeHash = sha256(filePath + '\n' + code).substring(0, 16);
const tracker = filePath + '|' + codeHash;
offsetsMap[codeHash] = originalOffset;
currentNodes.set(codeNormalized, node);
if (previousNodes.has(codeNormalized) &&
!(node._parentLabel &&
updatedParentLabels.has(node._parentLabel))) {
previousNodes.delete(codeNormalized);
} else {
if (node._segmentLabel) {
updatedParentLabels.add(node._segmentLabel);
}
toWrite.push({
code,
isAsync: node._topLevelAwait || node._topLevelForOfAwait,
addedOrChangedVars: node._definedVars,
tracker
});
addedOrChangedVarsSeen.push(...(node._definedVars ?? []));
}
}
const toRemove = findCodeToRemove(previousNodes, addedOrChangedVarsSeen);
const toDeclare = findVarsToDeclare(addedOrChangedVarsSeen);
const fragments = [...toDeclare, ...toRemove, ...toWrite];
return { fragments, latestNodes: currentNodes, offsetsMap };
};
module.exports = { generate, parse, prepareAstNodes, prepareCode, prepareAST, changedNodesToCodeFragments };