@rollup/plugin-commonjs 15.0.0 → 17.1.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,36 +1,99 @@
1
1
  'use strict';
2
2
 
3
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
-
5
3
  var path = require('path');
6
4
  var pluginutils = require('@rollup/pluginutils');
7
- var getCommonDir = _interopDefault(require('commondir'));
5
+ var getCommonDir = require('commondir');
8
6
  var fs = require('fs');
7
+ var glob = require('glob');
9
8
  var estreeWalker = require('estree-walker');
10
- var MagicString = _interopDefault(require('magic-string'));
9
+ var MagicString = require('magic-string');
10
+ var isReference = require('is-reference');
11
11
  var resolve = require('resolve');
12
- var isReference = _interopDefault(require('is-reference'));
13
- var glob = _interopDefault(require('glob'));
12
+
13
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
+
15
+ var getCommonDir__default = /*#__PURE__*/_interopDefaultLegacy(getCommonDir);
16
+ var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
17
+ var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
18
+ var isReference__default = /*#__PURE__*/_interopDefaultLegacy(isReference);
14
19
 
15
20
  var peerDependencies = {
16
- rollup: "^2.22.0"
21
+ rollup: "^2.30.0"
17
22
  };
18
23
 
19
- const PROXY_SUFFIX = '?commonjs-proxy';
20
- const getProxyId = (id) => `\0${id}${PROXY_SUFFIX}`;
21
- const getIdFromProxyId = (proxyId) => proxyId.slice(1, -PROXY_SUFFIX.length);
24
+ function tryParse(parse, code, id) {
25
+ try {
26
+ return parse(code, { allowReturnOutsideFunction: true });
27
+ } catch (err) {
28
+ err.message += ` in ${id}`;
29
+ throw err;
30
+ }
31
+ }
22
32
 
23
- const EXTERNAL_SUFFIX = '?commonjs-external';
24
- const getExternalProxyId = (id) => `\0${id}${EXTERNAL_SUFFIX}`;
25
- const getIdFromExternalProxyId = (proxyId) => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
33
+ const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
26
34
 
27
- const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
28
- const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
29
- if (path.startsWith(commonDir)) return VIRTUAL_PATH_BASE + path.slice(commonDir.length);
30
- return path;
31
- };
35
+ const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
36
+
37
+ function hasCjsKeywords(code, ignoreGlobal) {
38
+ const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
39
+ return firstpass.test(code);
40
+ }
41
+
42
+ /* eslint-disable no-underscore-dangle */
43
+
44
+ function analyzeTopLevelStatements(parse, code, id) {
45
+ const ast = tryParse(parse, code, id);
46
+
47
+ let isEsModule = false;
48
+ let hasDefaultExport = false;
49
+ let hasNamedExports = false;
50
+
51
+ for (const node of ast.body) {
52
+ switch (node.type) {
53
+ case 'ExportDefaultDeclaration':
54
+ isEsModule = true;
55
+ hasDefaultExport = true;
56
+ break;
57
+ case 'ExportNamedDeclaration':
58
+ isEsModule = true;
59
+ if (node.declaration) {
60
+ hasNamedExports = true;
61
+ } else {
62
+ for (const specifier of node.specifiers) {
63
+ if (specifier.exported.name === 'default') {
64
+ hasDefaultExport = true;
65
+ } else {
66
+ hasNamedExports = true;
67
+ }
68
+ }
69
+ }
70
+ break;
71
+ case 'ExportAllDeclaration':
72
+ isEsModule = true;
73
+ if (node.exported && node.exported.name === 'default') {
74
+ hasDefaultExport = true;
75
+ } else {
76
+ hasNamedExports = true;
77
+ }
78
+ break;
79
+ case 'ImportDeclaration':
80
+ isEsModule = true;
81
+ break;
82
+ }
83
+ }
84
+
85
+ return { isEsModule, hasDefaultExport, hasNamedExports, ast };
86
+ }
87
+
88
+ const isWrappedId = (id, suffix) => id.endsWith(suffix);
89
+ const wrapId = (id, suffix) => `\0${id}${suffix}`;
90
+ const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
91
+
92
+ const PROXY_SUFFIX = '?commonjs-proxy';
93
+ const REQUIRE_SUFFIX = '?commonjs-require';
94
+ const EXTERNAL_SUFFIX = '?commonjs-external';
32
95
 
33
- const DYNAMIC_REGISTER_PREFIX = '\0commonjs-dynamic-register:';
96
+ const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';
34
97
  const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
35
98
  const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
36
99
 
@@ -41,11 +104,6 @@ const HELPERS_ID = '\0commonjsHelpers.js';
41
104
  // This will no longer be necessary once Rollup switches to ES6 output, likely
42
105
  // in Rollup 3
43
106
 
44
- // The "hasOwnProperty" call in "getDefaultExportFromCjs" is technically not
45
- // needed, but for consumers that use Rollup's old interop pattern, it will fix
46
- // rollup/rollup-plugin-commonjs#224
47
- // We should remove it once Rollup core and this plugin are updated to not use
48
- // this pattern any more
49
107
  const HELPERS = `
50
108
  export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
51
109
 
@@ -53,16 +111,6 @@ export function getDefaultExportFromCjs (x) {
53
111
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
54
112
  }
55
113
 
56
- export function createCommonjsModule(fn, basedir, module) {
57
- return module = {
58
- path: basedir,
59
- exports: {},
60
- require: function (path, base) {
61
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
62
- }
63
- }, fn(module, module.exports), module.exports;
64
- }
65
-
66
114
  export function getDefaultExportFromNamespaceIfPresent (n) {
67
115
  return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
68
116
  }
@@ -70,15 +118,45 @@ export function getDefaultExportFromNamespaceIfPresent (n) {
70
118
  export function getDefaultExportFromNamespaceIfNotNamed (n) {
71
119
  return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
72
120
  }
121
+
122
+ export function getAugmentedNamespace(n) {
123
+ if (n.__esModule) return n;
124
+ var a = Object.defineProperty({}, '__esModule', {value: true});
125
+ Object.keys(n).forEach(function (k) {
126
+ var d = Object.getOwnPropertyDescriptor(n, k);
127
+ Object.defineProperty(a, k, d.get ? d : {
128
+ enumerable: true,
129
+ get: function () {
130
+ return n[k];
131
+ }
132
+ });
133
+ });
134
+ return a;
135
+ }
73
136
  `;
74
137
 
75
138
  const HELPER_NON_DYNAMIC = `
76
- export function commonjsRequire () {
77
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
139
+ export function createCommonjsModule(fn) {
140
+ var module = { exports: {} }
141
+ return fn(module, module.exports), module.exports;
142
+ }
143
+
144
+ export function commonjsRequire (target) {
145
+ throw new Error('Could not dynamically require "' + target + '". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.');
78
146
  }
79
147
  `;
80
148
 
81
149
  const HELPERS_DYNAMIC = `
150
+ export function createCommonjsModule(fn, basedir, module) {
151
+ return module = {
152
+ path: basedir,
153
+ exports: {},
154
+ require: function (path, base) {
155
+ return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
156
+ }
157
+ }, fn(module, module.exports), module.exports;
158
+ }
159
+
82
160
  export function commonjsRegister (path, loader) {
83
161
  DYNAMIC_REQUIRE_LOADERS[path] = loader;
84
162
  }
@@ -165,10 +243,13 @@ function dirname (path) {
165
243
  return '.';
166
244
  }
167
245
 
168
- export function commonjsRequire (path, originalModuleDir) {
246
+ export function commonjsResolveImpl (path, originalModuleDir, testCache) {
169
247
  const shouldTryNodeModules = isPossibleNodeModulesPath(path);
170
248
  path = normalize(path);
171
249
  let relPath;
250
+ if (path[0] === '/') {
251
+ originalModuleDir = '/';
252
+ }
172
253
  while (true) {
173
254
  if (!shouldTryNodeModules) {
174
255
  relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
@@ -177,33 +258,18 @@ export function commonjsRequire (path, originalModuleDir) {
177
258
  } else {
178
259
  relPath = normalize(join('node_modules', path));
179
260
  }
261
+
262
+ if (relPath.endsWith('/..')) {
263
+ break; // Travelled too far up, avoid infinite loop
264
+ }
265
+
180
266
  for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
181
267
  const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
182
- let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
183
- if (cachedModule) return cachedModule.exports;
184
- const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
185
- if (loader) {
186
- DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
187
- id: resolvedPath,
188
- filename: resolvedPath,
189
- path: dirname(resolvedPath),
190
- exports: {},
191
- parent: DEFAULT_PARENT_MODULE,
192
- loaded: false,
193
- children: [],
194
- paths: [],
195
- require: function (path, base) {
196
- return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
197
- }
198
- };
199
- try {
200
- loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
201
- } catch (error) {
202
- delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
203
- throw error;
204
- }
205
- cachedModule.loaded = true;
206
- return cachedModule.exports;
268
+ if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
269
+ return resolvedPath;
270
+ };
271
+ if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
272
+ return resolvedPath;
207
273
  };
208
274
  }
209
275
  if (!shouldTryNodeModules) break;
@@ -211,77 +277,74 @@ export function commonjsRequire (path, originalModuleDir) {
211
277
  if (nextDir === originalModuleDir) break;
212
278
  originalModuleDir = nextDir;
213
279
  }
280
+ return null;
281
+ }
282
+
283
+ export function commonjsResolve (path, originalModuleDir) {
284
+ const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
285
+ if (resolvedPath !== null) {
286
+ return resolvedPath;
287
+ }
288
+ return require.resolve(path);
289
+ }
290
+
291
+ export function commonjsRequire (path, originalModuleDir) {
292
+ const resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
293
+ if (resolvedPath !== null) {
294
+ let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
295
+ if (cachedModule) return cachedModule.exports;
296
+ const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
297
+ if (loader) {
298
+ DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
299
+ id: resolvedPath,
300
+ filename: resolvedPath,
301
+ path: dirname(resolvedPath),
302
+ exports: {},
303
+ parent: DEFAULT_PARENT_MODULE,
304
+ loaded: false,
305
+ children: [],
306
+ paths: [],
307
+ require: function (path, base) {
308
+ return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
309
+ }
310
+ };
311
+ try {
312
+ loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
313
+ } catch (error) {
314
+ delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
315
+ throw error;
316
+ }
317
+ cachedModule.loaded = true;
318
+ return cachedModule.exports;
319
+ };
320
+ }
214
321
  return require(path);
215
322
  }
216
323
 
217
324
  commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
325
+ commonjsRequire.resolve = commonjsResolve;
218
326
  `;
219
327
 
220
328
  function getHelpersModule(isDynamicRequireModulesEnabled) {
221
329
  return `${HELPERS}${isDynamicRequireModulesEnabled ? HELPERS_DYNAMIC : HELPER_NON_DYNAMIC}`;
222
330
  }
223
331
 
224
- /* eslint-disable no-undefined */
225
-
226
- const operators = {
227
- '==': (x) => equals(x.left, x.right, false),
228
-
229
- '!=': (x) => not(operators['=='](x)),
230
-
231
- '===': (x) => equals(x.left, x.right, true),
232
-
233
- '!==': (x) => not(operators['==='](x)),
234
-
235
- '!': (x) => isFalsy(x.argument),
236
-
237
- '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
238
-
239
- '||': (x) => isTruthy(x.left) || isTruthy(x.right)
240
- };
241
-
242
- function flatten(node) {
243
- const parts = [];
332
+ /* eslint-disable import/prefer-default-export */
244
333
 
245
- while (node.type === 'MemberExpression') {
246
- if (node.computed) return null;
334
+ function deconflict(scope, globals, identifier) {
335
+ let i = 1;
336
+ let deconflicted = pluginutils.makeLegalIdentifier(identifier);
247
337
 
248
- parts.unshift(node.property.name);
249
- // eslint-disable-next-line no-param-reassign
250
- node = node.object;
338
+ while (scope.contains(deconflicted) || globals.has(deconflicted)) {
339
+ deconflicted = pluginutils.makeLegalIdentifier(`${identifier}_${i}`);
340
+ i += 1;
251
341
  }
342
+ // eslint-disable-next-line no-param-reassign
343
+ scope.declarations[deconflicted] = true;
252
344
 
253
- if (node.type !== 'Identifier') return null;
254
-
255
- const { name } = node;
256
- parts.unshift(name);
257
-
258
- return { name, keypath: parts.join('.') };
259
- }
260
-
261
- function isTruthy(node) {
262
- if (node.type === 'Literal') return !!node.value;
263
- if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
264
- if (node.operator in operators) return operators[node.operator](node);
265
- return undefined;
266
- }
267
-
268
- function isFalsy(node) {
269
- return not(isTruthy(node));
270
- }
271
-
272
- function not(value) {
273
- return value === undefined ? value : !value;
274
- }
275
-
276
- function equals(a, b, strict) {
277
- if (a.type !== b.type) return undefined;
278
- // eslint-disable-next-line eqeqeq
279
- if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
280
- return undefined;
345
+ return deconflicted;
281
346
  }
282
347
 
283
- /* eslint-disable import/prefer-default-export */
284
-
285
348
  function getName(id) {
286
349
  const name = pluginutils.makeLegalIdentifier(path.basename(id, path.extname(id)));
287
350
  if (name !== 'index') {
@@ -291,918 +354,1219 @@ function getName(id) {
291
354
  return pluginutils.makeLegalIdentifier(segments[segments.length - 1]);
292
355
  }
293
356
 
294
- /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
357
+ function normalizePathSlashes(path) {
358
+ return path.replace(/\\/g, '/');
359
+ }
295
360
 
296
- 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(
297
- ' '
298
- );
299
- const blacklist = { __esModule: true };
300
- reserved.forEach((word) => (blacklist[word] = true));
361
+ const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
362
+ const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
363
+ const normalizedPath = normalizePathSlashes(path);
364
+ return normalizedPath.startsWith(commonDir)
365
+ ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
366
+ : normalizedPath;
367
+ };
301
368
 
302
- const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
369
+ function getPackageEntryPoint(dirPath) {
370
+ let entryPoint = 'index.js';
303
371
 
304
- const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
305
- const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
306
- const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
372
+ try {
373
+ if (fs.existsSync(path.join(dirPath, 'package.json'))) {
374
+ entryPoint =
375
+ JSON.parse(fs.readFileSync(path.join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
376
+ entryPoint;
377
+ }
378
+ } catch (ignored) {
379
+ // ignored
380
+ }
307
381
 
308
- function deconflict(scope, globals, identifier) {
309
- let i = 1;
310
- let deconflicted = pluginutils.makeLegalIdentifier(identifier);
382
+ return entryPoint;
383
+ }
311
384
 
312
- while (scope.contains(deconflicted) || globals.has(deconflicted) || deconflicted in blacklist) {
313
- deconflicted = `${identifier}_${i}`;
314
- i += 1;
315
- }
316
- scope.declarations[deconflicted] = true;
385
+ function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
386
+ let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
387
+ for (const dir of dynamicRequireModuleDirPaths) {
388
+ const entryPoint = getPackageEntryPoint(dir);
317
389
 
318
- return deconflicted;
390
+ code += `\ncommonjsRegister(${JSON.stringify(
391
+ getVirtualPathForDynamicRequirePath(dir, commonDir)
392
+ )}, function (module, exports) {
393
+ module.exports = require(${JSON.stringify(normalizePathSlashes(path.join(dir, entryPoint)))});
394
+ });`;
395
+ }
396
+ return code;
319
397
  }
320
398
 
321
- function tryParse(parse, code, id) {
322
- try {
323
- return parse(code, { allowReturnOutsideFunction: true });
324
- } catch (err) {
325
- err.message += ` in ${id}`;
326
- throw err;
399
+ function getDynamicPackagesEntryIntro(
400
+ dynamicRequireModuleDirPaths,
401
+ dynamicRequireModuleSet
402
+ ) {
403
+ let dynamicImports = Array.from(
404
+ dynamicRequireModuleSet,
405
+ (dynamicId) => `require(${JSON.stringify(wrapModuleRegisterProxy(dynamicId))});`
406
+ ).join('\n');
407
+
408
+ if (dynamicRequireModuleDirPaths.length) {
409
+ dynamicImports += `require(${JSON.stringify(wrapModuleRegisterProxy(DYNAMIC_PACKAGES_ID))});`;
327
410
  }
411
+
412
+ return dynamicImports;
328
413
  }
329
414
 
330
- function normalizePathSlashes(path) {
331
- return path.replace(/\\/g, '/');
415
+ function wrapModuleRegisterProxy(id) {
416
+ return wrapId(id, DYNAMIC_REGISTER_SUFFIX);
332
417
  }
333
418
 
334
- function hasCjsKeywords(code, ignoreGlobal) {
335
- const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
336
- return firstpass.test(code);
419
+ function unwrapModuleRegisterProxy(id) {
420
+ return unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
337
421
  }
338
422
 
339
- function checkEsModule(parse, code, id) {
340
- const ast = tryParse(parse, code, id);
423
+ function isModuleRegisterProxy(id) {
424
+ return isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
425
+ }
341
426
 
342
- let isEsModule = false;
343
- let hasDefaultExport = false;
344
- let hasNamedExports = false;
345
- for (const node of ast.body) {
346
- if (node.type === 'ExportDefaultDeclaration') {
347
- isEsModule = true;
348
- hasDefaultExport = true;
349
- } else if (node.type === 'ExportNamedDeclaration') {
350
- isEsModule = true;
351
- if (node.declaration) {
352
- hasNamedExports = true;
353
- } else {
354
- for (const specifier of node.specifiers) {
355
- if (specifier.exported.name === 'default') {
356
- hasDefaultExport = true;
357
- } else {
358
- hasNamedExports = true;
359
- }
360
- }
361
- }
362
- } else if (node.type === 'ExportAllDeclaration') {
363
- isEsModule = true;
364
- if (node.exported && node.exported.name === 'default') {
365
- hasDefaultExport = true;
366
- } else {
367
- hasNamedExports = true;
427
+ function isDynamicModuleImport(id, dynamicRequireModuleSet) {
428
+ const normalizedPath = normalizePathSlashes(id);
429
+ return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
430
+ }
431
+
432
+ function isDirectory(path) {
433
+ try {
434
+ if (fs.statSync(path).isDirectory()) return true;
435
+ } catch (ignored) {
436
+ // Nothing to do here
437
+ }
438
+ return false;
439
+ }
440
+
441
+ function getDynamicRequirePaths(patterns) {
442
+ const dynamicRequireModuleSet = new Set();
443
+ for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
444
+ const isNegated = pattern.startsWith('!');
445
+ const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
446
+ for (const path$1 of glob__default['default'].sync(isNegated ? pattern.substr(1) : pattern)) {
447
+ modifySet(normalizePathSlashes(path.resolve(path$1)));
448
+ if (isDirectory(path$1)) {
449
+ modifySet(normalizePathSlashes(path.resolve(path.join(path$1, getPackageEntryPoint(path$1)))));
368
450
  }
369
- } else if (node.type === 'ImportDeclaration') {
370
- isEsModule = true;
371
451
  }
372
452
  }
373
-
374
- return { isEsModule, hasDefaultExport, hasNamedExports, ast };
453
+ const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>
454
+ isDirectory(path)
455
+ );
456
+ return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
375
457
  }
376
458
 
377
- function getDefinePropertyCallName(node, targetName) {
378
- if (node.type !== 'CallExpression') return;
459
+ const isCjsPromises = new Map();
379
460
 
380
- const {
381
- callee: { object, property }
382
- } = node;
461
+ function getIsCjsPromise(id) {
462
+ let isCjsPromise = isCjsPromises.get(id);
463
+ if (isCjsPromise) return isCjsPromise.promise;
383
464
 
384
- if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
465
+ const promise = new Promise((resolve) => {
466
+ isCjsPromise = {
467
+ resolve,
468
+ promise: null
469
+ };
470
+ isCjsPromises.set(id, isCjsPromise);
471
+ });
472
+ isCjsPromise.promise = promise;
385
473
 
386
- if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
474
+ return promise;
475
+ }
387
476
 
388
- if (node.arguments.length !== 3) return;
477
+ function setIsCjsPromise(id, resolution) {
478
+ const isCjsPromise = isCjsPromises.get(id);
479
+ if (isCjsPromise) {
480
+ if (isCjsPromise.resolve) {
481
+ isCjsPromise.resolve(resolution);
482
+ isCjsPromise.resolve = null;
483
+ }
484
+ } else {
485
+ isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: null });
486
+ }
487
+ }
389
488
 
390
- const [target, val] = node.arguments;
391
- if (target.type !== 'Identifier' || target.name !== targetName) return;
392
- // eslint-disable-next-line consistent-return
393
- return val.value;
489
+ // e.g. id === "commonjsHelpers?commonjsRegister"
490
+ function getSpecificHelperProxy(id) {
491
+ return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
394
492
  }
395
493
 
396
- function transformCommonjs(
397
- parse,
398
- code,
399
- id,
400
- isEsModule,
401
- ignoreGlobal,
402
- ignoreRequire,
403
- sourceMap,
404
- isDynamicRequireModulesEnabled,
405
- dynamicRequireModuleSet,
406
- commonDir,
407
- astCache
408
- ) {
409
- const ast = astCache || tryParse(parse, code, id);
410
-
411
- const magicString = new MagicString(code);
412
-
413
- const required = {};
414
- // Because objects have no guaranteed ordering, yet we need it,
415
- // we need to keep track of the order in a array
416
- const sources = [];
417
-
418
- let uid = 0;
419
-
420
- let scope = pluginutils.attachScopes(ast, 'scope');
421
- const uses = { module: false, exports: false, global: false, require: false };
422
-
423
- let lexicalDepth = 0;
424
- let programDepth = 0;
425
-
426
- const globals = new Set();
427
-
428
- // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
429
- const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
430
-
431
- const namedExports = {};
432
-
433
- // TODO handle transpiled modules
434
- let shouldWrap = /__esModule/.test(code);
435
- let usesCommonjsHelpers = false;
494
+ function getUnknownRequireProxy(id, requireReturnsDefault) {
495
+ if (requireReturnsDefault === true || id.endsWith('.json')) {
496
+ return `export {default} from ${JSON.stringify(id)};`;
497
+ }
498
+ const name = getName(id);
499
+ const exported =
500
+ requireReturnsDefault === 'auto'
501
+ ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
502
+ : requireReturnsDefault === 'preferred'
503
+ ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
504
+ : !requireReturnsDefault
505
+ ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
506
+ : `export default ${name};`;
507
+ return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
508
+ }
436
509
 
437
- function isRequireStatement(node) {
438
- if (!node) return false;
439
- if (node.type !== 'CallExpression') return false;
510
+ function getDynamicJsonProxy(id, commonDir) {
511
+ const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
512
+ return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
513
+ getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
514
+ )}, function (module, exports) {
515
+ module.exports = require(${JSON.stringify(normalizedPath)});
516
+ });`;
517
+ }
440
518
 
441
- // Weird case of `require()` or `module.require()` without arguments
442
- if (node.arguments.length === 0) return false;
519
+ function getDynamicRequireProxy(normalizedPath, commonDir) {
520
+ return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
521
+ getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
522
+ )}, function (module, exports) {
523
+ ${fs.readFileSync(normalizedPath, { encoding: 'utf8' })}
524
+ });`;
525
+ }
443
526
 
444
- return isRequireIdentifier(node.callee);
527
+ async function getStaticRequireProxy(
528
+ id,
529
+ requireReturnsDefault,
530
+ esModulesWithDefaultExport,
531
+ esModulesWithNamedExports
532
+ ) {
533
+ const name = getName(id);
534
+ const isCjs = await getIsCjsPromise(id);
535
+ if (isCjs) {
536
+ return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
537
+ } else if (isCjs === null) {
538
+ return getUnknownRequireProxy(id, requireReturnsDefault);
539
+ } else if (!requireReturnsDefault) {
540
+ return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
541
+ id
542
+ )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
543
+ } else if (
544
+ requireReturnsDefault !== true &&
545
+ (requireReturnsDefault === 'namespace' ||
546
+ !esModulesWithDefaultExport.has(id) ||
547
+ (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
548
+ ) {
549
+ return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
445
550
  }
551
+ return `export {default} from ${JSON.stringify(id)};`;
552
+ }
446
553
 
447
- function isRequireIdentifier(node) {
448
- if (!node) return false;
554
+ /* eslint-disable no-param-reassign, no-undefined */
449
555
 
450
- if (node.type === 'Identifier' && node.name === 'require' /* `require` */) {
451
- // `require` is hidden by a variable in local scope
452
- if (scope.contains('require')) return false;
556
+ function getCandidatesForExtension(resolved, extension) {
557
+ return [resolved + extension, `${resolved}${path.sep}index${extension}`];
558
+ }
453
559
 
454
- return true;
455
- } else if (node.type === 'MemberExpression' /* `[something].[something]` */) {
456
- // `module.[something]`
457
- if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false;
560
+ function getCandidates(resolved, extensions) {
561
+ return extensions.reduce(
562
+ (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
563
+ [resolved]
564
+ );
565
+ }
458
566
 
459
- // `module` is hidden by a variable in local scope
460
- if (scope.contains('module')) return false;
567
+ function getResolveId(extensions) {
568
+ function resolveExtensions(importee, importer) {
569
+ // not our problem
570
+ if (importee[0] !== '.' || !importer) return undefined;
461
571
 
462
- // `module.require(...)`
463
- if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
572
+ const resolved = path.resolve(path.dirname(importer), importee);
573
+ const candidates = getCandidates(resolved, extensions);
464
574
 
465
- return true;
575
+ for (let i = 0; i < candidates.length; i += 1) {
576
+ try {
577
+ const stats = fs.statSync(candidates[i]);
578
+ if (stats.isFile()) return { id: candidates[i] };
579
+ } catch (err) {
580
+ /* noop */
581
+ }
466
582
  }
467
583
 
468
- return false;
584
+ return undefined;
469
585
  }
470
586
 
471
- function hasDynamicArguments(node) {
472
- return (
473
- node.arguments.length > 1 ||
474
- (node.arguments[0].type !== 'Literal' &&
475
- (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
476
- );
477
- }
587
+ return function resolveId(importee, rawImporter) {
588
+ const importer =
589
+ rawImporter && isModuleRegisterProxy(rawImporter)
590
+ ? unwrapModuleRegisterProxy(rawImporter)
591
+ : rawImporter;
478
592
 
479
- function isStaticRequireStatement(node) {
480
- if (!isRequireStatement(node)) return false;
481
- return !hasDynamicArguments(node);
482
- }
593
+ // Proxies are only importing resolved ids, no need to resolve again
594
+ if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
595
+ return importee;
596
+ }
483
597
 
484
- function isNodeRequireStatement(parent) {
485
- const reservedMethod = ['resolve', 'cache', 'main'];
486
- return !!(parent && parent.property && reservedMethod.indexOf(parent.property.name) > -1);
487
- }
598
+ const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
599
+ const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
600
+ let isModuleRegistration = false;
488
601
 
489
- function isIgnoredRequireStatement(requiredNode) {
490
- return ignoreRequire(requiredNode.arguments[0].value);
491
- }
492
-
493
- function getRequireStringArg(node) {
494
- return node.arguments[0].type === 'Literal'
495
- ? node.arguments[0].value
496
- : node.arguments[0].quasis[0].value.cooked;
497
- }
602
+ if (isProxyModule) {
603
+ importee = unwrapId(importee, PROXY_SUFFIX);
604
+ } else if (isRequiredModule) {
605
+ importee = unwrapId(importee, REQUIRE_SUFFIX);
498
606
 
499
- function getRequired(node, name) {
500
- let sourceId = getRequireStringArg(node);
501
- const isDynamicRegister = sourceId.startsWith(DYNAMIC_REGISTER_PREFIX);
502
- if (isDynamicRegister) {
503
- sourceId = sourceId.substr(DYNAMIC_REGISTER_PREFIX.length);
607
+ isModuleRegistration = isModuleRegisterProxy(importee);
608
+ if (isModuleRegistration) {
609
+ importee = unwrapModuleRegisterProxy(importee);
610
+ }
504
611
  }
505
612
 
506
- const existing = required[sourceId];
507
- // eslint-disable-next-line no-undefined
508
- if (existing === undefined) {
509
- const isDynamic = hasDynamicModuleForPath(sourceId);
613
+ if (
614
+ importee.startsWith(HELPERS_ID) ||
615
+ importee === DYNAMIC_PACKAGES_ID ||
616
+ importee.startsWith(DYNAMIC_JSON_PREFIX)
617
+ ) {
618
+ return importee;
619
+ }
510
620
 
511
- if (!name) {
512
- do {
513
- name = `require$$${uid}`;
514
- uid += 1;
515
- } while (scope.contains(name));
516
- }
621
+ if (importee.startsWith('\0')) {
622
+ return null;
623
+ }
517
624
 
518
- if (isDynamicRegister && sourceId.endsWith('.json')) {
519
- sourceId = DYNAMIC_JSON_PREFIX + sourceId;
625
+ return this.resolve(importee, importer, {
626
+ skipSelf: true,
627
+ custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
628
+ }).then((resolved) => {
629
+ if (!resolved) {
630
+ resolved = resolveExtensions(importee, importer);
520
631
  }
521
-
522
- if (isDynamicRegister || !isDynamic || sourceId.endsWith('.json')) {
523
- sources.push([sourceId, !isDynamicRegister]);
632
+ if (resolved && isProxyModule) {
633
+ resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
634
+ resolved.external = false;
635
+ } else if (resolved && isModuleRegistration) {
636
+ resolved.id = wrapModuleRegisterProxy(resolved.id);
637
+ } else if (!resolved && (isProxyModule || isRequiredModule)) {
638
+ return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
524
639
  }
640
+ return resolved;
641
+ });
642
+ };
643
+ }
525
644
 
526
- required[sourceId] = { source: sourceId, name, importsDefault: false, isDynamic };
645
+ function validateRollupVersion(rollupVersion, peerDependencyVersion) {
646
+ const [major, minor] = rollupVersion.split('.').map(Number);
647
+ const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
648
+ let minMajor = Infinity;
649
+ let minMinor = Infinity;
650
+ let foundVersion;
651
+ // eslint-disable-next-line no-cond-assign
652
+ while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
653
+ const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
654
+ if (foundMajor < minMajor) {
655
+ minMajor = foundMajor;
656
+ minMinor = foundMinor;
527
657
  }
528
-
529
- return required[sourceId];
530
658
  }
659
+ if (major < minMajor || (major === minMajor && minor < minMinor)) {
660
+ throw new Error(
661
+ `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
662
+ );
663
+ }
664
+ }
531
665
 
532
- function hasDynamicModuleForPath(source) {
533
- if (!/[/\\]/.test(source)) {
534
- try {
535
- const resolvedPath = normalizePathSlashes(
536
- resolve.sync(source, { basedir: path.dirname(id) })
537
- );
538
- if (dynamicRequireModuleSet.has(resolvedPath)) {
539
- return true;
540
- }
541
- } catch (ex) {
542
- // Probably a node.js internal module
543
- return false;
544
- }
545
-
546
- return false;
547
- }
666
+ const operators = {
667
+ '==': (x) => equals(x.left, x.right, false),
548
668
 
549
- for (const attemptExt of ['', '.js', '.json']) {
550
- const resolvedPath = normalizePathSlashes(path.resolve(path.dirname(id), source + attemptExt));
551
- if (dynamicRequireModuleSet.has(resolvedPath)) {
552
- return true;
553
- }
554
- }
669
+ '!=': (x) => not(operators['=='](x)),
555
670
 
556
- return false;
557
- }
671
+ '===': (x) => equals(x.left, x.right, true),
558
672
 
559
- function shouldUseSimulatedRequire(required) {
560
- return (
561
- hasDynamicModuleForPath(required.source) &&
562
- // We only do `commonjsRequire` for json if it's the `commonjsRegister` call.
563
- (required.source.startsWith(DYNAMIC_REGISTER_PREFIX) || !required.source.endsWith('.json'))
564
- );
565
- }
673
+ '!==': (x) => not(operators['==='](x)),
566
674
 
567
- // do a first pass, see which names are assigned to. This is necessary to prevent
568
- // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
569
- // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
570
- const assignedTo = new Set();
571
- estreeWalker.walk(ast, {
572
- enter(node) {
573
- if (node.type !== 'AssignmentExpression') return;
574
- if (node.left.type === 'MemberExpression') return;
675
+ '!': (x) => isFalsy(x.argument),
575
676
 
576
- pluginutils.extractAssignedNames(node.left).forEach((name) => {
577
- assignedTo.add(name);
578
- });
579
- }
580
- });
677
+ '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
581
678
 
582
- estreeWalker.walk(ast, {
583
- enter(node, parent) {
584
- if (sourceMap) {
585
- magicString.addSourcemapLocation(node.start);
586
- magicString.addSourcemapLocation(node.end);
587
- }
679
+ '||': (x) => isTruthy(x.left) || isTruthy(x.right)
680
+ };
588
681
 
589
- // skip dead branches
590
- if (parent && (parent.type === 'IfStatement' || parent.type === 'ConditionalExpression')) {
591
- if (node === parent.consequent && isFalsy(parent.test)) {
592
- this.skip();
593
- return;
594
- }
595
- if (node === parent.alternate && isTruthy(parent.test)) {
596
- this.skip();
597
- return;
598
- }
599
- }
682
+ function not(value) {
683
+ return value === null ? value : !value;
684
+ }
600
685
 
601
- if (node._skip) {
602
- this.skip();
603
- return;
604
- }
686
+ function equals(a, b, strict) {
687
+ if (a.type !== b.type) return null;
688
+ // eslint-disable-next-line eqeqeq
689
+ if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
690
+ return null;
691
+ }
605
692
 
606
- programDepth += 1;
693
+ function isTruthy(node) {
694
+ if (!node) return false;
695
+ if (node.type === 'Literal') return !!node.value;
696
+ if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
697
+ if (node.operator in operators) return operators[node.operator](node);
698
+ return null;
699
+ }
607
700
 
608
- if (node.scope) ({ scope } = node);
609
- if (functionType.test(node.type)) lexicalDepth += 1;
701
+ function isFalsy(node) {
702
+ return not(isTruthy(node));
703
+ }
610
704
 
611
- // if toplevel return, we need to wrap it
612
- if (node.type === 'ReturnStatement' && lexicalDepth === 0) {
613
- shouldWrap = true;
614
- }
705
+ function getKeypath(node) {
706
+ const parts = [];
615
707
 
616
- // rewrite `this` as `commonjsHelpers.commonjsGlobal`
617
- if (node.type === 'ThisExpression' && lexicalDepth === 0) {
618
- uses.global = true;
619
- if (!ignoreGlobal) {
620
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
621
- storeName: true
622
- });
623
- usesCommonjsHelpers = true;
624
- }
625
- return;
626
- }
708
+ while (node.type === 'MemberExpression') {
709
+ if (node.computed) return null;
627
710
 
628
- // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
629
- if (node.type === 'UnaryExpression' && node.operator === 'typeof') {
630
- const flattened = flatten(node.argument);
631
- if (!flattened) return;
711
+ parts.unshift(node.property.name);
712
+ // eslint-disable-next-line no-param-reassign
713
+ node = node.object;
714
+ }
632
715
 
633
- if (scope.contains(flattened.name)) return;
716
+ if (node.type !== 'Identifier') return null;
634
717
 
635
- if (
636
- flattened.keypath === 'module.exports' ||
637
- flattened.keypath === 'module' ||
638
- flattened.keypath === 'exports'
639
- ) {
640
- magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
641
- }
642
- }
718
+ const { name } = node;
719
+ parts.unshift(name);
643
720
 
644
- // rewrite `require` (if not already handled) `global` and `define`, and handle free references to
645
- // `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
646
- if (node.type === 'Identifier') {
647
- if (isReference(node, parent) && !scope.contains(node.name)) {
648
- if (node.name in uses) {
649
- if (isRequireIdentifier(node)) {
650
- if (isNodeRequireStatement(parent)) {
651
- return;
652
- }
721
+ return { name, keypath: parts.join('.') };
722
+ }
653
723
 
654
- if (!isDynamicRequireModulesEnabled && isStaticRequireStatement(parent)) {
655
- return;
656
- }
724
+ const KEY_COMPILED_ESM = '__esModule';
657
725
 
658
- if (isDynamicRequireModulesEnabled && isRequireStatement(parent)) {
659
- magicString.appendLeft(
660
- parent.end - 1,
661
- `,${JSON.stringify(
662
- path.dirname(id) === '.'
663
- ? null /* default behavior */
664
- : getVirtualPathForDynamicRequirePath(
665
- normalizePathSlashes(path.dirname(id)),
666
- commonDir
667
- )
668
- )}`
669
- );
670
- }
726
+ function isDefineCompiledEsm(node) {
727
+ const definedProperty =
728
+ getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports');
729
+ if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
730
+ return isTruthy(definedProperty.value);
731
+ }
732
+ return false;
733
+ }
671
734
 
672
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
673
- storeName: true
674
- });
675
- usesCommonjsHelpers = true;
676
- }
735
+ function getDefinePropertyCallName(node, targetName) {
736
+ const targetNames = targetName.split('.');
677
737
 
678
- uses[node.name] = true;
679
- if (node.name === 'global' && !ignoreGlobal) {
680
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
681
- storeName: true
682
- });
683
- usesCommonjsHelpers = true;
684
- }
738
+ const {
739
+ callee: { object, property }
740
+ } = node;
741
+ if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
742
+ if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
743
+ if (node.arguments.length !== 3) return;
685
744
 
686
- // if module or exports are used outside the context of an assignment
687
- // expression, we need to wrap the module
688
- if (node.name === 'module' || node.name === 'exports') {
689
- shouldWrap = true;
690
- }
691
- }
745
+ const [target, key, value] = node.arguments;
746
+ if (targetNames.length === 1) {
747
+ if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
748
+ return;
749
+ }
750
+ }
692
751
 
693
- if (node.name === 'define') {
694
- magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
695
- }
752
+ if (targetNames.length === 2) {
753
+ if (
754
+ target.type !== 'MemberExpression' ||
755
+ target.object.name !== targetNames[0] ||
756
+ target.property.name !== targetNames[1]
757
+ ) {
758
+ return;
759
+ }
760
+ }
696
761
 
697
- globals.add(node.name);
698
- }
762
+ if (value.type !== 'ObjectExpression' || !value.properties) return;
699
763
 
700
- return;
701
- }
764
+ const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
765
+ if (!valueProperty || !valueProperty.value) return;
702
766
 
703
- // Is this an assignment to exports or module.exports?
704
- if (node.type === 'AssignmentExpression') {
705
- if (node.left.type !== 'MemberExpression') return;
767
+ // eslint-disable-next-line consistent-return
768
+ return { key: key.value, value: valueProperty.value };
769
+ }
706
770
 
707
- const flattened = flatten(node.left);
708
- if (!flattened) return;
771
+ function isLocallyShadowed(name, scope) {
772
+ while (scope.parent) {
773
+ if (scope.declarations[name]) {
774
+ return true;
775
+ }
776
+ // eslint-disable-next-line no-param-reassign
777
+ scope = scope.parent;
778
+ }
779
+ return false;
780
+ }
709
781
 
710
- if (scope.contains(flattened.name)) return;
782
+ function isShorthandProperty(parent) {
783
+ return parent && parent.type === 'Property' && parent.shorthand;
784
+ }
711
785
 
712
- const match = exportsPattern.exec(flattened.keypath);
713
- if (!match || flattened.keypath === 'exports') return;
786
+ function wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath) {
787
+ const args = `module${uses.exports ? ', exports' : ''}`;
714
788
 
715
- uses[flattened.name] = true;
789
+ magicString
790
+ .trim()
791
+ .prepend(`var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`)
792
+ .append(
793
+ `\n}${virtualDynamicRequirePath ? `, ${JSON.stringify(virtualDynamicRequirePath)}` : ''});`
794
+ );
795
+ }
716
796
 
717
- // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
718
- // if this isn't top-level, we'll need to wrap the module
719
- if (programDepth > 3) shouldWrap = true;
797
+ function rewriteExportsAndGetExportsBlock(
798
+ magicString,
799
+ moduleName,
800
+ wrapped,
801
+ topLevelModuleExportsAssignments,
802
+ topLevelExportsAssignmentsByName,
803
+ defineCompiledEsmExpressions,
804
+ deconflict,
805
+ isRestorableCompiledEsm,
806
+ code,
807
+ uses,
808
+ HELPERS_NAME
809
+ ) {
810
+ const namedExportDeclarations = [`export { ${moduleName} as __moduleExports };`];
811
+ const moduleExportsPropertyAssignments = [];
812
+ let deconflictedDefaultExportName;
813
+
814
+ if (!wrapped) {
815
+ let hasModuleExportsAssignment = false;
816
+ const namedExportProperties = [];
817
+
818
+ // Collect and rewrite module.exports assignments
819
+ for (const { left } of topLevelModuleExportsAssignments) {
820
+ hasModuleExportsAssignment = true;
821
+ magicString.overwrite(left.start, left.end, `var ${moduleName}`);
822
+ }
720
823
 
721
- node.left._skip = true;
824
+ // Collect and rewrite named exports
825
+ for (const [exportName, node] of topLevelExportsAssignmentsByName) {
826
+ const deconflicted = deconflict(exportName);
827
+ magicString.overwrite(node.start, node.left.end, `var ${deconflicted}`);
722
828
 
723
- if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
724
- node.right.properties.forEach((prop) => {
725
- if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
726
- const { name } = prop.key;
727
- if (name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
728
- });
729
- return;
730
- }
829
+ if (exportName === 'default') {
830
+ deconflictedDefaultExportName = deconflicted;
831
+ } else {
832
+ namedExportDeclarations.push(
833
+ exportName === deconflicted
834
+ ? `export { ${exportName} };`
835
+ : `export { ${deconflicted} as ${exportName} };`
836
+ );
837
+ }
731
838
 
732
- if (match[1]) namedExports[match[1]] = true;
733
- return;
839
+ if (hasModuleExportsAssignment) {
840
+ moduleExportsPropertyAssignments.push(`${moduleName}.${exportName} = ${deconflicted};`);
841
+ } else {
842
+ namedExportProperties.push(`\t${exportName}: ${deconflicted}`);
734
843
  }
844
+ }
735
845
 
736
- const name = getDefinePropertyCallName(node, 'exports');
737
- if (name && name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
846
+ // Regenerate CommonJS namespace
847
+ if (!hasModuleExportsAssignment) {
848
+ const moduleExports = `{\n${namedExportProperties.join(',\n')}\n}`;
849
+ magicString
850
+ .trim()
851
+ .append(
852
+ `\n\nvar ${moduleName} = ${
853
+ isRestorableCompiledEsm
854
+ ? `/*#__PURE__*/Object.defineProperty(${moduleExports}, '__esModule', {value: true})`
855
+ : moduleExports
856
+ };`
857
+ );
858
+ }
859
+ }
738
860
 
739
- // if this is `var x = require('x')`, we can do `import x from 'x'`
740
- if (
741
- node.type === 'VariableDeclarator' &&
742
- node.id.type === 'Identifier' &&
743
- isStaticRequireStatement(node.init) &&
744
- !isIgnoredRequireStatement(node.init)
745
- ) {
746
- // for now, only do this for top-level requires. maybe fix this in future
747
- if (scope.parent) return;
861
+ // Generate default export
862
+ const defaultExport = [];
863
+ if (isRestorableCompiledEsm) {
864
+ defaultExport.push(`export default ${deconflictedDefaultExportName || moduleName};`);
865
+ } else if (
866
+ (wrapped || deconflictedDefaultExportName) &&
867
+ (defineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0)
868
+ ) {
869
+ // eslint-disable-next-line no-param-reassign
870
+ uses.commonjsHelpers = true;
871
+ defaultExport.push(
872
+ `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
873
+ );
874
+ } else {
875
+ defaultExport.push(`export default ${moduleName};`);
876
+ }
748
877
 
749
- // edge case — CJS allows you to assign to imports. ES doesn't
750
- if (assignedTo.has(node.id.name)) return;
878
+ return `\n\n${defaultExport
879
+ .concat(namedExportDeclarations)
880
+ .concat(moduleExportsPropertyAssignments)
881
+ .join('\n')}`;
882
+ }
751
883
 
752
- const required = getRequired(node.init, node.id.name);
753
- required.importsDefault = true;
884
+ function isRequireStatement(node, scope) {
885
+ if (!node) return false;
886
+ if (node.type !== 'CallExpression') return false;
754
887
 
755
- if (required.name === node.id.name && !required.isDynamic) {
756
- node._shouldRemove = true;
757
- }
758
- }
888
+ // Weird case of `require()` or `module.require()` without arguments
889
+ if (node.arguments.length === 0) return false;
759
890
 
760
- if (!isStaticRequireStatement(node) || isIgnoredRequireStatement(node)) {
761
- return;
762
- }
891
+ return isRequire(node.callee, scope);
892
+ }
763
893
 
764
- const required = getRequired(node);
894
+ function isRequire(node, scope) {
895
+ return (
896
+ (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
897
+ (node.type === 'MemberExpression' && isModuleRequire(node, scope))
898
+ );
899
+ }
765
900
 
766
- if (parent.type === 'ExpressionStatement') {
767
- // is a bare import, e.g. `require('foo');`
768
- magicString.remove(parent.start, parent.end);
769
- } else {
770
- required.importsDefault = true;
771
-
772
- if (shouldUseSimulatedRequire(required)) {
773
- magicString.overwrite(
774
- node.start,
775
- node.end,
776
- `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
777
- getVirtualPathForDynamicRequirePath(normalizePathSlashes(required.source), commonDir)
778
- )}, ${JSON.stringify(
779
- path.dirname(id) === '.'
780
- ? null /* default behavior */
781
- : getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir)
782
- )})`
783
- );
784
- usesCommonjsHelpers = true;
785
- } else {
786
- magicString.overwrite(node.start, node.end, required.name);
787
- }
788
- }
901
+ function isModuleRequire({ object, property }, scope) {
902
+ return (
903
+ object.type === 'Identifier' &&
904
+ object.name === 'module' &&
905
+ property.type === 'Identifier' &&
906
+ property.name === 'require' &&
907
+ !scope.contains('module')
908
+ );
909
+ }
789
910
 
790
- node.callee._skip = true;
791
- },
911
+ function isStaticRequireStatement(node, scope) {
912
+ if (!isRequireStatement(node, scope)) return false;
913
+ return !hasDynamicArguments(node);
914
+ }
792
915
 
793
- leave(node) {
794
- programDepth -= 1;
795
- if (node.scope) scope = scope.parent;
796
- if (functionType.test(node.type)) lexicalDepth -= 1;
916
+ function hasDynamicArguments(node) {
917
+ return (
918
+ node.arguments.length > 1 ||
919
+ (node.arguments[0].type !== 'Literal' &&
920
+ (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
921
+ );
922
+ }
797
923
 
798
- if (node.type === 'VariableDeclaration') {
799
- let keepDeclaration = false;
800
- let c = node.declarations[0].start;
924
+ const reservedMethod = { resolve: true, cache: true, main: true };
801
925
 
802
- for (let i = 0; i < node.declarations.length; i += 1) {
803
- const declarator = node.declarations[i];
926
+ function isNodeRequirePropertyAccess(parent) {
927
+ return parent && parent.property && reservedMethod[parent.property.name];
928
+ }
804
929
 
805
- if (declarator._shouldRemove) {
806
- magicString.remove(c, declarator.end);
807
- } else {
808
- if (!keepDeclaration) {
809
- magicString.remove(c, declarator.start);
810
- keepDeclaration = true;
811
- }
930
+ function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
931
+ return ignoreRequire(requiredNode.arguments[0].value);
932
+ }
812
933
 
813
- c = declarator.end;
814
- }
815
- }
934
+ function getRequireStringArg(node) {
935
+ return node.arguments[0].type === 'Literal'
936
+ ? node.arguments[0].value
937
+ : node.arguments[0].quasis[0].value.cooked;
938
+ }
816
939
 
817
- if (!keepDeclaration) {
818
- magicString.remove(node.start, node.end);
819
- }
940
+ function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
941
+ if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
942
+ try {
943
+ const resolvedPath = normalizePathSlashes(resolve.sync(source, { basedir: path.dirname(id) }));
944
+ if (dynamicRequireModuleSet.has(resolvedPath)) {
945
+ return true;
820
946
  }
947
+ } catch (ex) {
948
+ // Probably a node.js internal module
949
+ return false;
821
950
  }
822
- });
823
951
 
824
- if (
825
- !sources.length &&
826
- !uses.module &&
827
- !uses.exports &&
828
- !uses.require &&
829
- (ignoreGlobal || !uses.global)
830
- ) {
831
- // not a CommonJS module
832
- return null;
952
+ return false;
833
953
  }
834
954
 
835
- // If `isEsModule` is on, it means it has ES6 import/export statements,
836
- // which just can't be wrapped in a function.
837
- if (isEsModule) shouldWrap = false;
838
-
839
- usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
840
-
841
- const importBlock = `${(usesCommonjsHelpers
842
- ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`]
843
- : []
844
- )
845
- .concat(
846
- sources.map(
847
- ([source]) =>
848
- // import the actual module before the proxy, so that we know
849
- // what kind of proxy to build
850
- `import '${source}';`
851
- ),
852
- sources
853
- .filter(([, importProxy]) => importProxy)
854
- .map(([source]) => {
855
- const { name, importsDefault } = required[source];
856
- return `import ${importsDefault ? `${name} from ` : ``}'${
857
- source.startsWith('\0') ? source : getProxyId(source)
858
- }';`;
859
- })
860
- )
861
- .join('\n')}\n\n`;
862
-
863
- const namedExportDeclarations = [];
864
- let wrapperStart = '';
865
- let wrapperEnd = '';
866
-
867
- const moduleName = deconflict(scope, globals, getName(id));
868
- if (!isEsModule) {
869
- const exportModuleExports = {
870
- str: `export { ${moduleName} as __moduleExports };`,
871
- name: '__moduleExports'
872
- };
873
-
874
- namedExportDeclarations.push(exportModuleExports);
955
+ for (const attemptExt of ['', '.js', '.json']) {
956
+ const resolvedPath = normalizePathSlashes(path.resolve(path.dirname(id), source + attemptExt));
957
+ if (dynamicRequireModuleSet.has(resolvedPath)) {
958
+ return true;
959
+ }
875
960
  }
876
961
 
877
- const defaultExportPropertyAssignments = [];
878
- let hasDefaultExport = false;
962
+ return false;
963
+ }
879
964
 
880
- if (shouldWrap) {
881
- const args = `module${uses.exports ? ', exports' : ''}`;
965
+ function getRequireHandlers() {
966
+ const requiredSources = [];
967
+ const requiredBySource = Object.create(null);
968
+ const requiredByNode = new Map();
969
+ const requireExpressionsWithUsedReturnValue = [];
970
+
971
+ function addRequireStatement(sourceId, node, scope, usesReturnValue) {
972
+ const required = getRequired(sourceId);
973
+ requiredByNode.set(node, { scope, required });
974
+ if (usesReturnValue) {
975
+ required.nodesUsingRequired.push(node);
976
+ requireExpressionsWithUsedReturnValue.push(node);
977
+ }
978
+ }
882
979
 
883
- wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
980
+ function getRequired(sourceId) {
981
+ if (!requiredBySource[sourceId]) {
982
+ requiredSources.push(sourceId);
884
983
 
885
- wrapperEnd = `\n}`;
886
- if (isDynamicRequireModulesEnabled) {
887
- wrapperEnd += `, ${JSON.stringify(
888
- getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir)
889
- )}`;
984
+ requiredBySource[sourceId] = {
985
+ source: sourceId,
986
+ name: null,
987
+ nodesUsingRequired: []
988
+ };
890
989
  }
891
990
 
892
- wrapperEnd += `);`;
893
- } else {
894
- const names = [];
991
+ return requiredBySource[sourceId];
992
+ }
895
993
 
896
- for (const node of ast.body) {
897
- if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
898
- const { left } = node.expression;
899
- const flattened = flatten(left);
994
+ function rewriteRequireExpressionsAndGetImportBlock(
995
+ magicString,
996
+ topLevelDeclarations,
997
+ topLevelRequireDeclarators,
998
+ reassignedNames,
999
+ helpersNameIfUsed,
1000
+ dynamicRegisterSources
1001
+ ) {
1002
+ const removedDeclarators = getDeclaratorsReplacedByImportsAndSetImportNames(
1003
+ topLevelRequireDeclarators,
1004
+ requiredByNode,
1005
+ reassignedNames
1006
+ );
1007
+ setRemainingImportNamesAndRewriteRequires(
1008
+ requireExpressionsWithUsedReturnValue,
1009
+ requiredByNode,
1010
+ magicString
1011
+ );
1012
+ removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString);
1013
+ const importBlock = `${(helpersNameIfUsed
1014
+ ? [`import * as ${helpersNameIfUsed} from '${HELPERS_ID}';`]
1015
+ : []
1016
+ )
1017
+ .concat(
1018
+ // dynamic registers first, as the may be required in the other modules
1019
+ [...dynamicRegisterSources].map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
1020
+
1021
+ // now the actual modules so that they are analyzed before creating the proxies;
1022
+ // no need to do this for virtual modules as we never proxy them
1023
+ requiredSources
1024
+ .filter((source) => !source.startsWith('\0'))
1025
+ .map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
1026
+
1027
+ // now the proxy modules
1028
+ requiredSources.map((source) => {
1029
+ const { name, nodesUsingRequired } = requiredBySource[source];
1030
+ return `import ${nodesUsingRequired.length ? `${name} from ` : ``}'${
1031
+ source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
1032
+ }';`;
1033
+ })
1034
+ )
1035
+ .join('\n')}`;
1036
+ return importBlock ? `${importBlock}\n\n` : '';
1037
+ }
900
1038
 
901
- if (!flattened) {
902
- continue;
903
- }
1039
+ return {
1040
+ addRequireStatement,
1041
+ requiredSources,
1042
+ rewriteRequireExpressionsAndGetImportBlock
1043
+ };
1044
+ }
904
1045
 
905
- const match = exportsPattern.exec(flattened.keypath);
906
- if (!match) {
907
- continue;
908
- }
1046
+ function getDeclaratorsReplacedByImportsAndSetImportNames(
1047
+ topLevelRequireDeclarators,
1048
+ requiredByNode,
1049
+ reassignedNames
1050
+ ) {
1051
+ const removedDeclarators = new Set();
1052
+ for (const declarator of topLevelRequireDeclarators) {
1053
+ const { required } = requiredByNode.get(declarator.init);
1054
+ if (!required.name) {
1055
+ const potentialName = declarator.id.name;
1056
+ if (
1057
+ !reassignedNames.has(potentialName) &&
1058
+ !required.nodesUsingRequired.some((node) =>
1059
+ isLocallyShadowed(potentialName, requiredByNode.get(node).scope)
1060
+ )
1061
+ ) {
1062
+ required.name = potentialName;
1063
+ removedDeclarators.add(declarator);
1064
+ }
1065
+ }
1066
+ }
1067
+ return removedDeclarators;
1068
+ }
909
1069
 
910
- if (flattened.keypath === 'module.exports') {
911
- hasDefaultExport = true;
912
- magicString.overwrite(left.start, left.end, `var ${moduleName}`);
913
- } else {
914
- const [, name] = match;
915
- const deconflicted = deconflict(scope, globals, name);
1070
+ function setRemainingImportNamesAndRewriteRequires(
1071
+ requireExpressionsWithUsedReturnValue,
1072
+ requiredByNode,
1073
+ magicString
1074
+ ) {
1075
+ let uid = 0;
1076
+ for (const requireExpression of requireExpressionsWithUsedReturnValue) {
1077
+ const { required } = requiredByNode.get(requireExpression);
1078
+ if (!required.name) {
1079
+ let potentialName;
1080
+ const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
1081
+ do {
1082
+ potentialName = `require$$${uid}`;
1083
+ uid += 1;
1084
+ } while (required.nodesUsingRequired.some(isUsedName));
1085
+ required.name = potentialName;
1086
+ }
1087
+ magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
1088
+ }
1089
+ }
916
1090
 
917
- names.push({ name, deconflicted });
1091
+ function removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString) {
1092
+ for (const declaration of topLevelDeclarations) {
1093
+ let keepDeclaration = false;
1094
+ let [{ start }] = declaration.declarations;
1095
+ for (const declarator of declaration.declarations) {
1096
+ if (removedDeclarators.has(declarator)) {
1097
+ magicString.remove(start, declarator.end);
1098
+ } else if (!keepDeclaration) {
1099
+ magicString.remove(start, declarator.start);
1100
+ keepDeclaration = true;
1101
+ }
1102
+ start = declarator.end;
1103
+ }
1104
+ if (!keepDeclaration) {
1105
+ magicString.remove(declaration.start, declaration.end);
1106
+ }
1107
+ }
1108
+ }
918
1109
 
919
- magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
1110
+ /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
920
1111
 
921
- const declaration =
922
- name === deconflicted
923
- ? `export { ${name} };`
924
- : `export { ${deconflicted} as ${name} };`;
1112
+ const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
925
1113
 
926
- if (name !== 'default') {
927
- namedExportDeclarations.push({
928
- str: declaration,
929
- name
930
- });
931
- }
1114
+ const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
932
1115
 
933
- defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
934
- }
935
- }
936
- }
1116
+ function transformCommonjs(
1117
+ parse,
1118
+ code,
1119
+ id,
1120
+ isEsModule,
1121
+ ignoreGlobal,
1122
+ ignoreRequire,
1123
+ getIgnoreTryCatchRequireStatementMode,
1124
+ sourceMap,
1125
+ isDynamicRequireModulesEnabled,
1126
+ dynamicRequireModuleSet,
1127
+ disableWrap,
1128
+ commonDir,
1129
+ astCache
1130
+ ) {
1131
+ const ast = astCache || tryParse(parse, code, id);
1132
+ const magicString = new MagicString__default['default'](code);
1133
+ const uses = {
1134
+ module: false,
1135
+ exports: false,
1136
+ global: false,
1137
+ require: false,
1138
+ commonjsHelpers: false
1139
+ };
1140
+ const virtualDynamicRequirePath =
1141
+ isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path.dirname(id), commonDir);
1142
+ let scope = pluginutils.attachScopes(ast, 'scope');
1143
+ let lexicalDepth = 0;
1144
+ let programDepth = 0;
1145
+ let currentTryBlockEnd = null;
1146
+ let shouldWrap = false;
1147
+ const defineCompiledEsmExpressions = [];
937
1148
 
938
- if (!(isEsModule || hasDefaultExport)) {
939
- wrapperEnd = `\n\nvar ${moduleName} = {\n${names
940
- .map(({ name, deconflicted }) => `\t${name}: ${deconflicted}`)
941
- .join(',\n')}\n};`;
942
- }
943
- }
1149
+ const globals = new Set();
944
1150
 
945
- magicString
946
- .trim()
947
- .prepend(importBlock + wrapperStart)
948
- .trim()
949
- .append(wrapperEnd);
950
-
951
- const defaultExport =
952
- code.indexOf('__esModule') >= 0
953
- ? `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
954
- : `export default ${moduleName};`;
955
-
956
- const named = namedExportDeclarations
957
- .filter((x) => x.name !== 'default' || !hasDefaultExport)
958
- .map((x) => x.str);
959
-
960
- magicString.append(
961
- `\n\n${(isEsModule ? [] : [defaultExport])
962
- .concat(named)
963
- .concat(hasDefaultExport ? defaultExportPropertyAssignments : [])
964
- .join('\n')}`
965
- );
1151
+ // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
1152
+ const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
1153
+ const namedExports = {};
1154
+ const dynamicRegisterSources = new Set();
1155
+ let hasRemovedRequire = false;
966
1156
 
967
- code = magicString.toString();
968
- const map = sourceMap ? magicString.generateMap() : null;
1157
+ const {
1158
+ addRequireStatement,
1159
+ requiredSources,
1160
+ rewriteRequireExpressionsAndGetImportBlock
1161
+ } = getRequireHandlers();
969
1162
 
970
- return { code, map, syntheticNamedExports: isEsModule ? false : '__moduleExports' };
971
- }
1163
+ // See which names are assigned to. This is necessary to prevent
1164
+ // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
1165
+ // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
1166
+ const reassignedNames = new Set();
1167
+ const topLevelDeclarations = [];
1168
+ const topLevelRequireDeclarators = new Set();
1169
+ const skippedNodes = new Set();
1170
+ const topLevelModuleExportsAssignments = [];
1171
+ const topLevelExportsAssignmentsByName = new Map();
972
1172
 
973
- function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
974
- let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`;
975
- for (const dir of dynamicRequireModuleDirPaths) {
976
- let entryPoint = 'index.js';
1173
+ estreeWalker.walk(ast, {
1174
+ enter(node, parent) {
1175
+ if (skippedNodes.has(node)) {
1176
+ this.skip();
1177
+ return;
1178
+ }
977
1179
 
978
- try {
979
- if (fs.existsSync(path.join(dir, 'package.json'))) {
980
- entryPoint =
981
- JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), { encoding: 'utf8' })).main ||
982
- entryPoint;
1180
+ if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
1181
+ currentTryBlockEnd = null;
983
1182
  }
984
- } catch (ignored) {
985
- // ignored
986
- }
987
1183
 
988
- code += `\ncommonjsRegister(${JSON.stringify(
989
- getVirtualPathForDynamicRequirePath(dir, commonDir)
990
- )}, function (module, exports) {
991
- module.exports = require(${JSON.stringify(normalizePathSlashes(path.join(dir, entryPoint)))});
992
- });`;
993
- }
994
- return code;
995
- }
1184
+ programDepth += 1;
1185
+ if (node.scope) ({ scope } = node);
1186
+ if (functionType.test(node.type)) lexicalDepth += 1;
1187
+ if (sourceMap) {
1188
+ magicString.addSourcemapLocation(node.start);
1189
+ magicString.addSourcemapLocation(node.end);
1190
+ }
996
1191
 
997
- function getDynamicPackagesEntryIntro(
998
- id,
999
- dynamicRequireModuleDirPaths,
1000
- dynamicRequireModuleSet
1001
- ) {
1002
- try {
1003
- const code = fs.readFileSync(id, { encoding: 'utf8' });
1004
- let dynamicImports = Array.from(
1005
- dynamicRequireModuleSet,
1006
- (dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
1007
- ).join('\n');
1192
+ // eslint-disable-next-line default-case
1193
+ switch (node.type) {
1194
+ case 'TryStatement':
1195
+ if (currentTryBlockEnd === null) {
1196
+ currentTryBlockEnd = node.block.end;
1197
+ }
1198
+ return;
1199
+ case 'AssignmentExpression':
1200
+ if (node.left.type === 'MemberExpression') {
1201
+ const flattened = getKeypath(node.left);
1202
+ if (!flattened || scope.contains(flattened.name)) return;
1008
1203
 
1009
- if (dynamicRequireModuleDirPaths.length) {
1010
- dynamicImports += `require(${JSON.stringify(
1011
- DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID
1012
- )});`;
1013
- }
1204
+ const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
1205
+ if (!exportsPatternMatch || flattened.keypath === 'exports') return;
1014
1206
 
1015
- return `${dynamicImports}\n${code}`;
1016
- } catch (ex) {
1017
- this.warn(`Failed to read file ${id}, dynamic modules might not work correctly`);
1018
- return null;
1019
- }
1020
- }
1207
+ const [, exportName] = exportsPatternMatch;
1208
+ uses[flattened.name] = true;
1021
1209
 
1022
- function getDynamicRequirePaths(patterns) {
1023
- const dynamicRequireModuleSet = new Set();
1024
- for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
1025
- const isNegated = pattern.startsWith('!');
1026
- const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
1027
- for (const path$1 of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
1028
- modifySet(normalizePathSlashes(path.resolve(path$1)));
1029
- }
1030
- }
1031
- const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter(
1032
- (path) => {
1033
- try {
1034
- if (fs.statSync(path).isDirectory()) return true;
1035
- } catch (ignored) {
1036
- // Nothing to do here
1037
- }
1038
- return false;
1039
- }
1040
- );
1041
- return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
1042
- }
1210
+ // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
1211
+ if (programDepth > 3) {
1212
+ shouldWrap = true;
1213
+ } else if (exportName === KEY_COMPILED_ESM) {
1214
+ defineCompiledEsmExpressions.push(parent);
1215
+ } else if (flattened.keypath === 'module.exports') {
1216
+ topLevelModuleExportsAssignments.push(node);
1217
+ } else if (!topLevelExportsAssignmentsByName.has(exportName)) {
1218
+ topLevelExportsAssignmentsByName.set(exportName, node);
1219
+ } else {
1220
+ shouldWrap = true;
1221
+ }
1043
1222
 
1044
- /* eslint-disable no-undefined */
1045
- const isCjsPromises = new Map();
1223
+ skippedNodes.add(node.left);
1046
1224
 
1047
- function getIsCjsPromise(id) {
1048
- let isCjsPromise = isCjsPromises.get(id);
1049
- if (isCjsPromise) return isCjsPromise.promise;
1225
+ if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
1226
+ node.right.properties.forEach((prop) => {
1227
+ if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
1228
+ const { name } = prop.key;
1229
+ if (name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
1230
+ });
1231
+ return;
1232
+ }
1050
1233
 
1051
- const promise = new Promise((resolve) => {
1052
- isCjsPromise = {
1053
- resolve,
1054
- promise: undefined
1055
- };
1056
- isCjsPromises.set(id, isCjsPromise);
1057
- });
1058
- isCjsPromise.promise = promise;
1234
+ if (exportsPatternMatch[1]) namedExports[exportsPatternMatch[1]] = true;
1235
+ } else {
1236
+ for (const name of pluginutils.extractAssignedNames(node.left)) {
1237
+ reassignedNames.add(name);
1238
+ }
1239
+ }
1240
+ return;
1241
+ case 'CallExpression': {
1242
+ if (isDefineCompiledEsm(node)) {
1243
+ if (programDepth === 3 && parent.type === 'ExpressionStatement') {
1244
+ // skip special handling for [module.]exports until we know we render this
1245
+ skippedNodes.add(node.arguments[0]);
1246
+ defineCompiledEsmExpressions.push(parent);
1247
+ } else {
1248
+ shouldWrap = true;
1249
+ }
1250
+ return;
1251
+ }
1059
1252
 
1060
- return promise;
1061
- }
1253
+ if (
1254
+ node.callee.object &&
1255
+ node.callee.object.name === 'require' &&
1256
+ node.callee.property.name === 'resolve' &&
1257
+ hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
1258
+ ) {
1259
+ const requireNode = node.callee.object;
1260
+ magicString.appendLeft(
1261
+ node.end - 1,
1262
+ `,${JSON.stringify(
1263
+ path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1264
+ )}`
1265
+ );
1266
+ magicString.overwrite(
1267
+ requireNode.start,
1268
+ requireNode.end,
1269
+ `${HELPERS_NAME}.commonjsRequire`,
1270
+ {
1271
+ storeName: true
1272
+ }
1273
+ );
1274
+ uses.commonjsHelpers = true;
1275
+ return;
1276
+ }
1062
1277
 
1063
- function setIsCjsPromise(id, resolution) {
1064
- const isCjsPromise = isCjsPromises.get(id);
1065
- if (isCjsPromise) {
1066
- if (isCjsPromise.resolve) {
1067
- isCjsPromise.resolve(resolution);
1068
- isCjsPromise.resolve = undefined;
1069
- }
1070
- } else {
1071
- isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: undefined });
1072
- }
1073
- }
1278
+ if (!isStaticRequireStatement(node, scope)) return;
1279
+ if (!isDynamicRequireModulesEnabled) {
1280
+ skippedNodes.add(node.callee);
1281
+ }
1282
+ if (!isIgnoredRequireStatement(node, ignoreRequire)) {
1283
+ skippedNodes.add(node.callee);
1284
+ const usesReturnValue = parent.type !== 'ExpressionStatement';
1074
1285
 
1075
- // e.g. id === "commonjsHelpers?commonjsRegister"
1076
- function getSpecificHelperProxy(id) {
1077
- return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
1078
- }
1286
+ let canConvertRequire = true;
1287
+ let shouldRemoveRequireStatement = false;
1079
1288
 
1080
- function getUnknownRequireProxy(id, requireReturnsDefault) {
1081
- if (requireReturnsDefault === true || id.endsWith('.json')) {
1082
- return `export {default} from ${JSON.stringify(id)};`;
1083
- }
1084
- const name = getName(id);
1085
- const exported =
1086
- requireReturnsDefault === 'auto'
1087
- ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name})`
1088
- : requireReturnsDefault === 'preferred'
1089
- ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name})`
1090
- : `export default ${name}`;
1091
- return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
1092
- }
1289
+ if (currentTryBlockEnd !== null) {
1290
+ ({
1291
+ canConvertRequire,
1292
+ shouldRemoveRequireStatement
1293
+ } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
1093
1294
 
1094
- function getDynamicJsonProxy(id, commonDir) {
1095
- const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
1096
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
1097
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
1098
- )}, function (module, exports) {
1099
- module.exports = require(${JSON.stringify(normalizedPath)});
1100
- });`;
1101
- }
1295
+ if (shouldRemoveRequireStatement) {
1296
+ hasRemovedRequire = true;
1297
+ }
1298
+ }
1102
1299
 
1103
- function getDynamicRequireProxy(normalizedPath, commonDir) {
1104
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
1105
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
1106
- )}, function (module, exports) {
1107
- ${fs.readFileSync(normalizedPath, { encoding: 'utf8' })}
1108
- });`;
1109
- }
1300
+ let sourceId = getRequireStringArg(node);
1301
+ const isDynamicRegister = isModuleRegisterProxy(sourceId);
1302
+ if (isDynamicRegister) {
1303
+ sourceId = unwrapModuleRegisterProxy(sourceId);
1304
+ if (sourceId.endsWith('.json')) {
1305
+ sourceId = DYNAMIC_JSON_PREFIX + sourceId;
1306
+ }
1307
+ dynamicRegisterSources.add(wrapModuleRegisterProxy(sourceId));
1308
+ } else {
1309
+ if (
1310
+ !sourceId.endsWith('.json') &&
1311
+ hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
1312
+ ) {
1313
+ if (shouldRemoveRequireStatement) {
1314
+ magicString.overwrite(node.start, node.end, `undefined`);
1315
+ } else if (canConvertRequire) {
1316
+ magicString.overwrite(
1317
+ node.start,
1318
+ node.end,
1319
+ `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
1320
+ getVirtualPathForDynamicRequirePath(sourceId, commonDir)
1321
+ )}, ${JSON.stringify(
1322
+ path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1323
+ )})`
1324
+ );
1325
+ uses.commonjsHelpers = true;
1326
+ }
1327
+ return;
1328
+ }
1110
1329
 
1111
- async function getStaticRequireProxy(
1112
- id,
1113
- requireReturnsDefault,
1114
- esModulesWithDefaultExport,
1115
- esModulesWithNamedExports
1116
- ) {
1117
- const name = getName(id);
1118
- const isCjs = await getIsCjsPromise(id);
1119
- if (isCjs) {
1120
- return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
1121
- } else if (isCjs === null) {
1122
- return getUnknownRequireProxy(id, requireReturnsDefault);
1123
- } else if (
1124
- requireReturnsDefault !== true &&
1125
- (!requireReturnsDefault ||
1126
- !esModulesWithDefaultExport.has(id) ||
1127
- (esModulesWithNamedExports.has(id) && requireReturnsDefault === 'auto'))
1128
- ) {
1129
- return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
1130
- }
1131
- return `export {default} from ${JSON.stringify(id)};`;
1132
- }
1330
+ if (canConvertRequire) {
1331
+ addRequireStatement(sourceId, node, scope, usesReturnValue);
1332
+ }
1333
+ }
1133
1334
 
1134
- /* eslint-disable no-param-reassign, no-undefined */
1335
+ if (usesReturnValue) {
1336
+ if (shouldRemoveRequireStatement) {
1337
+ magicString.overwrite(node.start, node.end, `undefined`);
1338
+ return;
1339
+ }
1135
1340
 
1136
- function getCandidatesForExtension(resolved, extension) {
1137
- return [resolved + extension, `${resolved}${path.sep}index${extension}`];
1138
- }
1341
+ if (
1342
+ parent.type === 'VariableDeclarator' &&
1343
+ !scope.parent &&
1344
+ parent.id.type === 'Identifier'
1345
+ ) {
1346
+ // This will allow us to reuse this variable name as the imported variable if it is not reassigned
1347
+ // and does not conflict with variables in other places where this is imported
1348
+ topLevelRequireDeclarators.add(parent);
1349
+ }
1350
+ } else {
1351
+ // This is a bare import, e.g. `require('foo');`
1139
1352
 
1140
- function getCandidates(resolved, extensions) {
1141
- return extensions.reduce(
1142
- (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
1143
- [resolved]
1144
- );
1145
- }
1353
+ if (!canConvertRequire && !shouldRemoveRequireStatement) {
1354
+ return;
1355
+ }
1146
1356
 
1147
- function getResolveId(extensions) {
1148
- function resolveExtensions(importee, importer) {
1149
- // not our problem
1150
- if (importee[0] !== '.' || !importer) return undefined;
1357
+ magicString.remove(parent.start, parent.end);
1358
+ }
1359
+ }
1360
+ return;
1361
+ }
1362
+ case 'ConditionalExpression':
1363
+ case 'IfStatement':
1364
+ // skip dead branches
1365
+ if (isFalsy(node.test)) {
1366
+ skippedNodes.add(node.consequent);
1367
+ } else if (node.alternate && isTruthy(node.test)) {
1368
+ skippedNodes.add(node.alternate);
1369
+ }
1370
+ return;
1371
+ case 'Identifier': {
1372
+ const { name } = node;
1373
+ if (!(isReference__default['default'](node, parent) && !scope.contains(name))) return;
1374
+ switch (name) {
1375
+ case 'require':
1376
+ if (isNodeRequirePropertyAccess(parent)) {
1377
+ if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
1378
+ if (parent.property.name === 'cache') {
1379
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1380
+ storeName: true
1381
+ });
1382
+ uses.commonjsHelpers = true;
1383
+ }
1384
+ }
1151
1385
 
1152
- const resolved = path.resolve(path.dirname(importer), importee);
1153
- const candidates = getCandidates(resolved, extensions);
1386
+ return;
1387
+ }
1154
1388
 
1155
- for (let i = 0; i < candidates.length; i += 1) {
1156
- try {
1157
- const stats = fs.statSync(candidates[i]);
1158
- if (stats.isFile()) return { id: candidates[i] };
1159
- } catch (err) {
1160
- /* noop */
1389
+ if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
1390
+ magicString.appendLeft(
1391
+ parent.end - 1,
1392
+ `,${JSON.stringify(
1393
+ path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1394
+ )}`
1395
+ );
1396
+ }
1397
+ if (isShorthandProperty(parent)) {
1398
+ magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1399
+ } else {
1400
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1401
+ storeName: true
1402
+ });
1403
+ }
1404
+
1405
+ uses.commonjsHelpers = true;
1406
+ return;
1407
+ case 'module':
1408
+ case 'exports':
1409
+ shouldWrap = true;
1410
+ uses[name] = true;
1411
+ return;
1412
+ case 'global':
1413
+ uses.global = true;
1414
+ if (!ignoreGlobal) {
1415
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1416
+ storeName: true
1417
+ });
1418
+ uses.commonjsHelpers = true;
1419
+ }
1420
+ return;
1421
+ case 'define':
1422
+ magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
1423
+ return;
1424
+ default:
1425
+ globals.add(name);
1426
+ return;
1427
+ }
1428
+ }
1429
+ case 'MemberExpression':
1430
+ if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
1431
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1432
+ storeName: true
1433
+ });
1434
+ uses.commonjsHelpers = true;
1435
+ skippedNodes.add(node.object);
1436
+ skippedNodes.add(node.property);
1437
+ }
1438
+ return;
1439
+ case 'ReturnStatement':
1440
+ // if top-level return, we need to wrap it
1441
+ if (lexicalDepth === 0) {
1442
+ shouldWrap = true;
1443
+ }
1444
+ return;
1445
+ case 'ThisExpression':
1446
+ // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
1447
+ if (lexicalDepth === 0) {
1448
+ uses.global = true;
1449
+ if (!ignoreGlobal) {
1450
+ magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1451
+ storeName: true
1452
+ });
1453
+ uses.commonjsHelpers = true;
1454
+ }
1455
+ }
1456
+ return;
1457
+ case 'UnaryExpression':
1458
+ // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
1459
+ if (node.operator === 'typeof') {
1460
+ const flattened = getKeypath(node.argument);
1461
+ if (!flattened) return;
1462
+
1463
+ if (scope.contains(flattened.name)) return;
1464
+
1465
+ if (
1466
+ flattened.keypath === 'module.exports' ||
1467
+ flattened.keypath === 'module' ||
1468
+ flattened.keypath === 'exports'
1469
+ ) {
1470
+ magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
1471
+ }
1472
+ }
1473
+ return;
1474
+ case 'VariableDeclaration':
1475
+ if (!scope.parent) {
1476
+ topLevelDeclarations.push(node);
1477
+ }
1161
1478
  }
1479
+ },
1480
+
1481
+ leave(node) {
1482
+ programDepth -= 1;
1483
+ if (node.scope) scope = scope.parent;
1484
+ if (functionType.test(node.type)) lexicalDepth -= 1;
1162
1485
  }
1486
+ });
1163
1487
 
1164
- return undefined;
1488
+ let isRestorableCompiledEsm = false;
1489
+ if (defineCompiledEsmExpressions.length > 0) {
1490
+ if (!shouldWrap && defineCompiledEsmExpressions.length === 1) {
1491
+ isRestorableCompiledEsm = true;
1492
+ magicString.remove(
1493
+ defineCompiledEsmExpressions[0].start,
1494
+ defineCompiledEsmExpressions[0].end
1495
+ );
1496
+ } else {
1497
+ shouldWrap = true;
1498
+ uses.exports = true;
1499
+ }
1165
1500
  }
1166
1501
 
1167
- function resolveId(importee, importer) {
1168
- const isProxyModule = importee.endsWith(PROXY_SUFFIX);
1169
- if (isProxyModule) {
1170
- importee = getIdFromProxyId(importee);
1171
- }
1172
- if (importee.startsWith('\0')) {
1173
- if (
1174
- importee.startsWith(HELPERS_ID) ||
1175
- importee === DYNAMIC_PACKAGES_ID ||
1176
- importee.startsWith(DYNAMIC_JSON_PREFIX)
1177
- ) {
1178
- return importee;
1179
- }
1180
- if (!isProxyModule) {
1181
- return null;
1182
- }
1183
- }
1502
+ // We cannot wrap ES/mixed modules
1503
+ shouldWrap = shouldWrap && !disableWrap && !isEsModule;
1504
+ uses.commonjsHelpers = uses.commonjsHelpers || shouldWrap;
1184
1505
 
1185
- if (importer && importer.endsWith(PROXY_SUFFIX)) {
1186
- importer = getIdFromProxyId(importer);
1187
- }
1506
+ if (
1507
+ !(
1508
+ requiredSources.length ||
1509
+ dynamicRegisterSources.size ||
1510
+ uses.module ||
1511
+ uses.exports ||
1512
+ uses.require ||
1513
+ uses.commonjsHelpers ||
1514
+ hasRemovedRequire
1515
+ ) &&
1516
+ (ignoreGlobal || !uses.global)
1517
+ ) {
1518
+ return { meta: { commonjs: { isCommonJS: false } } };
1519
+ }
1188
1520
 
1189
- return this.resolve(importee, importer, { skipSelf: true }).then((resolved) => {
1190
- if (!resolved) {
1191
- resolved = resolveExtensions(importee, importer);
1192
- }
1193
- if (isProxyModule) {
1194
- if (!resolved) {
1195
- return { id: getExternalProxyId(importee), external: false };
1196
- }
1197
- resolved.id = (resolved.external ? getExternalProxyId : getProxyId)(resolved.id);
1198
- resolved.external = false;
1199
- return resolved;
1200
- }
1201
- return resolved;
1202
- });
1521
+ const moduleName = deconflict(scope, globals, getName(id));
1522
+
1523
+ let leadingComment = '';
1524
+ if (code.startsWith('/*')) {
1525
+ const commentEnd = code.indexOf('*/', 2) + 2;
1526
+ leadingComment = `${code.slice(0, commentEnd)}\n`;
1527
+ magicString.remove(0, commentEnd).trim();
1203
1528
  }
1204
1529
 
1205
- return resolveId;
1530
+ const exportBlock = isEsModule
1531
+ ? ''
1532
+ : rewriteExportsAndGetExportsBlock(
1533
+ magicString,
1534
+ moduleName,
1535
+ shouldWrap,
1536
+ topLevelModuleExportsAssignments,
1537
+ topLevelExportsAssignmentsByName,
1538
+ defineCompiledEsmExpressions,
1539
+ (name) => deconflict(scope, globals, name),
1540
+ isRestorableCompiledEsm,
1541
+ code,
1542
+ uses,
1543
+ HELPERS_NAME
1544
+ );
1545
+
1546
+ const importBlock = rewriteRequireExpressionsAndGetImportBlock(
1547
+ magicString,
1548
+ topLevelDeclarations,
1549
+ topLevelRequireDeclarators,
1550
+ reassignedNames,
1551
+ uses.commonjsHelpers && HELPERS_NAME,
1552
+ dynamicRegisterSources
1553
+ );
1554
+
1555
+ if (shouldWrap) {
1556
+ wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath);
1557
+ }
1558
+
1559
+ magicString
1560
+ .trim()
1561
+ .prepend(leadingComment + importBlock)
1562
+ .append(exportBlock);
1563
+
1564
+ return {
1565
+ code: magicString.toString(),
1566
+ map: sourceMap ? magicString.generateMap() : null,
1567
+ syntheticNamedExports: isEsModule ? false : '__moduleExports',
1568
+ meta: { commonjs: { isCommonJS: !isEsModule } }
1569
+ };
1206
1570
  }
1207
1571
 
1208
1572
  function commonjs(options = {}) {
@@ -1230,7 +1594,7 @@ function commonjs(options = {}) {
1230
1594
  );
1231
1595
  const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
1232
1596
  const commonDir = isDynamicRequireModulesEnabled
1233
- ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1597
+ ? getCommonDir__default['default'](null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1234
1598
  : null;
1235
1599
 
1236
1600
  const esModulesWithDefaultExport = new Set();
@@ -1243,12 +1607,31 @@ function commonjs(options = {}) {
1243
1607
  ? (id) => options.ignore.includes(id)
1244
1608
  : () => false;
1245
1609
 
1610
+ const getIgnoreTryCatchRequireStatementMode = (id) => {
1611
+ const mode =
1612
+ typeof options.ignoreTryCatch === 'function'
1613
+ ? options.ignoreTryCatch(id)
1614
+ : Array.isArray(options.ignoreTryCatch)
1615
+ ? options.ignoreTryCatch.includes(id)
1616
+ : options.ignoreTryCatch || false;
1617
+
1618
+ return {
1619
+ canConvertRequire: mode !== 'remove' && mode !== true,
1620
+ shouldRemoveRequireStatement: mode === 'remove'
1621
+ };
1622
+ };
1623
+
1246
1624
  const resolveId = getResolveId(extensions);
1247
1625
 
1248
1626
  const sourceMap = options.sourceMap !== false;
1249
1627
 
1250
1628
  function transformAndCheckExports(code, id) {
1251
- const { isEsModule, hasDefaultExport, hasNamedExports, ast } = checkEsModule(
1629
+ if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1630
+ code =
1631
+ getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1632
+ }
1633
+
1634
+ const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1252
1635
  this.parse,
1253
1636
  code,
1254
1637
  id
@@ -1264,46 +1647,44 @@ function commonjs(options = {}) {
1264
1647
  !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1265
1648
  (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1266
1649
  ) {
1267
- setIsCjsPromise(id, false);
1268
- return null;
1650
+ return { meta: { commonjs: { isCommonJS: false } } };
1269
1651
  }
1270
1652
 
1271
- const transformed = transformCommonjs(
1653
+ let disableWrap = false;
1654
+
1655
+ // avoid wrapping in createCommonjsModule, as this is a commonjsRegister call
1656
+ if (isModuleRegisterProxy(id)) {
1657
+ disableWrap = true;
1658
+ id = unwrapModuleRegisterProxy(id);
1659
+ }
1660
+
1661
+ return transformCommonjs(
1272
1662
  this.parse,
1273
1663
  code,
1274
1664
  id,
1275
1665
  isEsModule,
1276
1666
  ignoreGlobal || isEsModule,
1277
1667
  ignoreRequire,
1668
+ getIgnoreTryCatchRequireStatementMode,
1278
1669
  sourceMap,
1279
1670
  isDynamicRequireModulesEnabled,
1280
1671
  dynamicRequireModuleSet,
1672
+ disableWrap,
1281
1673
  commonDir,
1282
1674
  ast
1283
1675
  );
1284
-
1285
- setIsCjsPromise(id, isEsModule ? false : Boolean(transformed));
1286
- return transformed;
1287
1676
  }
1288
1677
 
1289
1678
  return {
1290
1679
  name: 'commonjs',
1291
1680
 
1292
1681
  buildStart() {
1682
+ validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1293
1683
  if (options.namedExports != null) {
1294
1684
  this.warn(
1295
1685
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1296
1686
  );
1297
1687
  }
1298
-
1299
- const [major, minor] = this.meta.rollupVersion.split('.').map(Number);
1300
- const minVersion = peerDependencies.rollup.slice(2);
1301
- const [minMajor, minMinor] = minVersion.split('.').map(Number);
1302
- if (major < minMajor || (major === minMajor && minor < minMinor)) {
1303
- this.error(
1304
- `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minVersion} but found rollup@${this.meta.rollupVersion}.`
1305
- );
1306
- }
1307
1688
  },
1308
1689
 
1309
1690
  resolveId,
@@ -1317,8 +1698,8 @@ function commonjs(options = {}) {
1317
1698
  return getSpecificHelperProxy(id);
1318
1699
  }
1319
1700
 
1320
- if (id.endsWith(EXTERNAL_SUFFIX)) {
1321
- const actualId = getIdFromExternalProxyId(id);
1701
+ if (isWrappedId(id, EXTERNAL_SUFFIX)) {
1702
+ const actualId = unwrapId(id, EXTERNAL_SUFFIX);
1322
1703
  return getUnknownRequireProxy(
1323
1704
  actualId,
1324
1705
  isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
@@ -1333,13 +1714,19 @@ function commonjs(options = {}) {
1333
1714
  return getDynamicJsonProxy(id, commonDir);
1334
1715
  }
1335
1716
 
1336
- const normalizedPath = normalizePathSlashes(id);
1337
- if (dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json')) {
1338
- return getDynamicRequireProxy(normalizedPath, commonDir);
1717
+ if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
1718
+ return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
1719
+ }
1720
+
1721
+ if (isModuleRegisterProxy(id)) {
1722
+ return getDynamicRequireProxy(
1723
+ normalizePathSlashes(unwrapModuleRegisterProxy(id)),
1724
+ commonDir
1725
+ );
1339
1726
  }
1340
1727
 
1341
- if (id.endsWith(PROXY_SUFFIX)) {
1342
- const actualId = getIdFromProxyId(id);
1728
+ if (isWrappedId(id, PROXY_SUFFIX)) {
1729
+ const actualId = unwrapId(id, PROXY_SUFFIX);
1343
1730
  return getStaticRequireProxy(
1344
1731
  actualId,
1345
1732
  getRequireReturnsDefault(actualId),
@@ -1348,36 +1735,42 @@ function commonjs(options = {}) {
1348
1735
  );
1349
1736
  }
1350
1737
 
1351
- if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1352
- return getDynamicPackagesEntryIntro(
1353
- id,
1354
- dynamicRequireModuleDirPaths,
1355
- dynamicRequireModuleSet
1356
- );
1357
- }
1358
-
1359
1738
  return null;
1360
1739
  },
1361
1740
 
1362
- transform(code, id) {
1741
+ transform(code, rawId) {
1742
+ let id = rawId;
1743
+
1744
+ if (isModuleRegisterProxy(id)) {
1745
+ id = unwrapModuleRegisterProxy(id);
1746
+ }
1747
+
1363
1748
  const extName = path.extname(id);
1364
- if (extName !== '.cjs' && id !== DYNAMIC_PACKAGES_ID && !id.startsWith(DYNAMIC_JSON_PREFIX)) {
1365
- if (!filter(id) || !extensions.includes(extName)) {
1366
- setIsCjsPromise(id, null);
1367
- return null;
1368
- }
1749
+ if (
1750
+ extName !== '.cjs' &&
1751
+ id !== DYNAMIC_PACKAGES_ID &&
1752
+ !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1753
+ (!filter(id) || !extensions.includes(extName))
1754
+ ) {
1755
+ return null;
1369
1756
  }
1370
1757
 
1371
- let transformed;
1372
1758
  try {
1373
- transformed = transformAndCheckExports.call(this, code, id);
1759
+ return transformAndCheckExports.call(this, code, rawId);
1374
1760
  } catch (err) {
1375
- transformed = null;
1376
- setIsCjsPromise(id, false);
1377
- this.error(err, err.loc);
1761
+ return this.error(err, err.loc);
1378
1762
  }
1763
+ },
1379
1764
 
1380
- return transformed;
1765
+ moduleParsed({ id, meta: { commonjs } }) {
1766
+ if (commonjs) {
1767
+ const isCjs = commonjs.isCommonJS;
1768
+ if (isCjs != null) {
1769
+ setIsCjsPromise(id, isCjs);
1770
+ return;
1771
+ }
1772
+ }
1773
+ setIsCjsPromise(id, null);
1381
1774
  }
1382
1775
  };
1383
1776
  }