-
-
Notifications
You must be signed in to change notification settings - Fork 556
/
transform.js
706 lines (572 loc) · 21.5 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
/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
import { dirname, resolve } from 'path';
import { attachScopes, extractAssignedNames, makeLegalIdentifier } from '@rollup/pluginutils';
import { walk } from 'estree-walker';
import MagicString from 'magic-string';
import { sync as nodeResolveSync } from 'resolve';
import { flatten, isFalsy, isReference, isTruthy } from './ast-utils';
import {
DYNAMIC_JSON_PREFIX,
DYNAMIC_REGISTER_PREFIX,
getProxyId,
getVirtualPathForDynamicRequirePath,
HELPERS_ID
} from './helpers';
import { getName } from './utils';
const reserved = 'process location abstract arguments boolean break byte case catch char class const continue debugger default delete do double else enum eval export extends false final finally float for from function goto if implements import in instanceof int interface let long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with yield'.split(
' '
);
const blacklist = { __esModule: true };
reserved.forEach((word) => (blacklist[word] = true));
const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
function deconflict(scope, globals, identifier) {
let i = 1;
let deconflicted = makeLegalIdentifier(identifier);
while (scope.contains(deconflicted) || globals.has(deconflicted) || deconflicted in blacklist) {
deconflicted = `${identifier}_${i}`;
i += 1;
}
scope.declarations[deconflicted] = true;
return deconflicted;
}
function tryParse(parse, code, id) {
try {
return parse(code, { allowReturnOutsideFunction: true });
} catch (err) {
err.message += ` in ${id}`;
throw err;
}
}
export function normalizePathSlashes(path) {
return path.replace(/\\/g, '/');
}
export function hasCjsKeywords(code, ignoreGlobal) {
const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
return firstpass.test(code);
}
export function checkEsModule(parse, code, id) {
const ast = tryParse(parse, code, id);
let isEsModule = false;
let hasDefaultExport = false;
let hasNamedExports = false;
for (const node of ast.body) {
if (node.type === 'ExportDefaultDeclaration') {
isEsModule = true;
hasDefaultExport = true;
} else if (node.type === 'ExportNamedDeclaration') {
isEsModule = true;
if (node.declaration) {
hasNamedExports = true;
} else {
for (const specifier of node.specifiers) {
if (specifier.exported.name === 'default') {
hasDefaultExport = true;
} else {
hasNamedExports = true;
}
}
}
} else if (node.type === 'ExportAllDeclaration') {
isEsModule = true;
if (node.exported && node.exported.name === 'default') {
hasDefaultExport = true;
} else {
hasNamedExports = true;
}
} else if (node.type === 'ImportDeclaration') {
isEsModule = true;
}
}
return { isEsModule, hasDefaultExport, hasNamedExports, ast };
}
function getDefinePropertyCallName(node, targetName) {
if (node.type !== 'CallExpression') return;
const {
callee: { object, property }
} = node;
if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
if (node.arguments.length !== 3) return;
const [target, val] = node.arguments;
if (target.type !== 'Identifier' || target.name !== targetName) return;
// eslint-disable-next-line consistent-return
return val.value;
}
export function transformCommonjs(
parse,
code,
id,
isEsModule,
ignoreGlobal,
ignoreRequire,
sourceMap,
isDynamicRequireModulesEnabled,
dynamicRequireModuleSet,
disableWrap,
commonDir,
astCache
) {
const ast = astCache || tryParse(parse, code, id);
const magicString = new MagicString(code);
const required = {};
// Because objects have no guaranteed ordering, yet we need it,
// we need to keep track of the order in a array
const sources = [];
let uid = 0;
let scope = attachScopes(ast, 'scope');
const uses = { module: false, exports: false, global: false, require: false };
let lexicalDepth = 0;
let programDepth = 0;
const globals = new Set();
// TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
const namedExports = {};
// TODO handle transpiled modules
let shouldWrap = /__esModule/.test(code);
let usesCommonjsHelpers = false;
function isRequireStatement(node) {
if (!node) return false;
if (node.type !== 'CallExpression') return false;
// Weird case of `require()` or `module.require()` without arguments
if (node.arguments.length === 0) return false;
return isRequireIdentifier(node.callee);
}
function isRequireIdentifier(node) {
if (!node) return false;
if (node.type === 'Identifier' && node.name === 'require' /* `require` */) {
// `require` is hidden by a variable in local scope
if (scope.contains('require')) return false;
return true;
} else if (node.type === 'MemberExpression' /* `[something].[something]` */) {
// `module.[something]`
if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false;
// `module` is hidden by a variable in local scope
if (scope.contains('module')) return false;
// `module.require(...)`
if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
return true;
}
return false;
}
function hasDynamicArguments(node) {
return (
node.arguments.length > 1 ||
(node.arguments[0].type !== 'Literal' &&
(node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
);
}
function isStaticRequireStatement(node) {
if (!isRequireStatement(node)) return false;
return !hasDynamicArguments(node);
}
function isNodeRequireStatement(parent) {
const reservedMethod = ['resolve', 'cache', 'main'];
return !!(parent && parent.property && reservedMethod.indexOf(parent.property.name) > -1);
}
function isIgnoredRequireStatement(requiredNode) {
return ignoreRequire(requiredNode.arguments[0].value);
}
function getRequireStringArg(node) {
return node.arguments[0].type === 'Literal'
? node.arguments[0].value
: node.arguments[0].quasis[0].value.cooked;
}
function getRequired(node, name) {
let sourceId = getRequireStringArg(node);
const isDynamicRegister = sourceId.startsWith(DYNAMIC_REGISTER_PREFIX);
if (isDynamicRegister) {
sourceId = sourceId.substr(DYNAMIC_REGISTER_PREFIX.length);
}
const existing = required[sourceId];
// eslint-disable-next-line no-undefined
if (existing === undefined) {
const isDynamic = hasDynamicModuleForPath(sourceId);
if (!name) {
do {
name = `require$$${uid}`;
uid += 1;
} while (scope.contains(name));
}
if (isDynamicRegister && sourceId.endsWith('.json')) {
sourceId = DYNAMIC_JSON_PREFIX + sourceId;
}
if (isDynamicRegister || !isDynamic || sourceId.endsWith('.json')) {
sources.push([sourceId, isDynamicRegister]);
}
required[sourceId] = { source: sourceId, name, importsDefault: false, isDynamic };
}
return required[sourceId];
}
function hasDynamicModuleForPath(source) {
if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
try {
const resolvedPath = normalizePathSlashes(
nodeResolveSync(source, { basedir: dirname(id) })
);
if (dynamicRequireModuleSet.has(resolvedPath)) {
return true;
}
} catch (ex) {
// Probably a node.js internal module
return false;
}
return false;
}
for (const attemptExt of ['', '.js', '.json']) {
const resolvedPath = normalizePathSlashes(resolve(dirname(id), source + attemptExt));
if (dynamicRequireModuleSet.has(resolvedPath)) {
return true;
}
}
return false;
}
function shouldUseSimulatedRequire(required) {
return (
hasDynamicModuleForPath(required.source) &&
// We only do `commonjsRequire` for json if it's the `commonjsRegister` call.
(required.source.startsWith(DYNAMIC_REGISTER_PREFIX) || !required.source.endsWith('.json'))
);
}
// do a first pass, see which names are assigned to. This is necessary to prevent
// illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
// where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
const assignedTo = new Set();
walk(ast, {
enter(node) {
if (node.type !== 'AssignmentExpression') return;
if (node.left.type === 'MemberExpression') return;
extractAssignedNames(node.left).forEach((name) => {
assignedTo.add(name);
});
}
});
walk(ast, {
enter(node, parent) {
if (sourceMap) {
magicString.addSourcemapLocation(node.start);
magicString.addSourcemapLocation(node.end);
}
// skip dead branches
if (parent && (parent.type === 'IfStatement' || parent.type === 'ConditionalExpression')) {
if (node === parent.consequent && isFalsy(parent.test)) {
this.skip();
return;
}
if (node === parent.alternate && isTruthy(parent.test)) {
this.skip();
return;
}
}
if (node._skip) {
this.skip();
return;
}
programDepth += 1;
if (node.scope) ({ scope } = node);
if (functionType.test(node.type)) lexicalDepth += 1;
// if toplevel return, we need to wrap it
if (node.type === 'ReturnStatement' && lexicalDepth === 0) {
shouldWrap = true;
}
// rewrite `this` as `commonjsHelpers.commonjsGlobal`
if (node.type === 'ThisExpression' && lexicalDepth === 0) {
uses.global = true;
if (!ignoreGlobal) {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
usesCommonjsHelpers = true;
}
return;
}
// rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
if (node.type === 'UnaryExpression' && node.operator === 'typeof') {
const flattened = flatten(node.argument);
if (!flattened) return;
if (scope.contains(flattened.name)) return;
if (
flattened.keypath === 'module.exports' ||
flattened.keypath === 'module' ||
flattened.keypath === 'exports'
) {
magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
}
}
// rewrite `require` (if not already handled) `global` and `define`, and handle free references to
// `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
if (node.type === 'Identifier') {
if (isReference(node, parent) && !scope.contains(node.name)) {
if (node.name in uses) {
if (isRequireIdentifier(node)) {
if (isNodeRequireStatement(parent)) {
return;
}
if (!isDynamicRequireModulesEnabled && isStaticRequireStatement(parent)) {
return;
}
if (isDynamicRequireModulesEnabled && isRequireStatement(parent)) {
magicString.appendLeft(
parent.end - 1,
`,${JSON.stringify(
dirname(id) === '.'
? null /* default behavior */
: getVirtualPathForDynamicRequirePath(
normalizePathSlashes(dirname(id)),
commonDir
)
)}`
);
}
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
storeName: true
});
usesCommonjsHelpers = true;
}
uses[node.name] = true;
if (node.name === 'global' && !ignoreGlobal) {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
usesCommonjsHelpers = true;
}
// if module or exports are used outside the context of an assignment
// expression, we need to wrap the module
if (node.name === 'module' || node.name === 'exports') {
shouldWrap = true;
}
}
if (node.name === 'define') {
magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
}
globals.add(node.name);
}
return;
}
// Is this an assignment to exports or module.exports?
if (node.type === 'AssignmentExpression') {
if (node.left.type !== 'MemberExpression') return;
const flattened = flatten(node.left);
if (!flattened) return;
if (scope.contains(flattened.name)) return;
const match = exportsPattern.exec(flattened.keypath);
if (!match || flattened.keypath === 'exports') return;
uses[flattened.name] = true;
// we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
// if this isn't top-level, we'll need to wrap the module
if (programDepth > 3) shouldWrap = true;
node.left._skip = true;
if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
node.right.properties.forEach((prop) => {
if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
const { name } = prop.key;
if (name === makeLegalIdentifier(name)) namedExports[name] = true;
});
return;
}
if (match[1]) namedExports[match[1]] = true;
return;
}
const name = getDefinePropertyCallName(node, 'exports');
if (name && name === makeLegalIdentifier(name)) namedExports[name] = true;
// if this is `var x = require('x')`, we can do `import x from 'x'`
if (
node.type === 'VariableDeclarator' &&
node.id.type === 'Identifier' &&
isStaticRequireStatement(node.init) &&
!isIgnoredRequireStatement(node.init)
) {
// for now, only do this for top-level requires. maybe fix this in future
if (scope.parent) return;
// edge case — CJS allows you to assign to imports. ES doesn't
if (assignedTo.has(node.id.name)) return;
const required = getRequired(node.init, node.id.name);
required.importsDefault = true;
if (required.name === node.id.name && !required.isDynamic) {
node._shouldRemove = true;
}
}
if (!isStaticRequireStatement(node) || isIgnoredRequireStatement(node)) {
return;
}
const required = getRequired(node);
if (parent.type === 'ExpressionStatement') {
// is a bare import, e.g. `require('foo');`
magicString.remove(parent.start, parent.end);
} else {
required.importsDefault = true;
if (shouldUseSimulatedRequire(required)) {
magicString.overwrite(
node.start,
node.end,
`${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
getVirtualPathForDynamicRequirePath(normalizePathSlashes(required.source), commonDir)
)}, ${JSON.stringify(
dirname(id) === '.'
? null /* default behavior */
: getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir)
)})`
);
usesCommonjsHelpers = true;
} else {
magicString.overwrite(node.start, node.end, required.name);
}
}
node.callee._skip = true;
},
leave(node) {
programDepth -= 1;
if (node.scope) scope = scope.parent;
if (functionType.test(node.type)) lexicalDepth -= 1;
if (node.type === 'VariableDeclaration') {
let keepDeclaration = false;
let c = node.declarations[0].start;
for (let i = 0; i < node.declarations.length; i += 1) {
const declarator = node.declarations[i];
if (declarator._shouldRemove) {
magicString.remove(c, declarator.end);
} else {
if (!keepDeclaration) {
magicString.remove(c, declarator.start);
keepDeclaration = true;
}
c = declarator.end;
}
}
if (!keepDeclaration) {
magicString.remove(node.start, node.end);
}
}
}
});
// If `isEsModule` is on, it means it has ES6 import/export statements,
// which just can't be wrapped in a function.
shouldWrap = shouldWrap && !disableWrap && !isEsModule;
usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
if (
!sources.length &&
!uses.module &&
!uses.exports &&
!uses.require &&
!usesCommonjsHelpers &&
(ignoreGlobal || !uses.global)
) {
return { meta: { commonjs: { isCommonJS: false } } };
}
const importBlock = `${(usesCommonjsHelpers
? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`]
: []
)
.concat(
// dynamic registers first (`commonjsRegister(,,,)`), as the may be required in the other modules
sources
.filter(([, isDynamicRegister]) => isDynamicRegister)
.map(([source]) => `import '${source}';`),
// now the solid modules, non-commonjsRegister
sources
.filter(([, isDynamicRegister]) => !isDynamicRegister)
.map(([source]) => `import '${source}';`),
// now the proxies for solid modules (non-commonjsRegister)
sources
.filter(([, isDynamicRegister]) => !isDynamicRegister)
.map(([source]) => {
const { name, importsDefault } = required[source];
return `import ${importsDefault ? `${name} from ` : ``}'${
source.startsWith('\0') ? source : getProxyId(source)
}';`;
})
)
.join('\n')}\n\n`;
const namedExportDeclarations = [];
let wrapperStart = '';
let wrapperEnd = '';
const moduleName = deconflict(scope, globals, getName(id));
if (!isEsModule) {
const exportModuleExports = {
str: `export { ${moduleName} as __moduleExports };`,
name: '__moduleExports'
};
namedExportDeclarations.push(exportModuleExports);
}
const defaultExportPropertyAssignments = [];
let hasDefaultExport = false;
if (shouldWrap) {
const args = `module${uses.exports ? ', exports' : ''}`;
wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
wrapperEnd = `\n}`;
if (isDynamicRequireModulesEnabled) {
wrapperEnd += `, ${JSON.stringify(
getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir)
)}`;
}
wrapperEnd += `);`;
} else {
const names = [];
for (const node of ast.body) {
if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
const { left } = node.expression;
const flattened = flatten(left);
if (!flattened) {
continue;
}
const match = exportsPattern.exec(flattened.keypath);
if (!match) {
continue;
}
if (flattened.keypath === 'module.exports') {
hasDefaultExport = true;
magicString.overwrite(left.start, left.end, `var ${moduleName}`);
} else {
const [, name] = match;
const deconflicted = deconflict(scope, globals, name);
names.push({ name, deconflicted });
magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
const declaration =
name === deconflicted
? `export { ${name} };`
: `export { ${deconflicted} as ${name} };`;
if (name !== 'default') {
namedExportDeclarations.push({
str: declaration,
name
});
}
defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
}
}
}
if (!(isEsModule || hasDefaultExport)) {
wrapperEnd = `\n\nvar ${moduleName} = {\n${names
.map(({ name, deconflicted }) => `\t${name}: ${deconflicted}`)
.join(',\n')}\n};`;
}
}
magicString
.trim()
.prepend(importBlock + wrapperStart)
.trim()
.append(wrapperEnd);
const defaultExport =
code.indexOf('__esModule') >= 0
? `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
: `export default ${moduleName};`;
const named = namedExportDeclarations
.filter((x) => x.name !== 'default' || !hasDefaultExport)
.map((x) => x.str);
magicString.append(
`\n\n${(isEsModule ? [] : [defaultExport])
.concat(named)
.concat(hasDefaultExport ? defaultExportPropertyAssignments : [])
.join('\n')}`
);
code = magicString.toString();
const map = sourceMap ? magicString.generateMap() : null;
return {
code,
map,
syntheticNamedExports: isEsModule ? false : '__moduleExports',
meta: { commonjs: { isCommonJS: !isEsModule } }
};
}