babel-plugin-transform-modules-commonjs-ec.js
23.3 KB
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
/**
* Both used by zrender and echarts.
*/
const assert = require('assert');
const nodePath = require('path');
const basename = nodePath.basename;
const extname = nodePath.extname;
const babelTypes = require('@babel/types');
const babelTemplate = require('@babel/template');
const helperModuleTransforms = require('@babel/helper-module-transforms');
const isModule = helperModuleTransforms.isModule;
const isSideEffectImport = helperModuleTransforms.isSideEffectImport;
const ensureStatementsHoisted = helperModuleTransforms.ensureStatementsHoisted;
module.exports = function ({types, template}, options) {
return {
visitor: {
Program: {
exit(path) {
// For now this requires unambiguous rather that just sourceType
// because Babel currently parses all files as sourceType:module.
if (!isModule(path, true /* requireUnambiguous */)) {
return;
}
// Rename the bindings auto-injected into the scope so there is no
// risk of conflict between the bindings.
path.scope.rename('exports');
path.scope.rename('module');
path.scope.rename('require');
path.scope.rename('__filename');
path.scope.rename('__dirname');
const meta = rewriteModuleStatementsAndPrepare(path);
let headers = [];
let tails = [];
const checkExport = createExportChecker();
for (const [source, metadata] of meta.source) {
headers.push(...buildRequireStatements(types, source, metadata));
headers.push(...buildNamespaceInitStatements(meta, metadata, checkExport));
}
tails.push(...buildLocalExportStatements(meta, checkExport));
ensureStatementsHoisted(headers);
// FIXME ensure tail?
path.unshiftContainer('body', headers);
path.pushContainer('body', tails);
checkAssignOrUpdateExport(path, meta);
}
}
}
};
};
/**
* Remove all imports and exports from the file, and return all metadata
* needed to reconstruct the module's behavior.
* @return {ModuleMetadata}
*/
function normalizeModuleAndLoadMetadata(programPath) {
nameAnonymousExports(programPath);
const {local, source} = getModuleMetadata(programPath);
removeModuleDeclarations(programPath);
// Reuse the imported namespace name if there is one.
for (const [, metadata] of source) {
if (metadata.importsNamespace.size > 0) {
// This is kind of gross. If we stop using `loose: true` we should
// just make this destructuring assignment.
metadata.name = metadata.importsNamespace.values().next().value;
}
}
return {
exportName: 'exports',
exportNameListName: null,
local,
source
};
}
/**
* Get metadata about the imports and exports present in this module.
*/
function getModuleMetadata(programPath) {
const localData = getLocalExportMetadata(programPath);
const sourceData = new Map();
const getData = sourceNode => {
const source = sourceNode.value;
let data = sourceData.get(source);
if (!data) {
data = {
name: programPath.scope.generateUidIdentifier(
basename(source, extname(source))
).name,
interop: 'none',
loc: null,
// Data about the requested sources and names.
imports: new Map(),
// importsNamespace: import * as util from './a/b/util';
importsNamespace: new Set(),
// Metadata about data that is passed directly from source to export.
reexports: new Map(),
reexportNamespace: new Set(),
reexportAll: null,
};
sourceData.set(source, data);
}
return data;
};
programPath.get('body').forEach(child => {
if (child.isImportDeclaration()) {
const data = getData(child.node.source);
if (!data.loc) {
data.loc = child.node.loc;
}
child.get('specifiers').forEach(spec => {
if (spec.isImportDefaultSpecifier()) {
const localName = spec.get('local').node.name;
data.imports.set(localName, 'default');
const reexport = localData.get(localName);
if (reexport) {
localData.delete(localName);
reexport.names.forEach(name => {
data.reexports.set(name, 'default');
});
}
}
else if (spec.isImportNamespaceSpecifier()) {
const localName = spec.get('local').node.name;
assert(
data.importsNamespace.size === 0,
`Duplicate import namespace: ${localName}`
);
data.importsNamespace.add(localName);
const reexport = localData.get(localName);
if (reexport) {
localData.delete(localName);
reexport.names.forEach(name => {
data.reexportNamespace.add(name);
});
}
}
else if (spec.isImportSpecifier()) {
const importName = spec.get('imported').node.name;
const localName = spec.get('local').node.name;
data.imports.set(localName, importName);
const reexport = localData.get(localName);
if (reexport) {
localData.delete(localName);
reexport.names.forEach(name => {
data.reexports.set(name, importName);
});
}
}
});
}
else if (child.isExportAllDeclaration()) {
const data = getData(child.node.source);
if (!data.loc) {
data.loc = child.node.loc;
}
data.reexportAll = {
loc: child.node.loc,
};
}
else if (child.isExportNamedDeclaration() && child.node.source) {
const data = getData(child.node.source);
if (!data.loc) {
data.loc = child.node.loc;
}
child.get('specifiers').forEach(spec => {
if (!spec.isExportSpecifier()) {
throw spec.buildCodeFrameError('Unexpected export specifier type');
}
const importName = spec.get('local').node.name;
const exportName = spec.get('exported').node.name;
data.reexports.set(exportName, importName);
if (exportName === '__esModule') {
throw exportName.buildCodeFrameError('Illegal export "__esModule".');
}
});
}
});
for (const metadata of sourceData.values()) {
if (metadata.importsNamespace.size > 0) {
metadata.interop = 'namespace';
continue;
}
let needsDefault = false;
let needsNamed = false;
for (const importName of metadata.imports.values()) {
if (importName === 'default') {
needsDefault = true;
}
else {
needsNamed = true;
}
}
for (const importName of metadata.reexports.values()) {
if (importName === 'default') {
needsDefault = true;
}
else {
needsNamed = true;
}
}
if (needsDefault && needsNamed) {
// TODO(logan): Using the namespace interop here is unfortunate. Revisit.
metadata.interop = 'namespace';
}
else if (needsDefault) {
metadata.interop = 'default';
}
}
return {
local: localData,
source: sourceData,
};
}
/**
* Get metadata about local variables that are exported.
* @return {Map<string, LocalExportMetadata>}
*/
function getLocalExportMetadata(programPath){
const bindingKindLookup = new Map();
programPath.get('body').forEach(child => {
let kind;
if (child.isImportDeclaration()) {
kind = 'import';
}
else {
if (child.isExportDefaultDeclaration()) {
child = child.get('declaration');
}
if (child.isExportNamedDeclaration() && child.node.declaration) {
child = child.get('declaration');
}
if (child.isFunctionDeclaration()) {
kind = 'hoisted';
}
else if (child.isClassDeclaration()) {
kind = 'block';
}
else if (child.isVariableDeclaration({ kind: 'var' })) {
kind = 'var';
}
else if (child.isVariableDeclaration()) {
kind = 'block';
}
else {
return;
}
}
Object.keys(child.getOuterBindingIdentifiers()).forEach(name => {
bindingKindLookup.set(name, kind);
});
});
const localMetadata = new Map();
const getLocalMetadata = idPath => {
const localName = idPath.node.name;
let metadata = localMetadata.get(localName);
if (!metadata) {
const kind = bindingKindLookup.get(localName);
if (kind === undefined) {
throw idPath.buildCodeFrameError(`Exporting local "${localName}", which is not declared.`);
}
metadata = {
names: [],
kind,
};
localMetadata.set(localName, metadata);
}
return metadata;
};
programPath.get('body').forEach(child => {
if (child.isExportNamedDeclaration() && !child.node.source) {
if (child.node.declaration) {
const declaration = child.get('declaration');
const ids = declaration.getOuterBindingIdentifierPaths();
Object.keys(ids).forEach(name => {
if (name === '__esModule') {
throw declaration.buildCodeFrameError('Illegal export "__esModule".');
}
getLocalMetadata(ids[name]).names.push(name);
});
}
else {
child.get('specifiers').forEach(spec => {
const local = spec.get('local');
const exported = spec.get('exported');
if (exported.node.name === '__esModule') {
throw exported.buildCodeFrameError('Illegal export "__esModule".');
}
getLocalMetadata(local).names.push(exported.node.name);
});
}
}
else if (child.isExportDefaultDeclaration()) {
const declaration = child.get('declaration');
if (
declaration.isFunctionDeclaration() ||
declaration.isClassDeclaration()
) {
getLocalMetadata(declaration.get('id')).names.push('default');
}
else {
// These should have been removed by the nameAnonymousExports() call.
throw declaration.buildCodeFrameError('Unexpected default expression export.');
}
}
});
return localMetadata;
}
/**
* Ensure that all exported values have local binding names.
*/
function nameAnonymousExports(programPath) {
// Name anonymous exported locals.
programPath.get('body').forEach(child => {
if (!child.isExportDefaultDeclaration()) {
return;
}
// export default foo;
const declaration = child.get('declaration');
if (declaration.isFunctionDeclaration()) {
if (!declaration.node.id) {
declaration.node.id = declaration.scope.generateUidIdentifier('default');
}
}
else if (declaration.isClassDeclaration()) {
if (!declaration.node.id) {
declaration.node.id = declaration.scope.generateUidIdentifier('default');
}
}
else {
const id = declaration.scope.generateUidIdentifier('default');
const namedDecl = babelTypes.exportNamedDeclaration(null, [
babelTypes.exportSpecifier(babelTypes.identifier(id.name), babelTypes.identifier('default')),
]);
namedDecl._blockHoist = child.node._blockHoist;
const varDecl = babelTypes.variableDeclaration('var', [
babelTypes.variableDeclarator(id, declaration.node),
]);
varDecl._blockHoist = child.node._blockHoist;
child.replaceWithMultiple([namedDecl, varDecl]);
}
});
}
function removeModuleDeclarations(programPath) {
programPath.get('body').forEach(child => {
if (child.isImportDeclaration()) {
child.remove();
}
else if (child.isExportNamedDeclaration()) {
if (child.node.declaration) {
child.node.declaration._blockHoist = child.node._blockHoist;
child.replaceWith(child.node.declaration);
}
else {
child.remove();
}
}
else if (child.isExportDefaultDeclaration()) {
// export default foo;
const declaration = child.get('declaration');
if (
declaration.isFunctionDeclaration() ||
declaration.isClassDeclaration()
) {
declaration._blockHoist = child.node._blockHoist;
child.replaceWith(declaration);
}
else {
// These should have been removed by the nameAnonymousExports() call.
throw declaration.buildCodeFrameError('Unexpected default expression export.');
}
}
else if (child.isExportAllDeclaration()) {
child.remove();
}
});
}
/**
* Perform all of the generic ES6 module rewriting needed to handle initial
* module processing. This function will rewrite the majority of the given
* program to reference the modules described by the returned metadata,
* and returns a list of statements for use when initializing the module.
*/
function rewriteModuleStatementsAndPrepare(path) {
path.node.sourceType = 'script';
const meta = normalizeModuleAndLoadMetadata(path);
return meta;
}
/**
* Create the runtime initialization statements for a given requested source.
* These will initialize all of the runtime import/export logic that
* can't be handled statically by the statements created by
* buildExportInitializationStatements().
*/
function buildNamespaceInitStatements(meta, metadata, checkExport) {
const statements = [];
const {localImportName, localImportDefaultName} = getLocalImportName(metadata);
for (const exportName of metadata.reexportNamespace) {
// Assign export to namespace object.
checkExport(exportName);
statements.push(buildExport({exportName, localName: localImportName}));
}
// Source code:
// import {color2 as color2Alias, color3, color4, color5} from 'xxx';
// export {default as b} from 'xxx';
// export {color2Alias};
// export {color3};
// let color5Renamed = color5
// export {color5Renamed};
// Only two entries in metadata.reexports:
// 'color2Alias' => 'color2'
// 'color3' => 'color3',
// 'b' => 'default'
//
// And consider:
// export {default as defaultAsBB} from './xx/yy';
// export {exportSingle} from './xx/yy';
// No entries in metadata.imports, and 'default' exists in metadata.reexports.
for (const entry of metadata.reexports.entries()) {
const exportName = entry[0];
checkExport(exportName);
statements.push(
(localImportDefaultName || entry[1] === 'default')
? buildExport({exportName, localName: localImportName})
: buildExport({exportName, namespace: localImportName, propName: entry[1]})
);
}
if (metadata.reexportAll) {
const statement = buildNamespaceReexport(
meta,
metadata.name,
checkExport
);
statement.loc = metadata.reexportAll.loc;
// Iterate props creating getter for each prop.
statements.push(statement);
}
return statements;
}
/**
* Create a re-export initialization loop for a specific imported namespace.
*/
function buildNamespaceReexport(meta, namespace, checkExport) {
checkExport();
return babelTemplate.statement(`
(function() {
for (var key in NAMESPACE) {
if (NAMESPACE == null || !NAMESPACE.hasOwnProperty(key) || key === 'default' || key === '__esModule') return;
VERIFY_NAME_LIST;
exports[key] = NAMESPACE[key];
}
})();
`)({
NAMESPACE: namespace,
VERIFY_NAME_LIST: meta.exportNameListName
? babelTemplate.statement(`
if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return;
`)({EXPORTS_LIST: meta.exportNameListName})
: null
});
}
function buildRequireStatements(types, source, metadata) {
let headers = [];
const loadExpr = types.callExpression(
types.identifier('require'),
// replace `require('./src/xxx')` to `require('./lib/xxx')`
// for echarts and zrender in old npm or webpack.
[types.stringLiteral(source.replace('/src/', '/lib/'))]
);
// side effect import: import 'xxx';
if (isSideEffectImport(metadata)) {
let header = types.expressionStatement(loadExpr);
header.loc = metadata.loc;
headers.push(header);
}
else {
const {localImportName, localImportDefaultName} = getLocalImportName(metadata);
let reqHeader = types.variableDeclaration('var', [
types.variableDeclarator(
types.identifier(localImportName),
loadExpr
)
]);
reqHeader.loc = metadata.loc;
headers.push(reqHeader);
if (!localImportDefaultName) {
// src:
// import {someInZrUtil1 as someInZrUtil1Alias, zz} from 'zrender/core/util';
// metadata.imports:
// Map { 'someInZrUtil1Alias' => 'someInZrUtil1', 'zz' => 'zz' }
for (const importEntry of metadata.imports) {
headers.push(
babelTemplate.statement(`var IMPORTNAME = NAMESPACE.PROPNAME;`)({
NAMESPACE: localImportName,
IMPORTNAME: importEntry[0],
PROPNAME: importEntry[1]
})
);
}
}
}
return headers;
}
function getLocalImportName(metadata) {
const localImportDefaultName = getDefaultName(metadata.imports);
assert(
!localImportDefaultName || metadata.imports.size === 1,
'Forbiden that both import default and others.'
);
return {
localImportName: localImportDefaultName || metadata.name,
localImportDefaultName
};
}
function getDefaultName(map) {
for (const entry of map) {
if (entry[1] === 'default') {
return entry[0];
}
}
}
function buildLocalExportStatements(meta, checkExport) {
let tails = [];
// All local export, for example:
// Map {
// 'localVarMame' => {
// names: [ 'exportName1', 'exportName2' ],
// kind: 'var'
// },
for (const localEntry of meta.local) {
for (const exportName of localEntry[1].names) {
checkExport(exportName);
tails.push(buildExport({exportName, localName: localEntry[0]}));
}
}
return tails;
}
function createExportChecker() {
let someHasBeenExported;
return function checkExport(exportName) {
assert(
!someHasBeenExported || exportName !== 'default',
`Forbiden that both export default and others.`
);
someHasBeenExported = true;
};
}
function buildExport({exportName, namespace, propName, localName}) {
const exportDefault = exportName === 'default';
const head = exportDefault ? 'module.exports' : `exports.${exportName}`;
let opt = {};
// FIXME
// Does `PRIORITY`, `LOCATION_PARAMS` recognised as babel-template placeholder?
// We have to do this for workaround temporarily.
if (/^[A-Z0-9_]+$/.test(localName)) {
opt[localName] = localName;
}
return babelTemplate.statement(
localName
? `${head} = ${localName};`
: `${head} = ${namespace}.${propName};`
)(opt);
}
/**
* Consider this case:
* export var a;
* function inject(b) {
* a = b;
* }
* It will be transpiled to:
* var a;
* exports.a = 1;
* function inject(b) {
* a = b;
* }
* That is a wrong transpilation, because the `export.a` will not
* be assigned as `b` when `inject` called.
* Of course, it can be transpiled correctly as:
* var _locals = {};
* var a;
* Object.defineProperty(exports, 'a', {
* get: function () { return _locals[a]; }
* };
* exports.a = a;
* function inject(b) {
* _locals[a] = b;
* }
* But it is not ES3 compatible.
* So we just forbiden this usage here.
*/
function checkAssignOrUpdateExport(programPath, meta) {
let visitor = {
// Include:
// `a++;` (no `path.get('left')`)
// `x += 1212`;
UpdateExpression: {
exit: function exit(path, scope) {
// console.log(arguments);
let left = path.get('left');
if (left && left.isIdentifier()) {
asertNotAssign(path, left.node.name);
}
}
},
// Include:
// `x = 5;` (`x` is an identifier.)
// `c.d = 3;` (but `c.d` is not an identifier.)
// `y = function () {}`
// Exclude:
// `var x = 121;`
// `export var x = 121;`
AssignmentExpression: {
exit: function exit(path) {
let left = path.get('left');
if (left.isIdentifier()) {
asertNotAssign(path, left.node.name);
}
}
}
};
function asertNotAssign(path, localName) {
// Ignore variables that is not in global scope.
if (programPath.scope.getBinding(localName) !== path.scope.getBinding(localName)) {
return;
}
for (const localEntry of meta.local) {
assert(
localName !== localEntry[0],
`An exported variable \`${localEntry[0]}\` is forbiden to be assigned.`
);
}
}
programPath.traverse(visitor);
}