@rollup/plugin-commonjs 13.0.2 → 16.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,226 +1,103 @@
1
1
  'use strict';
2
2
 
3
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
-
5
- var fs = require('fs');
6
3
  var path = require('path');
7
4
  var pluginutils = require('@rollup/pluginutils');
8
- var getCommonDir = _interopDefault(require('commondir'));
9
- var glob = _interopDefault(require('glob'));
5
+ var getCommonDir = require('commondir');
6
+ var fs = require('fs');
10
7
  var estreeWalker = require('estree-walker');
11
- var MagicString = _interopDefault(require('magic-string'));
8
+ var MagicString = require('magic-string');
12
9
  var resolve = require('resolve');
13
- var isReference = _interopDefault(require('is-reference'));
14
-
15
- function _slicedToArray(arr, i) {
16
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
17
- }
18
-
19
- function _arrayWithHoles(arr) {
20
- if (Array.isArray(arr)) return arr;
21
- }
22
-
23
- function _iterableToArrayLimit(arr, i) {
24
- if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
25
- var _arr = [];
26
- var _n = true;
27
- var _d = false;
28
- var _e = undefined;
29
-
30
- try {
31
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
32
- _arr.push(_s.value);
33
-
34
- if (i && _arr.length === i) break;
35
- }
36
- } catch (err) {
37
- _d = true;
38
- _e = err;
39
- } finally {
40
- try {
41
- if (!_n && _i["return"] != null) _i["return"]();
42
- } finally {
43
- if (_d) throw _e;
44
- }
45
- }
46
-
47
- return _arr;
48
- }
49
-
50
- function _unsupportedIterableToArray(o, minLen) {
51
- if (!o) return;
52
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
53
- var n = Object.prototype.toString.call(o).slice(8, -1);
54
- if (n === "Object" && o.constructor) n = o.constructor.name;
55
- if (n === "Map" || n === "Set") return Array.from(n);
56
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
57
- }
58
-
59
- function _arrayLikeToArray(arr, len) {
60
- if (len == null || len > arr.length) len = arr.length;
61
-
62
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
63
-
64
- return arr2;
65
- }
66
-
67
- function _nonIterableRest() {
68
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
69
- }
70
-
71
- function _createForOfIteratorHelper(o) {
72
- if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
73
- if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {
74
- var i = 0;
75
-
76
- var F = function () {};
77
-
78
- return {
79
- s: F,
80
- n: function () {
81
- if (i >= o.length) return {
82
- done: true
83
- };
84
- return {
85
- done: false,
86
- value: o[i++]
87
- };
88
- },
89
- e: function (e) {
90
- throw e;
91
- },
92
- f: F
93
- };
94
- }
10
+ var isReference = require('is-reference');
11
+ var glob = require('glob');
95
12
 
96
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
97
- }
13
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
98
14
 
99
- var it,
100
- normalCompletion = true,
101
- didErr = false,
102
- err;
103
- return {
104
- s: function () {
105
- it = o[Symbol.iterator]();
106
- },
107
- n: function () {
108
- var step = it.next();
109
- normalCompletion = step.done;
110
- return step;
111
- },
112
- e: function (e) {
113
- didErr = true;
114
- err = e;
115
- },
116
- f: function () {
117
- try {
118
- if (!normalCompletion && it.return != null) it.return();
119
- } finally {
120
- if (didErr) throw err;
121
- }
122
- }
123
- };
124
- }
15
+ var getCommonDir__default = /*#__PURE__*/_interopDefaultLegacy(getCommonDir);
16
+ var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
17
+ var isReference__default = /*#__PURE__*/_interopDefaultLegacy(isReference);
18
+ var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
125
19
 
126
20
  var peerDependencies = {
127
- rollup: "^2.3.4"
21
+ rollup: "^2.30.0"
128
22
  };
129
23
 
130
- /* eslint-disable no-undefined */
131
- const operators = {
132
- '==': x => equals(x.left, x.right, false),
133
- '!=': x => not(operators['=='](x)),
134
- '===': x => equals(x.left, x.right, true),
135
- '!==': x => not(operators['==='](x)),
136
- '!': x => isFalsy(x.argument),
137
- '&&': x => isTruthy(x.left) && isTruthy(x.right),
138
- '||': x => isTruthy(x.left) || isTruthy(x.right)
139
- };
140
- function flatten(node) {
141
- const parts = [];
142
-
143
- while (node.type === 'MemberExpression') {
144
- if (node.computed) return null;
145
- parts.unshift(node.property.name); // eslint-disable-next-line no-param-reassign
146
-
147
- node = node.object;
148
- }
149
-
150
- if (node.type !== 'Identifier') return null;
151
- const _node = node,
152
- name = _node.name;
153
- parts.unshift(name);
154
- return {
155
- name,
156
- keypath: parts.join('.')
157
- };
158
- }
159
-
160
- function isTruthy(node) {
161
- if (node.type === 'Literal') return !!node.value;
162
- if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
163
- if (node.operator in operators) return operators[node.operator](node);
164
- return undefined;
165
- }
166
- function isFalsy(node) {
167
- return not(isTruthy(node));
168
- }
169
-
170
- function not(value) {
171
- return value === undefined ? value : !value;
172
- }
173
-
174
- function equals(a, b, strict) {
175
- if (a.type !== b.type) return undefined; // eslint-disable-next-line eqeqeq
176
-
177
- if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
178
- return undefined;
179
- }
24
+ const isWrappedId = (id, suffix) => id.endsWith(suffix);
25
+ const wrapId = (id, suffix) => `\0${id}${suffix}`;
26
+ const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
180
27
 
181
28
  const PROXY_SUFFIX = '?commonjs-proxy';
182
- const getProxyId = id => `\0${id}${PROXY_SUFFIX}`;
183
- const getIdFromProxyId = proxyId => proxyId.slice(1, -PROXY_SUFFIX.length);
29
+ const REQUIRE_SUFFIX = '?commonjs-require';
184
30
  const EXTERNAL_SUFFIX = '?commonjs-external';
185
- const getExternalProxyId = id => `\0${id}${EXTERNAL_SUFFIX}`;
186
- const getIdFromExternalProxyId = proxyId => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
31
+
187
32
  const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
188
33
  const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
189
34
  if (path.startsWith(commonDir)) return VIRTUAL_PATH_BASE + path.slice(commonDir.length);
190
35
  return path;
191
36
  };
37
+
192
38
  const DYNAMIC_REGISTER_PREFIX = '\0commonjs-dynamic-register:';
193
39
  const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
194
40
  const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
195
- const HELPERS_ID = '\0commonjsHelpers.js'; // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
196
- // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
197
41
 
42
+ const HELPERS_ID = '\0commonjsHelpers.js';
43
+
44
+ // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
45
+ // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
46
+ // This will no longer be necessary once Rollup switches to ES6 output, likely
47
+ // in Rollup 3
48
+
49
+ // The "hasOwnProperty" call in "getDefaultExportFromCjs" is technically not
50
+ // needed, but for consumers that use Rollup's old interop pattern, it will fix
51
+ // rollup/rollup-plugin-commonjs#224
52
+ // We should remove it once Rollup core and this plugin are updated to not use
53
+ // this pattern any more
198
54
  const HELPERS = `
199
55
  export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
200
56
 
201
- export function unwrapExports (x) {
57
+ export function getDefaultExportFromCjs (x) {
202
58
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
203
59
  }
204
60
 
205
61
  export function createCommonjsModule(fn, basedir, module) {
206
62
  return module = {
207
- path: basedir,
208
- exports: {},
209
- require: function (path, base) {
210
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
211
- }
63
+ path: basedir,
64
+ exports: {},
65
+ require: function (path, base) {
66
+ return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
67
+ }
212
68
  }, fn(module, module.exports), module.exports;
213
69
  }
214
70
 
215
- export function getCjsExportFromNamespace (n) {
216
- return n && n['default'] || n;
71
+ export function getDefaultExportFromNamespaceIfPresent (n) {
72
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
73
+ }
74
+
75
+ export function getDefaultExportFromNamespaceIfNotNamed (n) {
76
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
77
+ }
78
+
79
+ export function getAugmentedNamespace(n) {
80
+ if (n.__esModule) return n;
81
+ var a = Object.defineProperty({}, '__esModule', {value: true});
82
+ Object.keys(n).forEach(function (k) {
83
+ var d = Object.getOwnPropertyDescriptor(n, k);
84
+ Object.defineProperty(a, k, d.get ? d : {
85
+ enumerable: true,
86
+ get: function () {
87
+ return n[k];
88
+ }
89
+ });
90
+ });
91
+ return a;
217
92
  }
218
93
  `;
94
+
219
95
  const HELPER_NON_DYNAMIC = `
220
96
  export function commonjsRequire () {
221
97
  throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
222
98
  }
223
99
  `;
100
+
224
101
  const HELPERS_DYNAMIC = `
225
102
  export function commonjsRegister (path, loader) {
226
103
  DYNAMIC_REQUIRE_LOADERS[path] = loader;
@@ -360,27 +237,92 @@ export function commonjsRequire (path, originalModuleDir) {
360
237
  commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
361
238
  `;
362
239
 
240
+ function getHelpersModule(isDynamicRequireModulesEnabled) {
241
+ return `${HELPERS}${isDynamicRequireModulesEnabled ? HELPERS_DYNAMIC : HELPER_NON_DYNAMIC}`;
242
+ }
243
+
244
+ /* eslint-disable no-undefined */
245
+
246
+ const operators = {
247
+ '==': (x) => equals(x.left, x.right, false),
248
+
249
+ '!=': (x) => not(operators['=='](x)),
250
+
251
+ '===': (x) => equals(x.left, x.right, true),
252
+
253
+ '!==': (x) => not(operators['==='](x)),
254
+
255
+ '!': (x) => isFalsy(x.argument),
256
+
257
+ '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
258
+
259
+ '||': (x) => isTruthy(x.left) || isTruthy(x.right)
260
+ };
261
+
262
+ function flatten(node) {
263
+ const parts = [];
264
+
265
+ while (node.type === 'MemberExpression') {
266
+ if (node.computed) return null;
267
+
268
+ parts.unshift(node.property.name);
269
+ // eslint-disable-next-line no-param-reassign
270
+ node = node.object;
271
+ }
272
+
273
+ if (node.type !== 'Identifier') return null;
274
+
275
+ const { name } = node;
276
+ parts.unshift(name);
277
+
278
+ return { name, keypath: parts.join('.') };
279
+ }
280
+
281
+ function isTruthy(node) {
282
+ if (node.type === 'Literal') return !!node.value;
283
+ if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
284
+ if (node.operator in operators) return operators[node.operator](node);
285
+ return undefined;
286
+ }
287
+
288
+ function isFalsy(node) {
289
+ return not(isTruthy(node));
290
+ }
291
+
292
+ function not(value) {
293
+ return value === undefined ? value : !value;
294
+ }
295
+
296
+ function equals(a, b, strict) {
297
+ if (a.type !== b.type) return undefined;
298
+ // eslint-disable-next-line eqeqeq
299
+ if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
300
+ return undefined;
301
+ }
302
+
363
303
  /* eslint-disable import/prefer-default-export */
304
+
364
305
  function getName(id) {
365
306
  const name = pluginutils.makeLegalIdentifier(path.basename(id, path.extname(id)));
366
-
367
307
  if (name !== 'index') {
368
308
  return name;
369
309
  }
370
-
371
310
  const segments = path.dirname(id).split(path.sep);
372
311
  return pluginutils.makeLegalIdentifier(segments[segments.length - 1]);
373
312
  }
374
313
 
375
- 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(' ');
376
- const blacklist = {
377
- __esModule: true
378
- };
379
- reserved.forEach(word => blacklist[word] = true);
314
+ /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
315
+
316
+ 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(
317
+ ' '
318
+ );
319
+ const blacklist = { __esModule: true };
320
+ reserved.forEach((word) => (blacklist[word] = true));
321
+
380
322
  const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
323
+
381
324
  const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
382
325
  const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
383
- const importExportDeclaration = /^(?:Import|Export(?:Named|Default))Declaration/;
384
326
  const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
385
327
 
386
328
  function deconflict(scope, globals, identifier) {
@@ -391,16 +333,14 @@ function deconflict(scope, globals, identifier) {
391
333
  deconflicted = `${identifier}_${i}`;
392
334
  i += 1;
393
335
  }
394
-
395
336
  scope.declarations[deconflicted] = true;
337
+
396
338
  return deconflicted;
397
339
  }
398
340
 
399
341
  function tryParse(parse, code, id) {
400
342
  try {
401
- return parse(code, {
402
- allowReturnOutsideFunction: true
403
- });
343
+ return parse(code, { allowReturnOutsideFunction: true });
404
344
  } catch (err) {
405
345
  err.message += ` in ${id}`;
406
346
  throw err;
@@ -410,147 +350,162 @@ function tryParse(parse, code, id) {
410
350
  function normalizePathSlashes(path) {
411
351
  return path.replace(/\\/g, '/');
412
352
  }
353
+
413
354
  function hasCjsKeywords(code, ignoreGlobal) {
414
355
  const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
415
356
  return firstpass.test(code);
416
357
  }
358
+
417
359
  function checkEsModule(parse, code, id) {
418
360
  const ast = tryParse(parse, code, id);
419
- let isEsModule = false;
420
-
421
- var _iterator = _createForOfIteratorHelper(ast.body),
422
- _step;
423
361
 
424
- try {
425
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
426
- const node = _step.value;
427
- if (node.type === 'ExportDefaultDeclaration') return {
428
- isEsModule: true,
429
- hasDefaultExport: true,
430
- ast
431
- };
432
-
433
- if (node.type === 'ExportNamedDeclaration') {
434
- isEsModule = true;
435
-
436
- var _iterator2 = _createForOfIteratorHelper(node.specifiers),
437
- _step2;
438
-
439
- try {
440
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
441
- const specifier = _step2.value;
442
-
443
- if (specifier.exported.name === 'default') {
444
- return {
445
- isEsModule: true,
446
- hasDefaultExport: true,
447
- ast
448
- };
449
- }
362
+ let isEsModule = false;
363
+ let hasDefaultExport = false;
364
+ let hasNamedExports = false;
365
+ for (const node of ast.body) {
366
+ if (node.type === 'ExportDefaultDeclaration') {
367
+ isEsModule = true;
368
+ hasDefaultExport = true;
369
+ } else if (node.type === 'ExportNamedDeclaration') {
370
+ isEsModule = true;
371
+ if (node.declaration) {
372
+ hasNamedExports = true;
373
+ } else {
374
+ for (const specifier of node.specifiers) {
375
+ if (specifier.exported.name === 'default') {
376
+ hasDefaultExport = true;
377
+ } else {
378
+ hasNamedExports = true;
450
379
  }
451
- } catch (err) {
452
- _iterator2.e(err);
453
- } finally {
454
- _iterator2.f();
455
380
  }
456
- } else if (importExportDeclaration.test(node.type)) isEsModule = true;
381
+ }
382
+ } else if (node.type === 'ExportAllDeclaration') {
383
+ isEsModule = true;
384
+ if (node.exported && node.exported.name === 'default') {
385
+ hasDefaultExport = true;
386
+ } else {
387
+ hasNamedExports = true;
388
+ }
389
+ } else if (node.type === 'ImportDeclaration') {
390
+ isEsModule = true;
457
391
  }
458
- } catch (err) {
459
- _iterator.e(err);
460
- } finally {
461
- _iterator.f();
462
392
  }
463
393
 
464
- return {
465
- isEsModule,
466
- hasDefaultExport: false,
467
- ast
468
- };
394
+ return { isEsModule, hasDefaultExport, hasNamedExports, ast };
469
395
  }
470
396
 
471
397
  function getDefinePropertyCallName(node, targetName) {
472
398
  if (node.type !== 'CallExpression') return;
473
- const _node$callee = node.callee,
474
- object = _node$callee.object,
475
- property = _node$callee.property;
399
+
400
+ const {
401
+ callee: { object, property }
402
+ } = node;
403
+
476
404
  if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
477
- if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
478
- if (node.arguments.length !== 3) return;
479
405
 
480
- const _node$arguments = _slicedToArray(node.arguments, 2),
481
- target = _node$arguments[0],
482
- val = _node$arguments[1];
406
+ if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
483
407
 
484
- if (target.type !== 'Identifier' || target.name !== targetName) return; // eslint-disable-next-line consistent-return
408
+ if (node.arguments.length !== 3) return;
485
409
 
410
+ const [target, val] = node.arguments;
411
+ if (target.type !== 'Identifier' || target.name !== targetName) return;
412
+ // eslint-disable-next-line consistent-return
486
413
  return val.value;
487
414
  }
488
415
 
489
- function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, ignoreGlobal, ignoreRequire, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, astCache) {
416
+ function transformCommonjs(
417
+ parse,
418
+ code,
419
+ id,
420
+ isEsModule,
421
+ ignoreGlobal,
422
+ ignoreRequire,
423
+ sourceMap,
424
+ isDynamicRequireModulesEnabled,
425
+ dynamicRequireModuleSet,
426
+ disableWrap,
427
+ commonDir,
428
+ astCache
429
+ ) {
490
430
  const ast = astCache || tryParse(parse, code, id);
491
- const magicString = new MagicString(code);
492
- const required = {}; // Because objects have no guaranteed ordering, yet we need it,
431
+
432
+ const magicString = new MagicString__default['default'](code);
433
+
434
+ const required = {};
435
+ // Because objects have no guaranteed ordering, yet we need it,
493
436
  // we need to keep track of the order in a array
437
+ const requiredSources = [];
438
+ const dynamicRegisterSources = [];
494
439
 
495
- const sources = [];
496
440
  let uid = 0;
441
+
497
442
  let scope = pluginutils.attachScopes(ast, 'scope');
498
- const uses = {
499
- module: false,
500
- exports: false,
501
- global: false,
502
- require: false
503
- };
443
+ const uses = { module: false, exports: false, global: false, require: false };
444
+
504
445
  let lexicalDepth = 0;
505
446
  let programDepth = 0;
506
- const globals = new Set(); // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
507
447
 
448
+ const globals = new Set();
449
+
450
+ // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
508
451
  const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
509
- const namedExports = {}; // TODO handle transpiled modules
510
452
 
453
+ const namedExports = {};
454
+
455
+ // TODO handle transpiled modules
511
456
  let shouldWrap = /__esModule/.test(code);
512
457
  let usesCommonjsHelpers = false;
513
458
 
514
459
  function isRequireStatement(node) {
515
460
  if (!node) return false;
516
- if (node.type !== 'CallExpression') return false; // Weird case of `require()` or `module.require()` without arguments
461
+ if (node.type !== 'CallExpression') return false;
517
462
 
463
+ // Weird case of `require()` or `module.require()` without arguments
518
464
  if (node.arguments.length === 0) return false;
465
+
519
466
  return isRequireIdentifier(node.callee);
520
467
  }
521
468
 
522
469
  function isRequireIdentifier(node) {
523
470
  if (!node) return false;
524
471
 
525
- if (node.type === 'Identifier' && node.name === 'require'
526
- /* `require` */
527
- ) {
528
- // `require` is hidden by a variable in local scope
529
- if (scope.contains('require')) return false;
530
- return true;
531
- } else if (node.type === 'MemberExpression'
532
- /* `[something].[something]` */
533
- ) {
534
- // `module.[something]`
535
- if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false; // `module` is hidden by a variable in local scope
472
+ if (node.type === 'Identifier' && node.name === 'require' /* `require` */) {
473
+ // `require` is hidden by a variable in local scope
474
+ if (scope.contains('require')) return false;
536
475
 
537
- if (scope.contains('module')) return false; // `module.require(...)`
476
+ return true;
477
+ } else if (node.type === 'MemberExpression' /* `[something].[something]` */) {
478
+ // `module.[something]`
479
+ if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false;
538
480
 
539
- if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
540
- return true;
541
- }
481
+ // `module` is hidden by a variable in local scope
482
+ if (scope.contains('module')) return false;
483
+
484
+ // `module.require(...)`
485
+ if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
486
+
487
+ return true;
488
+ }
542
489
 
543
490
  return false;
544
491
  }
545
492
 
546
493
  function hasDynamicArguments(node) {
547
- return node.arguments.length > 1 || node.arguments[0].type !== 'Literal' && (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0);
494
+ return (
495
+ node.arguments.length > 1 ||
496
+ (node.arguments[0].type !== 'Literal' &&
497
+ (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
498
+ );
548
499
  }
549
500
 
550
501
  function isStaticRequireStatement(node) {
551
502
  if (!isRequireStatement(node)) return false;
552
- if (hasDynamicArguments(node)) return false;
553
- return true;
503
+ return !hasDynamicArguments(node);
504
+ }
505
+
506
+ function isNodeRequireStatement(parent) {
507
+ const reservedMethod = ['resolve', 'cache', 'main'];
508
+ return !!(parent && parent.property && reservedMethod.indexOf(parent.property.name) > -1);
554
509
  }
555
510
 
556
511
  function isIgnoredRequireStatement(requiredNode) {
@@ -558,20 +513,20 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
558
513
  }
559
514
 
560
515
  function getRequireStringArg(node) {
561
- return node.arguments[0].type === 'Literal' ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked;
516
+ return node.arguments[0].type === 'Literal'
517
+ ? node.arguments[0].value
518
+ : node.arguments[0].quasis[0].value.cooked;
562
519
  }
563
520
 
564
521
  function getRequired(node, name) {
565
522
  let sourceId = getRequireStringArg(node);
566
523
  const isDynamicRegister = sourceId.startsWith(DYNAMIC_REGISTER_PREFIX);
567
-
568
524
  if (isDynamicRegister) {
569
525
  sourceId = sourceId.substr(DYNAMIC_REGISTER_PREFIX.length);
570
526
  }
571
527
 
572
- const existing = required[sourceId]; // eslint-disable-next-line no-undefined
573
-
574
- if (existing === undefined) {
528
+ const existing = required[sourceId];
529
+ if (!existing) {
575
530
  const isDynamic = hasDynamicModuleForPath(sourceId);
576
531
 
577
532
  if (!name) {
@@ -581,32 +536,29 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
581
536
  } while (scope.contains(name));
582
537
  }
583
538
 
584
- if (isDynamicRegister && sourceId.endsWith('.json')) {
585
- sourceId = DYNAMIC_JSON_PREFIX + sourceId;
539
+ if (isDynamicRegister) {
540
+ if (sourceId.endsWith('.json')) {
541
+ sourceId = DYNAMIC_JSON_PREFIX + sourceId;
542
+ }
543
+ dynamicRegisterSources.push(sourceId);
586
544
  }
587
545
 
588
- if (isDynamicRegister || !isDynamic || sourceId.endsWith('.json')) {
589
- sources.push([sourceId, !isDynamicRegister]);
546
+ if (!isDynamic || sourceId.endsWith('.json')) {
547
+ requiredSources.push(sourceId);
590
548
  }
591
549
 
592
- required[sourceId] = {
593
- source: sourceId,
594
- name,
595
- importsDefault: false,
596
- isDynamic
597
- };
550
+ required[sourceId] = { source: sourceId, name, importsDefault: false, isDynamic };
598
551
  }
599
552
 
600
553
  return required[sourceId];
601
554
  }
602
555
 
603
556
  function hasDynamicModuleForPath(source) {
604
- if (!/[/\\]/.test(source)) {
557
+ if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
605
558
  try {
606
- const resolvedPath = normalizePathSlashes(resolve.sync(source, {
607
- basedir: path.dirname(id)
608
- }));
609
-
559
+ const resolvedPath = normalizePathSlashes(
560
+ resolve.sync(source, { basedir: path.dirname(id) })
561
+ );
610
562
  if (dynamicRequireModuleSet.has(resolvedPath)) {
611
563
  return true;
612
564
  }
@@ -618,10 +570,8 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
618
570
  return false;
619
571
  }
620
572
 
621
- for (var _i = 0, _arr = ['', '.js', '.json']; _i < _arr.length; _i++) {
622
- const attemptExt = _arr[_i];
573
+ for (const attemptExt of ['', '.js', '.json']) {
623
574
  const resolvedPath = normalizePathSlashes(path.resolve(path.dirname(id), source + attemptExt));
624
-
625
575
  if (dynamicRequireModuleSet.has(resolvedPath)) {
626
576
  return true;
627
577
  }
@@ -631,38 +581,41 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
631
581
  }
632
582
 
633
583
  function shouldUseSimulatedRequire(required) {
634
- return hasDynamicModuleForPath(required.source) && ( // We only do `commonjsRequire` for json if it's the `commonjsRegister` call.
635
- required.source.startsWith(DYNAMIC_REGISTER_PREFIX) || !required.source.endsWith('.json'));
636
- } // do a first pass, see which names are assigned to. This is necessary to prevent
584
+ return (
585
+ hasDynamicModuleForPath(required.source) &&
586
+ // We only do `commonjsRequire` for json if it's the `commonjsRegister` call.
587
+ (required.source.startsWith(DYNAMIC_REGISTER_PREFIX) || !required.source.endsWith('.json'))
588
+ );
589
+ }
590
+
591
+ // do a first pass, see which names are assigned to. This is necessary to prevent
637
592
  // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
638
593
  // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
639
-
640
-
641
594
  const assignedTo = new Set();
642
595
  estreeWalker.walk(ast, {
643
596
  enter(node) {
644
597
  if (node.type !== 'AssignmentExpression') return;
645
598
  if (node.left.type === 'MemberExpression') return;
646
- pluginutils.extractAssignedNames(node.left).forEach(name => {
599
+
600
+ pluginutils.extractAssignedNames(node.left).forEach((name) => {
647
601
  assignedTo.add(name);
648
602
  });
649
603
  }
650
-
651
604
  });
605
+
652
606
  estreeWalker.walk(ast, {
653
607
  enter(node, parent) {
654
608
  if (sourceMap) {
655
609
  magicString.addSourcemapLocation(node.start);
656
610
  magicString.addSourcemapLocation(node.end);
657
- } // skip dead branches
658
-
611
+ }
659
612
 
613
+ // skip dead branches
660
614
  if (parent && (parent.type === 'IfStatement' || parent.type === 'ConditionalExpression')) {
661
615
  if (node === parent.consequent && isFalsy(parent.test)) {
662
616
  this.skip();
663
617
  return;
664
618
  }
665
-
666
619
  if (node === parent.alternate && isTruthy(parent.test)) {
667
620
  this.skip();
668
621
  return;
@@ -676,57 +629,68 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
676
629
 
677
630
  programDepth += 1;
678
631
 
679
- if (node.scope) {
680
- scope = node.scope;
681
- }
682
-
683
- if (functionType.test(node.type)) lexicalDepth += 1; // if toplevel return, we need to wrap it
632
+ if (node.scope) ({ scope } = node);
633
+ if (functionType.test(node.type)) lexicalDepth += 1;
684
634
 
635
+ // if toplevel return, we need to wrap it
685
636
  if (node.type === 'ReturnStatement' && lexicalDepth === 0) {
686
637
  shouldWrap = true;
687
- } // rewrite `this` as `commonjsHelpers.commonjsGlobal`
688
-
638
+ }
689
639
 
640
+ // rewrite `this` as `commonjsHelpers.commonjsGlobal`
690
641
  if (node.type === 'ThisExpression' && lexicalDepth === 0) {
691
642
  uses.global = true;
692
-
693
643
  if (!ignoreGlobal) {
694
644
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
695
645
  storeName: true
696
646
  });
697
647
  usesCommonjsHelpers = true;
698
648
  }
699
-
700
649
  return;
701
- } // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
702
-
650
+ }
703
651
 
652
+ // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
704
653
  if (node.type === 'UnaryExpression' && node.operator === 'typeof') {
705
654
  const flattened = flatten(node.argument);
706
655
  if (!flattened) return;
656
+
707
657
  if (scope.contains(flattened.name)) return;
708
658
 
709
- if (flattened.keypath === 'module.exports' || flattened.keypath === 'module' || flattened.keypath === 'exports') {
710
- magicString.overwrite(node.start, node.end, `'object'`, {
711
- storeName: false
712
- });
659
+ if (
660
+ flattened.keypath === 'module.exports' ||
661
+ flattened.keypath === 'module' ||
662
+ flattened.keypath === 'exports'
663
+ ) {
664
+ magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
713
665
  }
714
- } // rewrite `require` (if not already handled) `global` and `define`, and handle free references to
715
- // `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
716
-
666
+ }
717
667
 
668
+ // rewrite `require` (if not already handled) `global` and `define`, and handle free references to
669
+ // `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
718
670
  if (node.type === 'Identifier') {
719
- if (isReference(node, parent) && !scope.contains(node.name)) {
671
+ if (isReference__default['default'](node, parent) && !scope.contains(node.name)) {
720
672
  if (node.name in uses) {
721
673
  if (isRequireIdentifier(node)) {
674
+ if (isNodeRequireStatement(parent)) {
675
+ return;
676
+ }
677
+
722
678
  if (!isDynamicRequireModulesEnabled && isStaticRequireStatement(parent)) {
723
679
  return;
724
680
  }
725
681
 
726
682
  if (isDynamicRequireModulesEnabled && isRequireStatement(parent)) {
727
- magicString.appendLeft(parent.end - 1, `,${JSON.stringify(path.dirname(id) === '.' ? null
728
- /* default behavior */
729
- : getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir))}`);
683
+ magicString.appendLeft(
684
+ parent.end - 1,
685
+ `,${JSON.stringify(
686
+ path.dirname(id) === '.'
687
+ ? null /* default behavior */
688
+ : getVirtualPathForDynamicRequirePath(
689
+ normalizePathSlashes(path.dirname(id)),
690
+ commonDir
691
+ )
692
+ )}`
693
+ );
730
694
  }
731
695
 
732
696
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
@@ -736,51 +700,54 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
736
700
  }
737
701
 
738
702
  uses[node.name] = true;
739
-
740
703
  if (node.name === 'global' && !ignoreGlobal) {
741
704
  magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
742
705
  storeName: true
743
706
  });
744
707
  usesCommonjsHelpers = true;
745
- } // if module or exports are used outside the context of an assignment
746
- // expression, we need to wrap the module
747
-
708
+ }
748
709
 
710
+ // if module or exports are used outside the context of an assignment
711
+ // expression, we need to wrap the module
749
712
  if (node.name === 'module' || node.name === 'exports') {
750
713
  shouldWrap = true;
751
714
  }
752
715
  }
753
716
 
754
717
  if (node.name === 'define') {
755
- magicString.overwrite(node.start, node.end, 'undefined', {
756
- storeName: true
757
- });
718
+ magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
758
719
  }
759
720
 
760
721
  globals.add(node.name);
761
722
  }
762
723
 
763
724
  return;
764
- } // Is this an assignment to exports or module.exports?
765
-
725
+ }
766
726
 
727
+ // Is this an assignment to exports or module.exports?
767
728
  if (node.type === 'AssignmentExpression') {
768
729
  if (node.left.type !== 'MemberExpression') return;
730
+
769
731
  const flattened = flatten(node.left);
770
732
  if (!flattened) return;
733
+
771
734
  if (scope.contains(flattened.name)) return;
735
+
772
736
  const match = exportsPattern.exec(flattened.keypath);
773
737
  if (!match || flattened.keypath === 'exports') return;
774
- uses[flattened.name] = true; // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
775
- // if this isn't top-level, we'll need to wrap the module
776
738
 
739
+ uses[flattened.name] = true;
740
+
741
+ // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
742
+ // if this isn't top-level, we'll need to wrap the module
777
743
  if (programDepth > 3) shouldWrap = true;
744
+
778
745
  node.left._skip = true;
779
746
 
780
747
  if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
781
- node.right.properties.forEach(prop => {
748
+ node.right.properties.forEach((prop) => {
782
749
  if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
783
- const name = prop.key.name;
750
+ const { name } = prop.key;
784
751
  if (name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
785
752
  });
786
753
  return;
@@ -791,13 +758,21 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
791
758
  }
792
759
 
793
760
  const name = getDefinePropertyCallName(node, 'exports');
794
- if (name && name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true; // if this is `var x = require('x')`, we can do `import x from 'x'`
795
-
796
- if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier' && isStaticRequireStatement(node.init) && !isIgnoredRequireStatement(node.init)) {
761
+ if (name && name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
762
+
763
+ // if this is `var x = require('x')`, we can do `import x from 'x'`
764
+ if (
765
+ node.type === 'VariableDeclarator' &&
766
+ node.id.type === 'Identifier' &&
767
+ isStaticRequireStatement(node.init) &&
768
+ !isIgnoredRequireStatement(node.init)
769
+ ) {
797
770
  // for now, only do this for top-level requires. maybe fix this in future
798
- if (scope.parent) return; // edge case — CJS allows you to assign to imports. ES doesn't
771
+ if (scope.parent) return;
799
772
 
773
+ // edge case — CJS allows you to assign to imports. ES doesn't
800
774
  if (assignedTo.has(node.id.name)) return;
775
+
801
776
  const required = getRequired(node.init, node.id.name);
802
777
  required.importsDefault = true;
803
778
 
@@ -819,9 +794,17 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
819
794
  required.importsDefault = true;
820
795
 
821
796
  if (shouldUseSimulatedRequire(required)) {
822
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(getVirtualPathForDynamicRequirePath(normalizePathSlashes(required.source), commonDir))}, ${JSON.stringify(path.dirname(id) === '.' ? null
823
- /* default behavior */
824
- : getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir))})`);
797
+ magicString.overwrite(
798
+ node.start,
799
+ node.end,
800
+ `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
801
+ getVirtualPathForDynamicRequirePath(normalizePathSlashes(required.source), commonDir)
802
+ )}, ${JSON.stringify(
803
+ path.dirname(id) === '.'
804
+ ? null /* default behavior */
805
+ : getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir)
806
+ )})`
807
+ );
825
808
  usesCommonjsHelpers = true;
826
809
  } else {
827
810
  magicString.overwrite(node.start, node.end, required.name);
@@ -860,36 +843,61 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
860
843
  }
861
844
  }
862
845
  }
863
-
864
846
  });
865
847
 
866
- if (!sources.length && !uses.module && !uses.exports && !uses.require && (ignoreGlobal || !uses.global)) {
867
- // not a CommonJS module
868
- return null;
869
- } // If `isEsModule` is on, it means it has ES6 import/export statements,
848
+ // If `isEsModule` is on, it means it has ES6 import/export statements,
870
849
  // which just can't be wrapped in a function.
850
+ shouldWrap = shouldWrap && !disableWrap && !isEsModule;
871
851
 
872
-
873
- if (isEsModule) shouldWrap = false;
874
852
  usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
875
- const importBlock = `${(usesCommonjsHelpers ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`] : []).concat(sources.map(([source]) => // import the actual module before the proxy, so that we know
876
- // what kind of proxy to build
877
- `import '${source}';`), sources.filter(([, importProxy]) => importProxy).map(([source]) => {
878
- const _required$source = required[source],
879
- name = _required$source.name,
880
- importsDefault = _required$source.importsDefault;
881
- return `import ${importsDefault ? `${name} from ` : ``}'${getProxyId(source)}';`;
882
- })).join('\n')}\n\n`;
853
+
854
+ if (
855
+ !requiredSources.length &&
856
+ !dynamicRegisterSources.length &&
857
+ !uses.module &&
858
+ !uses.exports &&
859
+ !uses.require &&
860
+ !usesCommonjsHelpers &&
861
+ (ignoreGlobal || !uses.global)
862
+ ) {
863
+ return { meta: { commonjs: { isCommonJS: false } } };
864
+ }
865
+
866
+ const importBlock = `${(usesCommonjsHelpers
867
+ ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`]
868
+ : []
869
+ )
870
+ .concat(
871
+ // dynamic registers first, as the may be required in the other modules
872
+ dynamicRegisterSources.map((source) => `import '${source}';`),
873
+
874
+ // now the actual modules so that they are analyzed before creating the proxies;
875
+ // no need to do this for virtual modules as we never proxy them
876
+ requiredSources
877
+ .filter((source) => !source.startsWith('\0'))
878
+ .map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
879
+
880
+ // now the proxy modules
881
+ requiredSources.map((source) => {
882
+ const { name, importsDefault } = required[source];
883
+ return `import ${importsDefault ? `${name} from ` : ``}'${
884
+ source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
885
+ }';`;
886
+ })
887
+ )
888
+ .join('\n')}\n\n`;
889
+
883
890
  const namedExportDeclarations = [];
884
891
  let wrapperStart = '';
885
892
  let wrapperEnd = '';
886
- const moduleName = deconflict(scope, globals, getName(id));
887
893
 
888
- if ((!isEntry || hasImporters) && !isEsModule) {
894
+ const moduleName = deconflict(scope, globals, getName(id));
895
+ if (!isEsModule) {
889
896
  const exportModuleExports = {
890
897
  str: `export { ${moduleName} as __moduleExports };`,
891
898
  name: '__moduleExports'
892
899
  };
900
+
893
901
  namedExportDeclarations.push(exportModuleExports);
894
902
  }
895
903
 
@@ -898,174 +906,264 @@ function transformCommonjs(parse, code, id, isEntry, hasImporters, isEsModule, i
898
906
 
899
907
  if (shouldWrap) {
900
908
  const args = `module${uses.exports ? ', exports' : ''}`;
909
+
901
910
  wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
902
- wrapperEnd = `\n}`;
903
911
 
912
+ wrapperEnd = `\n}`;
904
913
  if (isDynamicRequireModulesEnabled) {
905
- wrapperEnd += `, ${JSON.stringify(getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir))}`;
914
+ wrapperEnd += `, ${JSON.stringify(
915
+ getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir)
916
+ )}`;
906
917
  }
907
918
 
908
919
  wrapperEnd += `);`;
909
920
  } else {
910
921
  const names = [];
911
922
 
912
- var _iterator3 = _createForOfIteratorHelper(ast.body),
913
- _step3;
923
+ for (const node of ast.body) {
924
+ if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
925
+ const { left } = node.expression;
926
+ const flattened = flatten(left);
914
927
 
915
- try {
916
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
917
- const node = _step3.value;
928
+ if (!flattened) {
929
+ continue;
930
+ }
918
931
 
919
- if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
920
- const left = node.expression.left;
921
- const flattened = flatten(left);
932
+ const match = exportsPattern.exec(flattened.keypath);
933
+ if (!match) {
934
+ continue;
935
+ }
922
936
 
923
- if (!flattened) {
924
- continue;
925
- }
937
+ if (flattened.keypath === 'module.exports') {
938
+ hasDefaultExport = true;
939
+ magicString.overwrite(left.start, left.end, `var ${moduleName}`);
940
+ } else {
941
+ const [, name] = match;
942
+ const deconflicted = deconflict(scope, globals, name);
926
943
 
927
- const match = exportsPattern.exec(flattened.keypath);
944
+ names.push({ name, deconflicted });
928
945
 
929
- if (!match) {
930
- continue;
931
- }
946
+ magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
932
947
 
933
- if (flattened.keypath === 'module.exports') {
934
- hasDefaultExport = true;
935
- magicString.overwrite(left.start, left.end, `var ${moduleName}`);
936
- } else {
937
- const _match = _slicedToArray(match, 2),
938
- name = _match[1];
948
+ const declaration =
949
+ name === deconflicted
950
+ ? `export { ${name} };`
951
+ : `export { ${deconflicted} as ${name} };`;
939
952
 
940
- const deconflicted = deconflict(scope, globals, name);
941
- names.push({
942
- name,
943
- deconflicted
953
+ if (name !== 'default') {
954
+ namedExportDeclarations.push({
955
+ str: declaration,
956
+ name
944
957
  });
945
- magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
946
- const declaration = name === deconflicted ? `export { ${name} };` : `export { ${deconflicted} as ${name} };`;
947
-
948
- if (name !== 'default') {
949
- namedExportDeclarations.push({
950
- str: declaration,
951
- name
952
- });
953
- }
954
-
955
- defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
956
958
  }
959
+
960
+ defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
957
961
  }
958
962
  }
959
- } catch (err) {
960
- _iterator3.e(err);
961
- } finally {
962
- _iterator3.f();
963
963
  }
964
964
 
965
- if (!hasDefaultExport && (names.length || (!isEntry || hasImporters) && !isEsModule)) {
966
- wrapperEnd = `\n\nvar ${moduleName} = {\n${names.map(({
967
- name,
968
- deconflicted
969
- }) => `\t${name}: ${deconflicted}`).join(',\n')}\n};`;
965
+ if (!(isEsModule || hasDefaultExport)) {
966
+ wrapperEnd = `\n\nvar ${moduleName} = {\n${names
967
+ .map(({ name, deconflicted }) => `\t${name}: ${deconflicted}`)
968
+ .join(',\n')}\n};`;
970
969
  }
971
970
  }
972
971
 
973
- const defaultExport = /__esModule/.test(code) ? `export default /*@__PURE__*/${HELPERS_NAME}.unwrapExports(${moduleName});` : `export default ${moduleName};`;
974
- const named = namedExportDeclarations.filter(x => x.name !== 'default' || !hasDefaultExport).map(x => x.str);
975
- const exportBlock = `\n\n${(isEsModule ? [] : [defaultExport]).concat(named).concat(hasDefaultExport ? defaultExportPropertyAssignments : []).join('\n')}`;
976
- magicString.trim().prepend(importBlock + wrapperStart).trim().append(wrapperEnd);
977
- const injectExportBlock = hasDefaultExport || named.length > 0 || shouldWrap || !isEntry || hasImporters;
972
+ magicString
973
+ .trim()
974
+ .prepend(importBlock + wrapperStart)
975
+ .trim()
976
+ .append(wrapperEnd);
978
977
 
979
- if (injectExportBlock) {
980
- magicString.append(exportBlock);
981
- }
978
+ const defaultExport =
979
+ code.indexOf('__esModule') >= 0
980
+ ? `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
981
+ : `export default ${moduleName};`;
982
+
983
+ const named = namedExportDeclarations
984
+ .filter((x) => x.name !== 'default' || !hasDefaultExport)
985
+ .map((x) => x.str);
986
+
987
+ magicString.append(
988
+ `\n\n${(isEsModule ? [] : [defaultExport])
989
+ .concat(named)
990
+ .concat(hasDefaultExport ? defaultExportPropertyAssignments : [])
991
+ .join('\n')}`
992
+ );
982
993
 
983
994
  code = magicString.toString();
984
995
  const map = sourceMap ? magicString.generateMap() : null;
996
+
985
997
  return {
986
998
  code,
987
999
  map,
988
- syntheticNamedExports: injectExportBlock
1000
+ syntheticNamedExports: isEsModule ? false : '__moduleExports',
1001
+ meta: { commonjs: { isCommonJS: !isEsModule } }
989
1002
  };
990
1003
  }
991
1004
 
992
- function getDynamicRequirePaths(patterns) {
993
- const dynamicRequireModuleSet = new Set();
1005
+ function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
1006
+ let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
1007
+ for (const dir of dynamicRequireModuleDirPaths) {
1008
+ let entryPoint = 'index.js';
994
1009
 
995
- var _iterator = _createForOfIteratorHelper(!patterns || Array.isArray(patterns) ? patterns || [] : [patterns]),
996
- _step;
1010
+ try {
1011
+ if (fs.existsSync(path.join(dir, 'package.json'))) {
1012
+ entryPoint =
1013
+ JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), { encoding: 'utf8' })).main ||
1014
+ entryPoint;
1015
+ }
1016
+ } catch (ignored) {
1017
+ // ignored
1018
+ }
997
1019
 
998
- try {
999
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1000
- const pattern = _step.value;
1001
- const isNegated = pattern.startsWith('!');
1002
- const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
1020
+ code += `\ncommonjsRegister(${JSON.stringify(
1021
+ getVirtualPathForDynamicRequirePath(dir, commonDir)
1022
+ )}, function (module, exports) {
1023
+ module.exports = require(${JSON.stringify(normalizePathSlashes(path.join(dir, entryPoint)))});
1024
+ });`;
1025
+ }
1026
+ return code;
1027
+ }
1003
1028
 
1004
- var _iterator2 = _createForOfIteratorHelper(glob.sync(isNegated ? pattern.substr(1) : pattern)),
1005
- _step2;
1029
+ function getDynamicPackagesEntryIntro(
1030
+ dynamicRequireModuleDirPaths,
1031
+ dynamicRequireModuleSet
1032
+ ) {
1033
+ let dynamicImports = Array.from(
1034
+ dynamicRequireModuleSet,
1035
+ (dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
1036
+ ).join('\n');
1006
1037
 
1007
- try {
1008
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1009
- const path$1 = _step2.value;
1010
- modifySet(normalizePathSlashes(path.resolve(path$1)));
1011
- }
1012
- } catch (err) {
1013
- _iterator2.e(err);
1014
- } finally {
1015
- _iterator2.f();
1016
- }
1017
- }
1018
- } catch (err) {
1019
- _iterator.e(err);
1020
- } finally {
1021
- _iterator.f();
1038
+ if (dynamicRequireModuleDirPaths.length) {
1039
+ dynamicImports += `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID)});`;
1022
1040
  }
1023
1041
 
1024
- const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter(path => {
1025
- try {
1026
- if (fs.statSync(path).isDirectory()) return true;
1027
- } catch (ignored) {// Nothing to do here
1028
- }
1042
+ return dynamicImports;
1043
+ }
1029
1044
 
1030
- return false;
1031
- });
1032
- return {
1033
- dynamicRequireModuleSet,
1034
- dynamicRequireModuleDirPaths
1035
- };
1045
+ function isModuleRegistrationProxy(id, dynamicRequireModuleSet) {
1046
+ const normalizedPath = normalizePathSlashes(id);
1047
+ return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
1048
+ }
1049
+
1050
+ function getDynamicRequirePaths(patterns) {
1051
+ const dynamicRequireModuleSet = new Set();
1052
+ for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
1053
+ const isNegated = pattern.startsWith('!');
1054
+ const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
1055
+ for (const path$1 of glob__default['default'].sync(isNegated ? pattern.substr(1) : pattern)) {
1056
+ modifySet(normalizePathSlashes(path.resolve(path$1)));
1057
+ }
1058
+ }
1059
+ const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter(
1060
+ (path) => {
1061
+ try {
1062
+ if (fs.statSync(path).isDirectory()) return true;
1063
+ } catch (ignored) {
1064
+ // Nothing to do here
1065
+ }
1066
+ return false;
1067
+ }
1068
+ );
1069
+ return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
1036
1070
  }
1037
1071
 
1038
- /* eslint-disable no-undefined */
1039
1072
  const isCjsPromises = new Map();
1073
+
1040
1074
  function getIsCjsPromise(id) {
1041
1075
  let isCjsPromise = isCjsPromises.get(id);
1042
1076
  if (isCjsPromise) return isCjsPromise.promise;
1043
- const promise = new Promise(resolve => {
1077
+
1078
+ const promise = new Promise((resolve) => {
1044
1079
  isCjsPromise = {
1045
1080
  resolve,
1046
- promise: undefined
1081
+ promise: null
1047
1082
  };
1048
1083
  isCjsPromises.set(id, isCjsPromise);
1049
1084
  });
1050
1085
  isCjsPromise.promise = promise;
1086
+
1051
1087
  return promise;
1052
1088
  }
1089
+
1053
1090
  function setIsCjsPromise(id, resolution) {
1054
1091
  const isCjsPromise = isCjsPromises.get(id);
1055
-
1056
1092
  if (isCjsPromise) {
1057
1093
  if (isCjsPromise.resolve) {
1058
1094
  isCjsPromise.resolve(resolution);
1059
- isCjsPromise.resolve = undefined;
1095
+ isCjsPromise.resolve = null;
1060
1096
  }
1061
1097
  } else {
1062
- isCjsPromises.set(id, {
1063
- promise: Promise.resolve(resolution),
1064
- resolve: undefined
1065
- });
1098
+ isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: null });
1066
1099
  }
1067
1100
  }
1068
1101
 
1102
+ // e.g. id === "commonjsHelpers?commonjsRegister"
1103
+ function getSpecificHelperProxy(id) {
1104
+ return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
1105
+ }
1106
+
1107
+ function getUnknownRequireProxy(id, requireReturnsDefault) {
1108
+ if (requireReturnsDefault === true || id.endsWith('.json')) {
1109
+ return `export {default} from ${JSON.stringify(id)};`;
1110
+ }
1111
+ const name = getName(id);
1112
+ const exported =
1113
+ requireReturnsDefault === 'auto'
1114
+ ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
1115
+ : requireReturnsDefault === 'preferred'
1116
+ ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
1117
+ : !requireReturnsDefault
1118
+ ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
1119
+ : `export default ${name};`;
1120
+ return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
1121
+ }
1122
+
1123
+ function getDynamicJsonProxy(id, commonDir) {
1124
+ const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
1125
+ return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
1126
+ getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
1127
+ )}, function (module, exports) {
1128
+ module.exports = require(${JSON.stringify(normalizedPath)});
1129
+ });`;
1130
+ }
1131
+
1132
+ function getDynamicRequireProxy(normalizedPath, commonDir) {
1133
+ return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
1134
+ getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
1135
+ )}, function (module, exports) {
1136
+ ${fs.readFileSync(normalizedPath, { encoding: 'utf8' })}
1137
+ });`;
1138
+ }
1139
+
1140
+ async function getStaticRequireProxy(
1141
+ id,
1142
+ requireReturnsDefault,
1143
+ esModulesWithDefaultExport,
1144
+ esModulesWithNamedExports
1145
+ ) {
1146
+ const name = getName(id);
1147
+ const isCjs = await getIsCjsPromise(id);
1148
+ if (isCjs) {
1149
+ return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
1150
+ } else if (isCjs === null) {
1151
+ return getUnknownRequireProxy(id, requireReturnsDefault);
1152
+ } else if (!requireReturnsDefault) {
1153
+ return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
1154
+ id
1155
+ )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
1156
+ } else if (
1157
+ requireReturnsDefault !== true &&
1158
+ (requireReturnsDefault === 'namespace' ||
1159
+ !esModulesWithDefaultExport.has(id) ||
1160
+ (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
1161
+ ) {
1162
+ return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
1163
+ }
1164
+ return `export {default} from ${JSON.stringify(id)};`;
1165
+ }
1166
+
1069
1167
  /* eslint-disable no-param-reassign, no-undefined */
1070
1168
 
1071
1169
  function getCandidatesForExtension(resolved, extension) {
@@ -1073,22 +1171,24 @@ function getCandidatesForExtension(resolved, extension) {
1073
1171
  }
1074
1172
 
1075
1173
  function getCandidates(resolved, extensions) {
1076
- return extensions.reduce((paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), [resolved]);
1174
+ return extensions.reduce(
1175
+ (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
1176
+ [resolved]
1177
+ );
1077
1178
  }
1078
1179
 
1079
1180
  function getResolveId(extensions) {
1080
1181
  function resolveExtensions(importee, importer) {
1081
1182
  // not our problem
1082
1183
  if (importee[0] !== '.' || !importer) return undefined;
1184
+
1083
1185
  const resolved = path.resolve(path.dirname(importer), importee);
1084
1186
  const candidates = getCandidates(resolved, extensions);
1085
1187
 
1086
1188
  for (let i = 0; i < candidates.length; i += 1) {
1087
1189
  try {
1088
1190
  const stats = fs.statSync(candidates[i]);
1089
- if (stats.isFile()) return {
1090
- id: candidates[i]
1091
- };
1191
+ if (stats.isFile()) return { id: candidates[i] };
1092
1192
  } catch (err) {
1093
1193
  /* noop */
1094
1194
  }
@@ -1097,103 +1197,132 @@ function getResolveId(extensions) {
1097
1197
  return undefined;
1098
1198
  }
1099
1199
 
1100
- function resolveId(importee, importer) {
1101
- const isProxyModule = importee.endsWith(PROXY_SUFFIX);
1200
+ return function resolveId(importee, importer) {
1201
+ // Proxies are only importing resolved ids, no need to resolve again
1202
+ if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
1203
+ return importee;
1204
+ }
1102
1205
 
1206
+ const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
1207
+ const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
1103
1208
  if (isProxyModule) {
1104
- importee = getIdFromProxyId(importee);
1105
- } else if (importee.startsWith('\0')) {
1106
- if (importee === HELPERS_ID || importee === DYNAMIC_PACKAGES_ID || importee.startsWith(DYNAMIC_JSON_PREFIX)) {
1209
+ importee = unwrapId(importee, PROXY_SUFFIX);
1210
+ } else if (isRequiredModule) {
1211
+ importee = unwrapId(importee, REQUIRE_SUFFIX);
1212
+ }
1213
+ if (importee.startsWith('\0')) {
1214
+ if (
1215
+ importee.startsWith(HELPERS_ID) ||
1216
+ importee === DYNAMIC_PACKAGES_ID ||
1217
+ importee.startsWith(DYNAMIC_JSON_PREFIX)
1218
+ ) {
1107
1219
  return importee;
1108
1220
  }
1109
-
1110
1221
  return null;
1111
1222
  }
1112
1223
 
1113
- if (importee.startsWith(DYNAMIC_JSON_PREFIX)) {
1114
- return importee;
1115
- }
1116
-
1117
- if (importer && importer.endsWith(PROXY_SUFFIX)) {
1118
- importer = getIdFromProxyId(importer);
1119
- }
1120
-
1121
1224
  return this.resolve(importee, importer, {
1122
- skipSelf: true
1123
- }).then(resolved => {
1225
+ skipSelf: true,
1226
+ custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
1227
+ }).then((resolved) => {
1124
1228
  if (!resolved) {
1125
1229
  resolved = resolveExtensions(importee, importer);
1126
1230
  }
1127
-
1128
- if (isProxyModule) {
1129
- if (!resolved) {
1130
- return {
1131
- id: getExternalProxyId(importee),
1132
- external: false
1133
- };
1134
- }
1135
-
1136
- resolved.id = (resolved.external ? getExternalProxyId : getProxyId)(resolved.id);
1231
+ if (resolved && isProxyModule) {
1232
+ resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
1137
1233
  resolved.external = false;
1138
- return resolved;
1234
+ } else if (!resolved && (isProxyModule || isRequiredModule)) {
1235
+ return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
1139
1236
  }
1140
-
1141
1237
  return resolved;
1142
1238
  });
1143
- }
1144
-
1145
- return resolveId;
1239
+ };
1146
1240
  }
1147
1241
 
1148
1242
  function commonjs(options = {}) {
1149
1243
  const extensions = options.extensions || ['.js'];
1150
1244
  const filter = pluginutils.createFilter(options.include, options.exclude);
1151
- const ignoreGlobal = options.ignoreGlobal;
1152
-
1153
- const _getDynamicRequirePat = getDynamicRequirePaths(options.dynamicRequireTargets),
1154
- dynamicRequireModuleSet = _getDynamicRequirePat.dynamicRequireModuleSet,
1155
- dynamicRequireModuleDirPaths = _getDynamicRequirePat.dynamicRequireModuleDirPaths;
1156
-
1245
+ const {
1246
+ ignoreGlobal,
1247
+ requireReturnsDefault: requireReturnsDefaultOption,
1248
+ esmExternals
1249
+ } = options;
1250
+ const getRequireReturnsDefault =
1251
+ typeof requireReturnsDefaultOption === 'function'
1252
+ ? requireReturnsDefaultOption
1253
+ : () => requireReturnsDefaultOption;
1254
+ let esmExternalIds;
1255
+ const isEsmExternal =
1256
+ typeof esmExternals === 'function'
1257
+ ? esmExternals
1258
+ : Array.isArray(esmExternals)
1259
+ ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1260
+ : () => esmExternals;
1261
+
1262
+ const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1263
+ options.dynamicRequireTargets
1264
+ );
1157
1265
  const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
1158
- const commonDir = isDynamicRequireModulesEnabled ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd())) : null;
1159
- const esModulesWithoutDefaultExport = new Set();
1266
+ const commonDir = isDynamicRequireModulesEnabled
1267
+ ? getCommonDir__default['default'](null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1268
+ : null;
1269
+
1160
1270
  const esModulesWithDefaultExport = new Set();
1161
- const ignoreRequire = typeof options.ignore === 'function' ? options.ignore : Array.isArray(options.ignore) ? id => options.ignore.includes(id) : () => false;
1162
- const resolveId = getResolveId(extensions);
1163
- const sourceMap = options.sourceMap !== false;
1271
+ const esModulesWithNamedExports = new Set();
1164
1272
 
1165
- function transformAndCheckExports(code, id) {
1166
- const _checkEsModule = checkEsModule(this.parse, code, id),
1167
- isEsModule = _checkEsModule.isEsModule,
1168
- hasDefaultExport = _checkEsModule.hasDefaultExport,
1169
- ast = _checkEsModule.ast;
1273
+ const ignoreRequire =
1274
+ typeof options.ignore === 'function'
1275
+ ? options.ignore
1276
+ : Array.isArray(options.ignore)
1277
+ ? (id) => options.ignore.includes(id)
1278
+ : () => false;
1170
1279
 
1171
- const isDynamicRequireModule = dynamicRequireModuleSet.has(normalizePathSlashes(id));
1280
+ const resolveId = getResolveId(extensions);
1172
1281
 
1173
- if (isEsModule && (!isDynamicRequireModule || !options.transformMixedEsModules)) {
1174
- (hasDefaultExport ? esModulesWithDefaultExport : esModulesWithoutDefaultExport).add(id);
1282
+ const sourceMap = options.sourceMap !== false;
1175
1283
 
1176
- if (!options.transformMixedEsModules) {
1177
- setIsCjsPromise(id, false);
1178
- return null;
1179
- }
1180
- } // it is not an ES module AND it does not have CJS-specific elements.
1181
- else if (!hasCjsKeywords(code, ignoreGlobal)) {
1182
- esModulesWithoutDefaultExport.add(id);
1183
- setIsCjsPromise(id, false);
1184
- return null;
1185
- }
1284
+ function transformAndCheckExports(code, id) {
1285
+ if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1286
+ code =
1287
+ getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1288
+ }
1186
1289
 
1187
- const moduleInfo = this.getModuleInfo(id);
1188
- const transformed = transformCommonjs(this.parse, code, id, moduleInfo.isEntry, moduleInfo.importers && moduleInfo.importers.length > 0, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, ast);
1189
- setIsCjsPromise(id, isEsModule ? false : Boolean(transformed));
1290
+ const { isEsModule, hasDefaultExport, hasNamedExports, ast } = checkEsModule(
1291
+ this.parse,
1292
+ code,
1293
+ id
1294
+ );
1295
+ if (hasDefaultExport) {
1296
+ esModulesWithDefaultExport.add(id);
1297
+ }
1298
+ if (hasNamedExports) {
1299
+ esModulesWithNamedExports.add(id);
1300
+ }
1190
1301
 
1191
- if (!transformed) {
1192
- if (!isEsModule || isDynamicRequireModule) esModulesWithoutDefaultExport.add(id);
1193
- return null;
1302
+ if (
1303
+ !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1304
+ (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1305
+ ) {
1306
+ return { meta: { commonjs: { isCommonJS: false } } };
1194
1307
  }
1195
1308
 
1196
- return transformed;
1309
+ // avoid wrapping in createCommonjsModule, as this is a commonjsRegister call
1310
+ const disableWrap = isModuleRegistrationProxy(id, dynamicRequireModuleSet);
1311
+
1312
+ return transformCommonjs(
1313
+ this.parse,
1314
+ code,
1315
+ id,
1316
+ isEsModule,
1317
+ ignoreGlobal || isEsModule,
1318
+ ignoreRequire,
1319
+ sourceMap,
1320
+ isDynamicRequireModulesEnabled,
1321
+ dynamicRequireModuleSet,
1322
+ disableWrap,
1323
+ commonDir,
1324
+ ast
1325
+ );
1197
1326
  }
1198
1327
 
1199
1328
  return {
@@ -1201,23 +1330,18 @@ function commonjs(options = {}) {
1201
1330
 
1202
1331
  buildStart() {
1203
1332
  if (options.namedExports != null) {
1204
- this.warn('The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.');
1333
+ this.warn(
1334
+ 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1335
+ );
1205
1336
  }
1206
1337
 
1207
- const _this$meta$rollupVers = this.meta.rollupVersion.split('.').map(Number),
1208
- _this$meta$rollupVers2 = _slicedToArray(_this$meta$rollupVers, 2),
1209
- major = _this$meta$rollupVers2[0],
1210
- minor = _this$meta$rollupVers2[1];
1211
-
1338
+ const [major, minor] = this.meta.rollupVersion.split('.').map(Number);
1212
1339
  const minVersion = peerDependencies.rollup.slice(2);
1213
-
1214
- const _minVersion$split$map = minVersion.split('.').map(Number),
1215
- _minVersion$split$map2 = _slicedToArray(_minVersion$split$map, 2),
1216
- minMajor = _minVersion$split$map2[0],
1217
- minMinor = _minVersion$split$map2[1];
1218
-
1219
- if (major < minMajor || major === minMajor && minor < minMinor) {
1220
- this.error(`Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minVersion} but found rollup@${this.meta.rollupVersion}.`);
1340
+ const [minMajor, minMinor] = minVersion.split('.').map(Number);
1341
+ if (major < minMajor || (major === minMajor && minor < minMinor)) {
1342
+ this.error(
1343
+ `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minVersion} but found rollup@${this.meta.rollupVersion}.`
1344
+ );
1221
1345
  }
1222
1346
  },
1223
1347
 
@@ -1225,136 +1349,74 @@ function commonjs(options = {}) {
1225
1349
 
1226
1350
  load(id) {
1227
1351
  if (id === HELPERS_ID) {
1228
- let code = HELPERS; // Do not bloat everyone's code with the module manager code
1229
-
1230
- if (isDynamicRequireModulesEnabled) code += HELPERS_DYNAMIC;else code += HELPER_NON_DYNAMIC;
1231
- return code;
1232
- } // generate proxy modules
1233
-
1234
-
1235
- if (id.endsWith(EXTERNAL_SUFFIX)) {
1236
- const actualId = getIdFromExternalProxyId(id);
1237
- const name = getName(actualId);
1238
- if (actualId === HELPERS_ID || actualId === DYNAMIC_PACKAGES_ID) // These do not export default
1239
- return `import * as ${name} from ${JSON.stringify(actualId)}; export default ${name};`;
1240
- return `import ${name} from ${JSON.stringify(actualId)}; export default ${name};`;
1352
+ return getHelpersModule(isDynamicRequireModulesEnabled);
1241
1353
  }
1242
1354
 
1243
- if (id === DYNAMIC_PACKAGES_ID) {
1244
- let code = `const { commonjsRegister } = require('${HELPERS_ID}');`;
1245
-
1246
- var _iterator = _createForOfIteratorHelper(dynamicRequireModuleDirPaths),
1247
- _step;
1248
-
1249
- try {
1250
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1251
- const dir = _step.value;
1252
- let entryPoint = 'index.js';
1253
-
1254
- try {
1255
- if (fs.existsSync(path.join(dir, 'package.json'))) {
1256
- entryPoint = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), {
1257
- encoding: 'utf8'
1258
- })).main || entryPoint;
1259
- }
1260
- } catch (ignored) {// ignored
1261
- }
1262
-
1263
- code += `\ncommonjsRegister(${JSON.stringify(getVirtualPathForDynamicRequirePath(dir, commonDir))}, function (module, exports) {
1264
- module.exports = require(${JSON.stringify(normalizePathSlashes(path.join(dir, entryPoint)))});
1265
- });`;
1266
- }
1267
- } catch (err) {
1268
- _iterator.e(err);
1269
- } finally {
1270
- _iterator.f();
1271
- }
1272
-
1273
- return code;
1355
+ if (id.startsWith(HELPERS_ID)) {
1356
+ return getSpecificHelperProxy(id);
1274
1357
  }
1275
1358
 
1276
- let actualId = id;
1277
- const isDynamicJson = actualId.startsWith(DYNAMIC_JSON_PREFIX);
1278
-
1279
- if (isDynamicJson) {
1280
- actualId = actualId.slice(DYNAMIC_JSON_PREFIX.length);
1359
+ if (isWrappedId(id, EXTERNAL_SUFFIX)) {
1360
+ const actualId = unwrapId(id, EXTERNAL_SUFFIX);
1361
+ return getUnknownRequireProxy(
1362
+ actualId,
1363
+ isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
1364
+ );
1281
1365
  }
1282
1366
 
1283
- const normalizedPath = normalizePathSlashes(actualId);
1284
-
1285
- if (isDynamicJson) {
1286
- return `require('${HELPERS_ID}').commonjsRegister(${JSON.stringify(getVirtualPathForDynamicRequirePath(normalizedPath, commonDir))}, function (module, exports) {
1287
- module.exports = require(${JSON.stringify(normalizedPath)});
1288
- });`;
1367
+ if (id === DYNAMIC_PACKAGES_ID) {
1368
+ return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
1289
1369
  }
1290
1370
 
1291
- if (dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json')) {
1292
- // Try our best to still export the module fully.
1293
- // The commonjs polyfill should take care of circular references.
1294
- return `require('${HELPERS_ID}').commonjsRegister(${JSON.stringify(getVirtualPathForDynamicRequirePath(normalizedPath, commonDir))}, function (module, exports) {
1295
- ${fs.readFileSync(normalizedPath, {
1296
- encoding: 'utf8'
1297
- })}
1298
- });`;
1371
+ if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
1372
+ return getDynamicJsonProxy(id, commonDir);
1299
1373
  }
1300
1374
 
1301
- if (actualId.endsWith(PROXY_SUFFIX)) {
1302
- actualId = getIdFromProxyId(actualId);
1303
- const name = getName(actualId);
1304
- return getIsCjsPromise(actualId).then(isCjs => {
1305
- if (dynamicRequireModuleSet.has(normalizePathSlashes(actualId)) && !actualId.endsWith('.json')) return `import {commonjsRequire} from '${HELPERS_ID}'; const ${name} = commonjsRequire(${JSON.stringify(getVirtualPathForDynamicRequirePath(normalizePathSlashes(actualId), commonDir))}); export default (${name} && ${name}['default']) || ${name}`;else if (isCjs) return `import { __moduleExports } from ${JSON.stringify(actualId)}; export default __moduleExports;`;else if (esModulesWithoutDefaultExport.has(actualId)) return `import * as ${name} from ${JSON.stringify(actualId)}; export default ${name};`;else if (esModulesWithDefaultExport.has(actualId)) {
1306
- return `export {default} from ${JSON.stringify(actualId)};`;
1307
- }
1308
- return `import * as ${name} from ${JSON.stringify(actualId)}; import {getCjsExportFromNamespace} from "${HELPERS_ID}"; export default getCjsExportFromNamespace(${name})`;
1309
- });
1375
+ if (isModuleRegistrationProxy(id, dynamicRequireModuleSet)) {
1376
+ return getDynamicRequireProxy(normalizePathSlashes(id), commonDir);
1310
1377
  }
1311
1378
 
1312
- if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1313
- let code;
1314
-
1315
- try {
1316
- code = fs.readFileSync(actualId, {
1317
- encoding: 'utf8'
1318
- });
1319
- } catch (ex) {
1320
- this.warn(`Failed to read file ${actualId}, dynamic modules might not work correctly`);
1321
- return null;
1322
- }
1323
-
1324
- let dynamicImports = Array.from(dynamicRequireModuleSet).map(dynamicId => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`).join('\n');
1325
-
1326
- if (dynamicRequireModuleDirPaths.length) {
1327
- dynamicImports += `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID)});`;
1328
- }
1329
-
1330
- code = `${dynamicImports}\n${code}`;
1331
- return code;
1379
+ if (isWrappedId(id, PROXY_SUFFIX)) {
1380
+ const actualId = unwrapId(id, PROXY_SUFFIX);
1381
+ return getStaticRequireProxy(
1382
+ actualId,
1383
+ getRequireReturnsDefault(actualId),
1384
+ esModulesWithDefaultExport,
1385
+ esModulesWithNamedExports
1386
+ );
1332
1387
  }
1333
1388
 
1334
1389
  return null;
1335
1390
  },
1336
1391
 
1337
1392
  transform(code, id) {
1338
- if (id !== DYNAMIC_PACKAGES_ID && !id.startsWith(DYNAMIC_JSON_PREFIX)) {
1339
- if (!filter(id) || extensions.indexOf(path.extname(id)) === -1) {
1340
- setIsCjsPromise(id, null);
1341
- return null;
1342
- }
1393
+ const extName = path.extname(id);
1394
+ if (
1395
+ extName !== '.cjs' &&
1396
+ id !== DYNAMIC_PACKAGES_ID &&
1397
+ !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1398
+ (!filter(id) || !extensions.includes(extName))
1399
+ ) {
1400
+ return null;
1343
1401
  }
1344
1402
 
1345
- let transformed;
1346
-
1347
1403
  try {
1348
- transformed = transformAndCheckExports.call(this, code, id);
1404
+ return transformAndCheckExports.call(this, code, id);
1349
1405
  } catch (err) {
1350
- transformed = null;
1351
- setIsCjsPromise(id, false);
1352
- this.error(err, err.loc);
1406
+ return this.error(err, err.loc);
1353
1407
  }
1408
+ },
1354
1409
 
1355
- return transformed;
1410
+ moduleParsed({ id, meta: { commonjs } }) {
1411
+ if (commonjs) {
1412
+ const isCjs = commonjs.isCommonJS;
1413
+ if (isCjs != null) {
1414
+ setIsCjsPromise(id, isCjs);
1415
+ return;
1416
+ }
1417
+ }
1418
+ setIsCjsPromise(id, null);
1356
1419
  }
1357
-
1358
1420
  };
1359
1421
  }
1360
1422