@rollup/plugin-commonjs 20.0.0 → 22.0.0-1

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
@@ -2,13 +2,12 @@
2
2
 
3
3
  var path = require('path');
4
4
  var pluginutils = require('@rollup/pluginutils');
5
- var getCommonDir = require('commondir');
6
5
  var fs = require('fs');
6
+ var getCommonDir = require('commondir');
7
7
  var glob = require('glob');
8
8
  var estreeWalker = require('estree-walker');
9
9
  var MagicString = require('magic-string');
10
10
  var isReference = require('is-reference');
11
- var resolve = require('resolve');
12
11
 
13
12
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
13
 
@@ -17,8 +16,9 @@ var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
17
16
  var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
18
17
  var isReference__default = /*#__PURE__*/_interopDefaultLegacy(isReference);
19
18
 
19
+ var version = "22.0.0-1";
20
20
  var peerDependencies = {
21
- rollup: "^2.38.3"
21
+ rollup: "^2.60.0"
22
22
  };
23
23
 
24
24
  function tryParse(parse, code, id) {
@@ -85,271 +85,6 @@ function analyzeTopLevelStatements(parse, code, id) {
85
85
  return { isEsModule, hasDefaultExport, hasNamedExports, ast };
86
86
  }
87
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';
95
- const EXPORTS_SUFFIX = '?commonjs-exports';
96
- const MODULE_SUFFIX = '?commonjs-module';
97
-
98
- const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';
99
- const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
100
- const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
101
-
102
- const HELPERS_ID = '\0commonjsHelpers.js';
103
-
104
- // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
105
- // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
106
- // This will no longer be necessary once Rollup switches to ES6 output, likely
107
- // in Rollup 3
108
-
109
- const HELPERS = `
110
- export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
111
-
112
- export function getDefaultExportFromCjs (x) {
113
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
114
- }
115
-
116
- export function getDefaultExportFromNamespaceIfPresent (n) {
117
- return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
118
- }
119
-
120
- export function getDefaultExportFromNamespaceIfNotNamed (n) {
121
- return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
122
- }
123
-
124
- export function getAugmentedNamespace(n) {
125
- if (n.__esModule) return n;
126
- var a = Object.defineProperty({}, '__esModule', {value: true});
127
- Object.keys(n).forEach(function (k) {
128
- var d = Object.getOwnPropertyDescriptor(n, k);
129
- Object.defineProperty(a, k, d.get ? d : {
130
- enumerable: true,
131
- get: function () {
132
- return n[k];
133
- }
134
- });
135
- });
136
- return a;
137
- }
138
- `;
139
-
140
- const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
141
-
142
- const HELPER_NON_DYNAMIC = `
143
- export function commonjsRequire (path) {
144
- ${FAILED_REQUIRE_ERROR}
145
- }
146
- `;
147
-
148
- const getDynamicHelpers = (ignoreDynamicRequires) => `
149
- export function createModule(modulePath) {
150
- return {
151
- path: modulePath,
152
- exports: {},
153
- require: function (path, base) {
154
- return commonjsRequire(path, base == null ? modulePath : base);
155
- }
156
- };
157
- }
158
-
159
- export function commonjsRegister (path, loader) {
160
- DYNAMIC_REQUIRE_LOADERS[path] = loader;
161
- }
162
-
163
- export function commonjsRegisterOrShort (path, to) {
164
- const resolvedPath = commonjsResolveImpl(path, null, true);
165
- if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
166
- DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];
167
- } else {
168
- DYNAMIC_REQUIRE_SHORTS[path] = to;
169
- }
170
- }
171
-
172
- const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
173
- const DYNAMIC_REQUIRE_CACHE = Object.create(null);
174
- const DYNAMIC_REQUIRE_SHORTS = Object.create(null);
175
- const DEFAULT_PARENT_MODULE = {
176
- id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
177
- };
178
- const CHECKED_EXTENSIONS = ['', '.js', '.json'];
179
-
180
- function normalize (path) {
181
- path = path.replace(/\\\\/g, '/');
182
- const parts = path.split('/');
183
- const slashed = parts[0] === '';
184
- for (let i = 1; i < parts.length; i++) {
185
- if (parts[i] === '.' || parts[i] === '') {
186
- parts.splice(i--, 1);
187
- }
188
- }
189
- for (let i = 1; i < parts.length; i++) {
190
- if (parts[i] !== '..') continue;
191
- if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
192
- parts.splice(--i, 2);
193
- i--;
194
- }
195
- }
196
- path = parts.join('/');
197
- if (slashed && path[0] !== '/')
198
- path = '/' + path;
199
- else if (path.length === 0)
200
- path = '.';
201
- return path;
202
- }
203
-
204
- function join () {
205
- if (arguments.length === 0)
206
- return '.';
207
- let joined;
208
- for (let i = 0; i < arguments.length; ++i) {
209
- let arg = arguments[i];
210
- if (arg.length > 0) {
211
- if (joined === undefined)
212
- joined = arg;
213
- else
214
- joined += '/' + arg;
215
- }
216
- }
217
- if (joined === undefined)
218
- return '.';
219
-
220
- return joined;
221
- }
222
-
223
- function isPossibleNodeModulesPath (modulePath) {
224
- let c0 = modulePath[0];
225
- if (c0 === '/' || c0 === '\\\\') return false;
226
- let c1 = modulePath[1], c2 = modulePath[2];
227
- if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
228
- (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
229
- if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))
230
- return false;
231
- return true;
232
- }
233
-
234
- function dirname (path) {
235
- if (path.length === 0)
236
- return '.';
237
-
238
- let i = path.length - 1;
239
- while (i > 0) {
240
- const c = path.charCodeAt(i);
241
- if ((c === 47 || c === 92) && i !== path.length - 1)
242
- break;
243
- i--;
244
- }
245
-
246
- if (i > 0)
247
- return path.substr(0, i);
248
-
249
- if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
250
- return path.charAt(0);
251
-
252
- return '.';
253
- }
254
-
255
- export function commonjsResolveImpl (path, originalModuleDir, testCache) {
256
- const shouldTryNodeModules = isPossibleNodeModulesPath(path);
257
- path = normalize(path);
258
- let relPath;
259
- if (path[0] === '/') {
260
- originalModuleDir = '/';
261
- }
262
- while (true) {
263
- if (!shouldTryNodeModules) {
264
- relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
265
- } else if (originalModuleDir) {
266
- relPath = normalize(originalModuleDir + '/node_modules/' + path);
267
- } else {
268
- relPath = normalize(join('node_modules', path));
269
- }
270
-
271
- if (relPath.endsWith('/..')) {
272
- break; // Travelled too far up, avoid infinite loop
273
- }
274
-
275
- for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
276
- const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
277
- if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
278
- return resolvedPath;
279
- }
280
- if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {
281
- return resolvedPath;
282
- }
283
- if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
284
- return resolvedPath;
285
- }
286
- }
287
- if (!shouldTryNodeModules) break;
288
- const nextDir = normalize(originalModuleDir + '/..');
289
- if (nextDir === originalModuleDir) break;
290
- originalModuleDir = nextDir;
291
- }
292
- return null;
293
- }
294
-
295
- export function commonjsResolve (path, originalModuleDir) {
296
- const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
297
- if (resolvedPath !== null) {
298
- return resolvedPath;
299
- }
300
- return require.resolve(path);
301
- }
302
-
303
- export function commonjsRequire (path, originalModuleDir) {
304
- let resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
305
- if (resolvedPath !== null) {
306
- let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
307
- if (cachedModule) return cachedModule.exports;
308
- let shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];
309
- if (shortTo) {
310
- cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];
311
- if (cachedModule)
312
- return cachedModule.exports;
313
- resolvedPath = commonjsResolveImpl(shortTo, null, true);
314
- }
315
- const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
316
- if (loader) {
317
- DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
318
- id: resolvedPath,
319
- filename: resolvedPath,
320
- path: dirname(resolvedPath),
321
- exports: {},
322
- parent: DEFAULT_PARENT_MODULE,
323
- loaded: false,
324
- children: [],
325
- paths: [],
326
- require: function (path, base) {
327
- return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
328
- }
329
- };
330
- try {
331
- loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
332
- } catch (error) {
333
- delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
334
- throw error;
335
- }
336
- cachedModule.loaded = true;
337
- return cachedModule.exports;
338
- };
339
- }
340
- ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
341
- }
342
-
343
- commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
344
- commonjsRequire.resolve = commonjsResolve;
345
- `;
346
-
347
- function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) {
348
- return `${HELPERS}${
349
- isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC
350
- }`;
351
- }
352
-
353
88
  /* eslint-disable import/prefer-default-export */
354
89
 
355
90
  function deconflict(scopes, globals, identifier) {
@@ -382,13 +117,35 @@ function normalizePathSlashes(path) {
382
117
  return path.replace(/\\/g, '/');
383
118
  }
384
119
 
385
- const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
386
- const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
387
- const normalizedPath = normalizePathSlashes(path);
388
- return normalizedPath.startsWith(commonDir)
389
- ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
390
- : normalizedPath;
391
- };
120
+ const getVirtualPathForDynamicRequirePath = (path$1, commonDir) =>
121
+ `/${normalizePathSlashes(path.relative(commonDir, path$1))}`;
122
+
123
+ function capitalize(name) {
124
+ return name[0].toUpperCase() + name.slice(1);
125
+ }
126
+
127
+ function getStrictRequiresFilter({ strictRequires }) {
128
+ switch (strictRequires) {
129
+ case true:
130
+ return { strictRequiresFilter: () => true, detectCyclesAndConditional: false };
131
+ // eslint-disable-next-line no-undefined
132
+ case undefined:
133
+ case 'auto':
134
+ case 'debug':
135
+ case null:
136
+ return { strictRequiresFilter: () => false, detectCyclesAndConditional: true };
137
+ case false:
138
+ return { strictRequiresFilter: () => false, detectCyclesAndConditional: false };
139
+ default:
140
+ if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) {
141
+ return {
142
+ strictRequiresFilter: pluginutils.createFilter(strictRequires),
143
+ detectCyclesAndConditional: false
144
+ };
145
+ }
146
+ throw new Error('Unexpected value for "strictRequires" option.');
147
+ }
148
+ }
392
149
 
393
150
  function getPackageEntryPoint(dirPath) {
394
151
  let entryPoint = 'index.js';
@@ -406,41 +163,6 @@ function getPackageEntryPoint(dirPath) {
406
163
  return entryPoint;
407
164
  }
408
165
 
409
- function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
410
- let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`;
411
- for (const dir of dynamicRequireModuleDirPaths) {
412
- const entryPoint = getPackageEntryPoint(dir);
413
-
414
- code += `\ncommonjsRegisterOrShort(${JSON.stringify(
415
- getVirtualPathForDynamicRequirePath(dir, commonDir)
416
- )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(path.join(dir, entryPoint), commonDir))});`;
417
- }
418
- return code;
419
- }
420
-
421
- function getDynamicPackagesEntryIntro(
422
- dynamicRequireModuleDirPaths,
423
- dynamicRequireModuleSet
424
- ) {
425
- let dynamicImports = Array.from(
426
- dynamicRequireModuleSet,
427
- (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`
428
- ).join('\n');
429
-
430
- if (dynamicRequireModuleDirPaths.length) {
431
- dynamicImports += `require(${JSON.stringify(
432
- wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)
433
- )});`;
434
- }
435
-
436
- return dynamicImports;
437
- }
438
-
439
- function isDynamicModuleImport(id, dynamicRequireModuleSet) {
440
- const normalizedPath = normalizePathSlashes(id);
441
- return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
442
- }
443
-
444
166
  function isDirectory(path) {
445
167
  try {
446
168
  if (fs.statSync(path).isDirectory()) return true;
@@ -450,102 +172,250 @@ function isDirectory(path) {
450
172
  return false;
451
173
  }
452
174
 
453
- function getDynamicRequirePaths(patterns) {
454
- const dynamicRequireModuleSet = new Set();
175
+ function getDynamicRequireModules(patterns, dynamicRequireRoot) {
176
+ const dynamicRequireModules = new Map();
177
+ const dirNames = new Set();
455
178
  for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
456
179
  const isNegated = pattern.startsWith('!');
457
- const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
458
- for (const path$1 of glob__default['default'].sync(isNegated ? pattern.substr(1) : pattern)) {
459
- modifySet(normalizePathSlashes(path.resolve(path$1)));
460
- if (isDirectory(path$1)) {
461
- modifySet(normalizePathSlashes(path.resolve(path.join(path$1, getPackageEntryPoint(path$1)))));
180
+ const modifyMap = (targetPath, resolvedPath) =>
181
+ isNegated
182
+ ? dynamicRequireModules.delete(targetPath)
183
+ : dynamicRequireModules.set(targetPath, resolvedPath);
184
+ for (const path$1 of glob__default["default"].sync(isNegated ? pattern.substr(1) : pattern)) {
185
+ const resolvedPath = path.resolve(path$1);
186
+ const requirePath = normalizePathSlashes(resolvedPath);
187
+ if (isDirectory(resolvedPath)) {
188
+ dirNames.add(resolvedPath);
189
+ const modulePath = path.resolve(path.join(resolvedPath, getPackageEntryPoint(path$1)));
190
+ modifyMap(requirePath, modulePath);
191
+ modifyMap(normalizePathSlashes(modulePath), modulePath);
192
+ } else {
193
+ dirNames.add(path.dirname(resolvedPath));
194
+ modifyMap(requirePath, resolvedPath);
462
195
  }
463
196
  }
464
197
  }
465
- const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>
466
- isDirectory(path)
467
- );
468
- return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
198
+ return {
199
+ commonDir: dirNames.size ? getCommonDir__default["default"]([...dirNames, dynamicRequireRoot]) : null,
200
+ dynamicRequireModules
201
+ };
469
202
  }
470
203
 
471
- function getCommonJSMetaPromise(commonJSMetaPromises, id) {
472
- let commonJSMetaPromise = commonJSMetaPromises.get(id);
473
- if (commonJSMetaPromise) return commonJSMetaPromise.promise;
204
+ const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
474
205
 
475
- const promise = new Promise((resolve) => {
476
- commonJSMetaPromise = {
477
- resolve,
478
- promise: null
479
- };
480
- commonJSMetaPromises.set(id, commonJSMetaPromise);
481
- });
482
- commonJSMetaPromise.promise = promise;
206
+ function getDynamicModuleRegistry(
207
+ isDynamicRequireModulesEnabled,
208
+ dynamicRequireModules,
209
+ commonDir,
210
+ ignoreDynamicRequires
211
+ ) {
212
+ if (!isDynamicRequireModulesEnabled) {
213
+ return `export function commonjsRequire(path) {
214
+ ${FAILED_REQUIRE_ERROR}
215
+ }`;
216
+ }
217
+ const dynamicModuleImports = [...dynamicRequireModules.values()]
218
+ .map(
219
+ (id, index) =>
220
+ `import ${
221
+ id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }`
222
+ } from ${JSON.stringify(id)};`
223
+ )
224
+ .join('\n');
225
+ const dynamicModuleProps = [...dynamicRequireModules.keys()]
226
+ .map(
227
+ (id, index) =>
228
+ `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${
229
+ id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}`
230
+ }`
231
+ )
232
+ .join(',\n');
233
+ return `${dynamicModuleImports}
234
+
235
+ var dynamicModules;
236
+
237
+ function getDynamicModules() {
238
+ return dynamicModules || (dynamicModules = {
239
+ ${dynamicModuleProps}
240
+ });
241
+ }
483
242
 
484
- return promise;
243
+ export function commonjsRequire(path, originalModuleDir) {
244
+ var resolvedPath = commonjsResolveImpl(path, originalModuleDir);
245
+ if (resolvedPath !== null) {
246
+ return getDynamicModules()[resolvedPath]();
247
+ }
248
+ ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
485
249
  }
486
250
 
487
- function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) {
488
- const commonJSMetaPromise = commonJSMetaPromises.get(id);
489
- if (commonJSMetaPromise) {
490
- if (commonJSMetaPromise.resolve) {
491
- commonJSMetaPromise.resolve(commonjsMeta);
492
- commonJSMetaPromise.resolve = null;
493
- }
494
- } else {
495
- commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });
496
- }
251
+ function commonjsResolve (path, originalModuleDir) {
252
+ const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
253
+ if (resolvedPath !== null) {
254
+ return resolvedPath;
255
+ }
256
+ return require.resolve(path);
497
257
  }
498
258
 
499
- // e.g. id === "commonjsHelpers?commonjsRegister"
500
- function getSpecificHelperProxy(id) {
501
- return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
259
+ commonjsRequire.resolve = commonjsResolve;
260
+
261
+ function commonjsResolveImpl (path, originalModuleDir) {
262
+ var shouldTryNodeModules = isPossibleNodeModulesPath(path);
263
+ path = normalize(path);
264
+ var relPath;
265
+ if (path[0] === '/') {
266
+ originalModuleDir = '';
267
+ }
268
+ var modules = getDynamicModules();
269
+ var checkedExtensions = ['', '.js', '.json'];
270
+ while (true) {
271
+ if (!shouldTryNodeModules) {
272
+ relPath = normalize(originalModuleDir + '/' + path);
273
+ } else {
274
+ relPath = normalize(originalModuleDir + '/node_modules/' + path);
275
+ }
276
+
277
+ if (relPath.endsWith('/..')) {
278
+ break; // Travelled too far up, avoid infinite loop
279
+ }
280
+
281
+ for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
282
+ var resolvedPath = relPath + checkedExtensions[extensionIndex];
283
+ if (modules[resolvedPath]) {
284
+ return resolvedPath;
285
+ }
286
+ }
287
+ if (!shouldTryNodeModules) break;
288
+ var nextDir = normalize(originalModuleDir + '/..');
289
+ if (nextDir === originalModuleDir) break;
290
+ originalModuleDir = nextDir;
291
+ }
292
+ return null;
293
+ }
294
+
295
+ function isPossibleNodeModulesPath (modulePath) {
296
+ var c0 = modulePath[0];
297
+ if (c0 === '/' || c0 === '\\\\') return false;
298
+ var c1 = modulePath[1], c2 = modulePath[2];
299
+ if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
300
+ (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
301
+ if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
302
+ return true;
303
+ }
304
+
305
+ function normalize (path) {
306
+ path = path.replace(/\\\\/g, '/');
307
+ var parts = path.split('/');
308
+ var slashed = parts[0] === '';
309
+ for (var i = 1; i < parts.length; i++) {
310
+ if (parts[i] === '.' || parts[i] === '') {
311
+ parts.splice(i--, 1);
312
+ }
313
+ }
314
+ for (var i = 1; i < parts.length; i++) {
315
+ if (parts[i] !== '..') continue;
316
+ if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
317
+ parts.splice(--i, 2);
318
+ i--;
319
+ }
320
+ }
321
+ path = parts.join('/');
322
+ if (slashed && path[0] !== '/') path = '/' + path;
323
+ else if (path.length === 0) path = '.';
324
+ return path;
325
+ }`;
326
+ }
327
+
328
+ const isWrappedId = (id, suffix) => id.endsWith(suffix);
329
+ const wrapId = (id, suffix) => `\0${id}${suffix}`;
330
+ const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
331
+
332
+ const PROXY_SUFFIX = '?commonjs-proxy';
333
+ const WRAPPED_SUFFIX = '?commonjs-wrapped';
334
+ const EXTERNAL_SUFFIX = '?commonjs-external';
335
+ const EXPORTS_SUFFIX = '?commonjs-exports';
336
+ const MODULE_SUFFIX = '?commonjs-module';
337
+ const ES_IMPORT_SUFFIX = '?es-import';
338
+
339
+ const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
340
+ const HELPERS_ID = '\0commonjsHelpers.js';
341
+
342
+ const IS_WRAPPED_COMMONJS = 'withRequireFunction';
343
+
344
+ // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
345
+ // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
346
+ // This could be improved by inspecting Rollup's "generatedCode" option
347
+
348
+ const HELPERS = `
349
+ export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
350
+
351
+ export function getDefaultExportFromCjs (x) {
352
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
353
+ }
354
+
355
+ export function getDefaultExportFromNamespaceIfPresent (n) {
356
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
357
+ }
358
+
359
+ export function getDefaultExportFromNamespaceIfNotNamed (n) {
360
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
361
+ }
362
+
363
+ export function getAugmentedNamespace(n) {
364
+ var f = n.default;
365
+ if (typeof f == "function") {
366
+ var a = function () {
367
+ return f.apply(this, arguments);
368
+ };
369
+ a.prototype = f.prototype;
370
+ } else a = {};
371
+ Object.defineProperty(a, '__esModule', {value: true});
372
+ Object.keys(n).forEach(function (k) {
373
+ var d = Object.getOwnPropertyDescriptor(n, k);
374
+ Object.defineProperty(a, k, d.get ? d : {
375
+ enumerable: true,
376
+ get: function () {
377
+ return n[k];
378
+ }
379
+ });
380
+ });
381
+ return a;
382
+ }
383
+ `;
384
+
385
+ function getHelpersModule() {
386
+ return HELPERS;
502
387
  }
503
388
 
504
389
  function getUnknownRequireProxy(id, requireReturnsDefault) {
505
390
  if (requireReturnsDefault === true || id.endsWith('.json')) {
506
- return `export {default} from ${JSON.stringify(id)};`;
391
+ return `export { default } from ${JSON.stringify(id)};`;
507
392
  }
508
393
  const name = getName(id);
509
394
  const exported =
510
395
  requireReturnsDefault === 'auto'
511
- ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
396
+ ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
512
397
  : requireReturnsDefault === 'preferred'
513
- ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
398
+ ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
514
399
  : !requireReturnsDefault
515
- ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
400
+ ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
516
401
  : `export default ${name};`;
517
402
  return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
518
403
  }
519
404
 
520
- function getDynamicJsonProxy(id, commonDir) {
521
- const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
522
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
523
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
524
- )}, function (module, exports) {
525
- module.exports = require(${JSON.stringify(normalizedPath)});
526
- });`;
527
- }
528
-
529
- function getDynamicRequireProxy(normalizedPath, commonDir) {
530
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
531
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
532
- )}, function (module, exports) {
533
- ${fs.readFileSync(normalizedPath, { encoding: 'utf8' })}
534
- });`;
535
- }
536
-
537
405
  async function getStaticRequireProxy(
538
406
  id,
539
407
  requireReturnsDefault,
540
408
  esModulesWithDefaultExport,
541
409
  esModulesWithNamedExports,
542
- commonJsMetaPromises
410
+ loadModule
543
411
  ) {
544
412
  const name = getName(id);
545
- const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id);
413
+ const {
414
+ meta: { commonjs: commonjsMeta }
415
+ } = await loadModule({ id });
546
416
  if (commonjsMeta && commonjsMeta.isCommonJS) {
547
417
  return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
548
- } else if (commonjsMeta === null) {
418
+ } else if (!commonjsMeta) {
549
419
  return getUnknownRequireProxy(id, requireReturnsDefault);
550
420
  } else if (!requireReturnsDefault) {
551
421
  return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
@@ -562,6 +432,27 @@ async function getStaticRequireProxy(
562
432
  return `export { default } from ${JSON.stringify(id)};`;
563
433
  }
564
434
 
435
+ function getEsImportProxy(id, defaultIsModuleExports) {
436
+ const name = getName(id);
437
+ const exportsName = `${name}Exports`;
438
+ const requireModule = `require${capitalize(name)}`;
439
+ let code =
440
+ `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` +
441
+ `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` +
442
+ `var ${exportsName} = ${requireModule}();\n` +
443
+ `export { ${exportsName} as __moduleExports };`;
444
+ if (defaultIsModuleExports) {
445
+ code += `\nexport { ${exportsName} as default };`;
446
+ } else {
447
+ code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
448
+ }
449
+ return {
450
+ code,
451
+ syntheticNamedExports: '__moduleExports',
452
+ meta: { commonjs: { isCommonJS: false } }
453
+ };
454
+ }
455
+
565
456
  /* eslint-disable no-param-reassign, no-undefined */
566
457
 
567
458
  function getCandidatesForExtension(resolved, extension) {
@@ -575,86 +466,216 @@ function getCandidates(resolved, extensions) {
575
466
  );
576
467
  }
577
468
 
469
+ function resolveExtensions(importee, importer, extensions) {
470
+ // not our problem
471
+ if (importee[0] !== '.' || !importer) return undefined;
472
+
473
+ const resolved = path.resolve(path.dirname(importer), importee);
474
+ const candidates = getCandidates(resolved, extensions);
475
+
476
+ for (let i = 0; i < candidates.length; i += 1) {
477
+ try {
478
+ const stats = fs.statSync(candidates[i]);
479
+ if (stats.isFile()) return { id: candidates[i] };
480
+ } catch (err) {
481
+ /* noop */
482
+ }
483
+ }
484
+
485
+ return undefined;
486
+ }
487
+
578
488
  function getResolveId(extensions) {
579
- function resolveExtensions(importee, importer) {
580
- // not our problem
581
- if (importee[0] !== '.' || !importer) return undefined;
489
+ return async function resolveId(importee, importer, resolveOptions) {
490
+ if (
491
+ resolveOptions.custom &&
492
+ resolveOptions.custom.commonjs &&
493
+ resolveOptions.custom.commonjs.skipResolver
494
+ ) {
495
+ return null;
496
+ }
497
+ if (isWrappedId(importee, WRAPPED_SUFFIX)) {
498
+ return unwrapId(importee, WRAPPED_SUFFIX);
499
+ }
582
500
 
583
- const resolved = path.resolve(path.dirname(importer), importee);
584
- const candidates = getCandidates(resolved, extensions);
501
+ if (
502
+ isWrappedId(importee, MODULE_SUFFIX) ||
503
+ isWrappedId(importee, EXPORTS_SUFFIX) ||
504
+ isWrappedId(importee, PROXY_SUFFIX) ||
505
+ isWrappedId(importee, ES_IMPORT_SUFFIX) ||
506
+ isWrappedId(importee, EXTERNAL_SUFFIX) ||
507
+ importee.startsWith(HELPERS_ID) ||
508
+ importee === DYNAMIC_MODULES_ID
509
+ ) {
510
+ return importee;
511
+ }
585
512
 
586
- for (let i = 0; i < candidates.length; i += 1) {
587
- try {
588
- const stats = fs.statSync(candidates[i]);
589
- if (stats.isFile()) return { id: candidates[i] };
590
- } catch (err) {
591
- /* noop */
513
+ if (importer) {
514
+ if (
515
+ importer === DYNAMIC_MODULES_ID ||
516
+ // Proxies are only importing resolved ids, no need to resolve again
517
+ isWrappedId(importer, PROXY_SUFFIX) ||
518
+ isWrappedId(importer, ES_IMPORT_SUFFIX)
519
+ ) {
520
+ return importee;
521
+ }
522
+ if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
523
+ // We need to return null for unresolved imports so that the proper warning is shown
524
+ if (!(await this.resolve(importee, importer, { skipSelf: true }))) {
525
+ return null;
526
+ }
527
+ // For other external imports, we need to make sure they are handled as external
528
+ return { id: importee, external: true };
592
529
  }
593
530
  }
594
531
 
595
- return undefined;
596
- }
597
-
598
- return function resolveId(importee, rawImporter) {
599
- if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
600
- return importee;
532
+ if (importee.startsWith('\0')) {
533
+ return null;
601
534
  }
602
535
 
603
- const importer =
604
- rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
605
- ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
606
- : rawImporter;
536
+ // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
537
+ // if that is the case, we need to add a proxy.
538
+ const customOptions = resolveOptions.custom;
607
539
 
608
- // Except for exports, proxies are only importing resolved ids,
609
- // no need to resolve again
610
- if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
611
- return importee;
540
+ // If this is a require, we do not need a proxy
541
+ if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
542
+ return null;
612
543
  }
613
544
 
614
- const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
615
- const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
616
- let isModuleRegistration = false;
545
+ const resolved =
546
+ (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
547
+ resolveExtensions(importee, importer, extensions);
548
+ if (!resolved || resolved.external) {
549
+ return resolved;
550
+ }
551
+ const {
552
+ meta: { commonjs: commonjsMeta }
553
+ } = await this.load(resolved);
554
+ if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
555
+ return wrapId(resolved.id, ES_IMPORT_SUFFIX);
556
+ }
557
+ return resolved;
558
+ };
559
+ }
617
560
 
618
- if (isProxyModule) {
619
- importee = unwrapId(importee, PROXY_SUFFIX);
620
- } else if (isRequiredModule) {
621
- importee = unwrapId(importee, REQUIRE_SUFFIX);
561
+ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional) {
562
+ const knownCjsModuleTypes = Object.create(null);
563
+ const requiredIds = Object.create(null);
564
+ const unconditionallyRequiredIds = Object.create(null);
565
+ const parentModules = Object.create(null);
566
+ const childModules = Object.create(null);
567
+ const getParentModules = (id) => parentModules[id] || (parentModules[id] = Object.create(null));
568
+ const getChildModules = (id) => childModules[id] || (childModules[id] = Object.create(null));
622
569
 
623
- isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
624
- if (isModuleRegistration) {
625
- importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
570
+ return {
571
+ getWrappedIds: () =>
572
+ Object.keys(knownCjsModuleTypes).filter(
573
+ (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
574
+ ),
575
+ isRequiredId: (id) => requiredIds[id],
576
+ resolveRequireSourcesAndGetMeta: (rollupContext) => async (
577
+ parentId,
578
+ isParentCommonJS,
579
+ sources
580
+ ) => {
581
+ knownCjsModuleTypes[parentId] = knownCjsModuleTypes[parentId] || isParentCommonJS;
582
+ if (
583
+ knownCjsModuleTypes[parentId] &&
584
+ requiredIds[parentId] &&
585
+ !unconditionallyRequiredIds[parentId]
586
+ ) {
587
+ knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
626
588
  }
627
- }
589
+ const requireTargets = await Promise.all(
590
+ sources.map(async ({ source, isConditional }) => {
591
+ // Never analyze or proxy internal modules
592
+ if (source.startsWith('\0')) {
593
+ return { id: source, allowProxy: false };
594
+ }
595
+ const resolved =
596
+ (await rollupContext.resolve(source, parentId, {
597
+ custom: {
598
+ 'node-resolve': { isRequire: true },
599
+ commonjs: { skipResolver: true }
600
+ }
601
+ })) || resolveExtensions(source, parentId, extensions);
602
+ if (!resolved) {
603
+ return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
604
+ }
605
+ const childId = resolved.id;
606
+ if (resolved.external) {
607
+ return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
608
+ }
609
+ requiredIds[childId] = true;
610
+ if (
611
+ !(
612
+ detectCyclesAndConditional &&
613
+ (isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)
614
+ )
615
+ ) {
616
+ unconditionallyRequiredIds[childId] = true;
617
+ }
618
+ const parentDependentModules = getParentModules(parentId);
619
+ const childDependentModules = getParentModules(childId);
628
620
 
629
- if (
630
- importee.startsWith(HELPERS_ID) ||
631
- importee === DYNAMIC_PACKAGES_ID ||
632
- importee.startsWith(DYNAMIC_JSON_PREFIX)
633
- ) {
634
- return importee;
635
- }
621
+ // Copy the parents of the current parent to the child
622
+ for (const dependentId of Object.keys(parentDependentModules)) {
623
+ childDependentModules[dependentId] = true;
624
+ }
636
625
 
637
- if (importee.startsWith('\0')) {
638
- return null;
639
- }
626
+ // Add the current parent to the child as well. If the child module already has known
627
+ // dependencies because it has already been loaded, add the current parent module to their
628
+ // parent modules
629
+ childDependentModules[parentId] = true;
630
+ const dependenciesToUpdate = new Set(Object.keys(getChildModules(childId)));
631
+ for (const dependencyId of dependenciesToUpdate) {
632
+ getParentModules(dependencyId)[parentId] = true;
633
+ for (const subDependencyId of Object.keys(getChildModules(dependencyId))) {
634
+ dependenciesToUpdate.add(subDependencyId);
635
+ }
636
+ }
640
637
 
641
- return this.resolve(importee, importer, {
642
- skipSelf: true,
643
- custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
644
- }).then((resolved) => {
645
- if (!resolved) {
646
- resolved = resolveExtensions(importee, importer);
647
- }
648
- if (resolved && isProxyModule) {
649
- resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
650
- resolved.external = false;
651
- } else if (resolved && isModuleRegistration) {
652
- resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
653
- } else if (!resolved && (isProxyModule || isRequiredModule)) {
654
- return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
655
- }
656
- return resolved;
657
- });
638
+ // Add the child as a dependency to the parent
639
+ getChildModules(parentId)[childId] = true;
640
+
641
+ // If we depend on one of our dependencies, we have a cycle. Then all modules that
642
+ // we depend on that also depend on the same module are part of a cycle as well. Trying
643
+ // to wait for loading this module would lead to a deadlock.
644
+ if (parentDependentModules[childId]) {
645
+ if (detectCyclesAndConditional && isParentCommonJS) {
646
+ knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
647
+ knownCjsModuleTypes[childId] = IS_WRAPPED_COMMONJS;
648
+ for (const dependentId of Object.keys(parentDependentModules)) {
649
+ if (getParentModules(dependentId)[childId]) {
650
+ knownCjsModuleTypes[dependentId] = IS_WRAPPED_COMMONJS;
651
+ }
652
+ }
653
+ }
654
+ } else {
655
+ // This makes sure the current transform handler waits for all direct dependencies to be
656
+ // loaded and transformed and therefore for all transitive CommonJS dependencies to be
657
+ // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
658
+ await rollupContext.load(resolved);
659
+ }
660
+ return { id: childId, allowProxy: true };
661
+ })
662
+ );
663
+ return {
664
+ requireTargets: requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
665
+ const isCommonJS = knownCjsModuleTypes[dependencyId];
666
+ return {
667
+ source: sources[index].source,
668
+ id: allowProxy
669
+ ? isCommonJS === IS_WRAPPED_COMMONJS
670
+ ? wrapId(dependencyId, WRAPPED_SUFFIX)
671
+ : wrapId(dependencyId, PROXY_SUFFIX)
672
+ : dependencyId,
673
+ isCommonJS
674
+ };
675
+ }),
676
+ usesRequireWrapper: knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS
677
+ };
678
+ }
658
679
  };
659
680
  }
660
681
 
@@ -814,8 +835,9 @@ function wrapCode(magicString, uses, moduleName, exportsName) {
814
835
  }
815
836
  magicString
816
837
  .trim()
838
+ .indent('\t')
817
839
  .prepend(`(function (${args.join(', ')}) {\n`)
818
- .append(`\n}(${passedArgs.join(', ')}));`);
840
+ .append(`\n} (${passedArgs.join(', ')}));`);
819
841
  }
820
842
 
821
843
  function rewriteExportsAndGetExportsBlock(
@@ -833,12 +855,27 @@ function rewriteExportsAndGetExportsBlock(
833
855
  HELPERS_NAME,
834
856
  exportMode,
835
857
  detectWrappedDefault,
836
- defaultIsModuleExports
858
+ defaultIsModuleExports,
859
+ usesRequireWrapper,
860
+ requireName
837
861
  ) {
838
862
  const exports = [];
839
863
  const exportDeclarations = [];
840
864
 
841
- if (exportMode === 'replace') {
865
+ if (usesRequireWrapper) {
866
+ getExportsWhenUsingRequireWrapper(
867
+ magicString,
868
+ wrapped,
869
+ exportMode,
870
+ exports,
871
+ moduleExportsAssignments,
872
+ exportsAssignmentsByName,
873
+ moduleName,
874
+ exportsName,
875
+ requireName,
876
+ defineCompiledEsmExpressions
877
+ );
878
+ } else if (exportMode === 'replace') {
842
879
  getExportsForReplacedModuleExports(
843
880
  magicString,
844
881
  exports,
@@ -881,6 +918,49 @@ function rewriteExportsAndGetExportsBlock(
881
918
  return `\n\n${exportDeclarations.join('\n')}`;
882
919
  }
883
920
 
921
+ function getExportsWhenUsingRequireWrapper(
922
+ magicString,
923
+ wrapped,
924
+ exportMode,
925
+ exports,
926
+ moduleExportsAssignments,
927
+ exportsAssignmentsByName,
928
+ moduleName,
929
+ exportsName,
930
+ requireName,
931
+ defineCompiledEsmExpressions
932
+ ) {
933
+ if (!wrapped) {
934
+ if (exportMode === 'replace') {
935
+ for (const { left } of moduleExportsAssignments) {
936
+ magicString.overwrite(left.start, left.end, exportsName);
937
+ }
938
+ } else {
939
+ // Collect and rewrite module.exports assignments
940
+ for (const { left } of moduleExportsAssignments) {
941
+ magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
942
+ }
943
+ // Collect and rewrite named exports
944
+ for (const [exportName, { nodes }] of exportsAssignmentsByName) {
945
+ for (const node of nodes) {
946
+ magicString.overwrite(node.start, node.left.end, `${exportsName}.${exportName}`);
947
+ }
948
+ }
949
+ // Collect and rewrite exports.__esModule assignments
950
+ for (const expression of defineCompiledEsmExpressions) {
951
+ const moduleExportsExpression =
952
+ expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
953
+ magicString.overwrite(
954
+ moduleExportsExpression.start,
955
+ moduleExportsExpression.end,
956
+ exportsName
957
+ );
958
+ }
959
+ }
960
+ }
961
+ exports.push(`${requireName} as __require`);
962
+ }
963
+
884
964
  function getExportsForReplacedModuleExports(
885
965
  magicString,
886
966
  exports,
@@ -968,7 +1048,7 @@ function getExports(
968
1048
  }
969
1049
 
970
1050
  if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
971
- exportDeclarations.push(`export default ${exportsName};`);
1051
+ exports.push(`${exportsName} as default`);
972
1052
  } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
973
1053
  exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
974
1054
  } else {
@@ -978,7 +1058,7 @@ function getExports(
978
1058
  }
979
1059
  }
980
1060
 
981
- function isRequireStatement(node, scope) {
1061
+ function isRequireExpression(node, scope) {
982
1062
  if (!node) return false;
983
1063
  if (node.type !== 'CallExpression') return false;
984
1064
 
@@ -1005,11 +1085,6 @@ function isModuleRequire({ object, property }, scope) {
1005
1085
  );
1006
1086
  }
1007
1087
 
1008
- function isStaticRequireStatement(node, scope) {
1009
- if (!isRequireStatement(node, scope)) return false;
1010
- return !hasDynamicArguments(node);
1011
- }
1012
-
1013
1088
  function hasDynamicArguments(node) {
1014
1089
  return (
1015
1090
  node.arguments.length > 1 ||
@@ -1024,89 +1099,58 @@ function isNodeRequirePropertyAccess(parent) {
1024
1099
  return parent && parent.property && reservedMethod[parent.property.name];
1025
1100
  }
1026
1101
 
1027
- function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
1028
- return ignoreRequire(requiredNode.arguments[0].value);
1029
- }
1030
-
1031
1102
  function getRequireStringArg(node) {
1032
1103
  return node.arguments[0].type === 'Literal'
1033
1104
  ? node.arguments[0].value
1034
1105
  : node.arguments[0].quasis[0].value.cooked;
1035
1106
  }
1036
1107
 
1037
- function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
1038
- if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
1039
- try {
1040
- const resolvedPath = normalizePathSlashes(resolve.sync(source, { basedir: path.dirname(id) }));
1041
- if (dynamicRequireModuleSet.has(resolvedPath)) {
1042
- return true;
1043
- }
1044
- } catch (ex) {
1045
- // Probably a node.js internal module
1046
- return false;
1047
- }
1048
-
1049
- return false;
1050
- }
1051
-
1052
- for (const attemptExt of ['', '.js', '.json']) {
1053
- const resolvedPath = normalizePathSlashes(path.resolve(path.dirname(id), source + attemptExt));
1054
- if (dynamicRequireModuleSet.has(resolvedPath)) {
1055
- return true;
1056
- }
1057
- }
1058
-
1059
- return false;
1060
- }
1061
-
1062
1108
  function getRequireHandlers() {
1063
- const requiredSources = [];
1064
- const requiredBySource = Object.create(null);
1065
- const requiredByNode = new Map();
1066
- const requireExpressionsWithUsedReturnValue = [];
1067
-
1068
- function addRequireStatement(sourceId, node, scope, usesReturnValue) {
1069
- const required = getRequired(sourceId);
1070
- requiredByNode.set(node, { scope, required });
1071
- if (usesReturnValue) {
1072
- required.nodesUsingRequired.push(node);
1073
- requireExpressionsWithUsedReturnValue.push(node);
1074
- }
1075
- }
1076
-
1077
- function getRequired(sourceId) {
1078
- if (!requiredBySource[sourceId]) {
1079
- requiredSources.push(sourceId);
1080
-
1081
- requiredBySource[sourceId] = {
1082
- source: sourceId,
1083
- name: null,
1084
- nodesUsingRequired: []
1085
- };
1086
- }
1087
-
1088
- return requiredBySource[sourceId];
1109
+ const requireExpressions = [];
1110
+
1111
+ function addRequireStatement(
1112
+ sourceId,
1113
+ node,
1114
+ scope,
1115
+ usesReturnValue,
1116
+ isInsideTryBlock,
1117
+ isInsideConditional,
1118
+ toBeRemoved
1119
+ ) {
1120
+ requireExpressions.push({
1121
+ sourceId,
1122
+ node,
1123
+ scope,
1124
+ usesReturnValue,
1125
+ isInsideTryBlock,
1126
+ isInsideConditional,
1127
+ toBeRemoved
1128
+ });
1089
1129
  }
1090
1130
 
1091
- function rewriteRequireExpressionsAndGetImportBlock(
1131
+ async function rewriteRequireExpressionsAndGetImportBlock(
1092
1132
  magicString,
1093
1133
  topLevelDeclarations,
1094
- topLevelRequireDeclarators,
1095
1134
  reassignedNames,
1096
1135
  helpersName,
1097
- dynamicRegisterSources,
1136
+ dynamicRequireName,
1098
1137
  moduleName,
1099
1138
  exportsName,
1100
1139
  id,
1101
- exportMode
1140
+ exportMode,
1141
+ resolveRequireSourcesAndGetMeta,
1142
+ needsRequireWrapper,
1143
+ isEsModule,
1144
+ usesRequire,
1145
+ getIgnoreTryCatchRequireStatementMode
1102
1146
  ) {
1103
- setRemainingImportNamesAndRewriteRequires(
1104
- requireExpressionsWithUsedReturnValue,
1105
- requiredByNode,
1106
- magicString
1107
- );
1108
1147
  const imports = [];
1109
1148
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1149
+ if (usesRequire) {
1150
+ imports.push(
1151
+ `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1152
+ );
1153
+ }
1110
1154
  if (exportMode === 'module') {
1111
1155
  imports.push(
1112
1156
  `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
@@ -1118,58 +1162,115 @@ function getRequireHandlers() {
1118
1162
  `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
1119
1163
  );
1120
1164
  }
1121
- for (const source of dynamicRegisterSources) {
1122
- imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1123
- }
1124
- for (const source of requiredSources) {
1125
- if (!source.startsWith('\0')) {
1126
- imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1127
- }
1128
- const { name, nodesUsingRequired } = requiredBySource[source];
1129
- imports.push(
1130
- `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
1131
- source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
1132
- )};`
1133
- );
1134
- }
1135
- return imports.length ? `${imports.join('\n')}\n\n` : '';
1165
+ const requiresBySource = collectSources(requireExpressions);
1166
+ const { requireTargets, usesRequireWrapper } = await resolveRequireSourcesAndGetMeta(
1167
+ id,
1168
+ needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1169
+ Object.keys(requiresBySource).map((source) => {
1170
+ return {
1171
+ source,
1172
+ isConditional: requiresBySource[source].every((require) => require.isInsideConditional)
1173
+ };
1174
+ })
1175
+ );
1176
+ processRequireExpressions(
1177
+ imports,
1178
+ requireTargets,
1179
+ requiresBySource,
1180
+ getIgnoreTryCatchRequireStatementMode,
1181
+ magicString
1182
+ );
1183
+ return {
1184
+ importBlock: imports.length ? `${imports.join('\n')}\n\n` : '',
1185
+ usesRequireWrapper
1186
+ };
1136
1187
  }
1137
1188
 
1138
1189
  return {
1139
1190
  addRequireStatement,
1140
- requiredSources,
1141
1191
  rewriteRequireExpressionsAndGetImportBlock
1142
1192
  };
1143
1193
  }
1144
1194
 
1145
- function setRemainingImportNamesAndRewriteRequires(
1146
- requireExpressionsWithUsedReturnValue,
1147
- requiredByNode,
1195
+ function collectSources(requireExpressions) {
1196
+ const requiresBySource = Object.create(null);
1197
+ for (const requireExpression of requireExpressions) {
1198
+ const { sourceId } = requireExpression;
1199
+ if (!requiresBySource[sourceId]) {
1200
+ requiresBySource[sourceId] = [];
1201
+ }
1202
+ const requires = requiresBySource[sourceId];
1203
+ requires.push(requireExpression);
1204
+ }
1205
+ return requiresBySource;
1206
+ }
1207
+
1208
+ function processRequireExpressions(
1209
+ imports,
1210
+ requireTargets,
1211
+ requiresBySource,
1212
+ getIgnoreTryCatchRequireStatementMode,
1148
1213
  magicString
1149
1214
  ) {
1150
- let uid = 0;
1151
- for (const requireExpression of requireExpressionsWithUsedReturnValue) {
1152
- const { required } = requiredByNode.get(requireExpression);
1153
- if (!required.name) {
1154
- let potentialName;
1155
- const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
1156
- do {
1157
- potentialName = `require$$${uid}`;
1158
- uid += 1;
1159
- } while (required.nodesUsingRequired.some(isUsedName));
1160
- required.name = potentialName;
1215
+ const generateRequireName = getGenerateRequireName();
1216
+ for (const { source, id: resolvedId, isCommonJS } of requireTargets) {
1217
+ const requires = requiresBySource[source];
1218
+ const name = generateRequireName(requires);
1219
+ let usesRequired = false;
1220
+ let needsImport = false;
1221
+ for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
1222
+ const { canConvertRequire, shouldRemoveRequire } =
1223
+ isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX)
1224
+ ? getIgnoreTryCatchRequireStatementMode(source)
1225
+ : { canConvertRequire: true, shouldRemoveRequire: false };
1226
+ if (shouldRemoveRequire) {
1227
+ if (usesReturnValue) {
1228
+ magicString.overwrite(node.start, node.end, 'undefined');
1229
+ } else {
1230
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1231
+ }
1232
+ } else if (canConvertRequire) {
1233
+ needsImport = true;
1234
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1235
+ magicString.overwrite(node.start, node.end, `${name}()`);
1236
+ } else if (usesReturnValue) {
1237
+ usesRequired = true;
1238
+ magicString.overwrite(node.start, node.end, name);
1239
+ } else {
1240
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1241
+ }
1242
+ }
1243
+ }
1244
+ if (needsImport) {
1245
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1246
+ imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)};`);
1247
+ } else {
1248
+ imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)};`);
1249
+ }
1161
1250
  }
1162
- magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
1163
1251
  }
1164
1252
  }
1165
1253
 
1254
+ function getGenerateRequireName() {
1255
+ let uid = 0;
1256
+ return (requires) => {
1257
+ let name;
1258
+ const hasNameConflict = ({ scope }) => scope.contains(name);
1259
+ do {
1260
+ name = `require$$${uid}`;
1261
+ uid += 1;
1262
+ } while (requires.some(hasNameConflict));
1263
+ return name;
1264
+ };
1265
+ }
1266
+
1166
1267
  /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
1167
1268
 
1168
1269
  const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
1169
1270
 
1170
1271
  const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
1171
1272
 
1172
- function transformCommonjs(
1273
+ async function transformCommonjs(
1173
1274
  parse,
1174
1275
  code,
1175
1276
  id,
@@ -1180,21 +1281,23 @@ function transformCommonjs(
1180
1281
  getIgnoreTryCatchRequireStatementMode,
1181
1282
  sourceMap,
1182
1283
  isDynamicRequireModulesEnabled,
1183
- dynamicRequireModuleSet,
1184
- disableWrap,
1284
+ dynamicRequireModules,
1185
1285
  commonDir,
1186
1286
  astCache,
1187
- defaultIsModuleExports
1287
+ defaultIsModuleExports,
1288
+ needsRequireWrapper,
1289
+ resolveRequireSourcesAndGetMeta,
1290
+ isRequired,
1291
+ checkDynamicRequire
1188
1292
  ) {
1189
1293
  const ast = astCache || tryParse(parse, code, id);
1190
- const magicString = new MagicString__default['default'](code);
1294
+ const magicString = new MagicString__default["default"](code);
1191
1295
  const uses = {
1192
1296
  module: false,
1193
1297
  exports: false,
1194
1298
  global: false,
1195
1299
  require: false
1196
1300
  };
1197
- let usesDynamicRequire = false;
1198
1301
  const virtualDynamicRequirePath =
1199
1302
  isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path.dirname(id), commonDir);
1200
1303
  let scope = pluginutils.attachScopes(ast, 'scope');
@@ -1204,24 +1307,18 @@ function transformCommonjs(
1204
1307
  let shouldWrap = false;
1205
1308
 
1206
1309
  const globals = new Set();
1207
-
1208
- // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
1209
- const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');
1210
- const dynamicRegisterSources = new Set();
1211
- let hasRemovedRequire = false;
1212
-
1213
- const {
1214
- addRequireStatement,
1215
- requiredSources,
1216
- rewriteRequireExpressionsAndGetImportBlock
1217
- } = getRequireHandlers();
1310
+ // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
1311
+ // or contains nested requires, those should be handled as function calls unless there is an
1312
+ // unconditional require elsewhere.
1313
+ let currentConditionalNodeEnd = null;
1314
+ const conditionalNodes = new Set();
1315
+ const { addRequireStatement, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1218
1316
 
1219
1317
  // See which names are assigned to. This is necessary to prevent
1220
1318
  // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
1221
1319
  // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
1222
1320
  const reassignedNames = new Set();
1223
1321
  const topLevelDeclarations = [];
1224
- const topLevelRequireDeclarators = new Set();
1225
1322
  const skippedNodes = new Set();
1226
1323
  const moduleAccessScopes = new Set([scope]);
1227
1324
  const exportsAccessScopes = new Set([scope]);
@@ -1230,6 +1327,8 @@ function transformCommonjs(
1230
1327
  const exportsAssignmentsByName = new Map();
1231
1328
  const topLevelAssignments = new Set();
1232
1329
  const topLevelDefineCompiledEsmExpressions = [];
1330
+ const replacedGlobal = [];
1331
+ const replacedDynamicRequires = [];
1233
1332
 
1234
1333
  estreeWalker.walk(ast, {
1235
1334
  enter(node, parent) {
@@ -1241,6 +1340,12 @@ function transformCommonjs(
1241
1340
  if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
1242
1341
  currentTryBlockEnd = null;
1243
1342
  }
1343
+ if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) {
1344
+ currentConditionalNodeEnd = null;
1345
+ }
1346
+ if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) {
1347
+ currentConditionalNodeEnd = node.end;
1348
+ }
1244
1349
 
1245
1350
  programDepth += 1;
1246
1351
  if (node.scope) ({ scope } = node);
@@ -1252,11 +1357,6 @@ function transformCommonjs(
1252
1357
 
1253
1358
  // eslint-disable-next-line default-case
1254
1359
  switch (node.type) {
1255
- case 'TryStatement':
1256
- if (currentTryBlockEnd === null) {
1257
- currentTryBlockEnd = node.block.end;
1258
- }
1259
- return;
1260
1360
  case 'AssignmentExpression':
1261
1361
  if (node.left.type === 'MemberExpression') {
1262
1362
  const flattened = getKeypath(node.left);
@@ -1327,12 +1427,15 @@ function transformCommonjs(
1327
1427
  return;
1328
1428
  }
1329
1429
 
1430
+ // Transform require.resolve
1330
1431
  if (
1432
+ isDynamicRequireModulesEnabled &&
1331
1433
  node.callee.object &&
1332
- node.callee.object.name === 'require' &&
1333
- node.callee.property.name === 'resolve' &&
1334
- hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
1434
+ isRequire(node.callee.object, scope) &&
1435
+ node.callee.property.name === 'resolve'
1335
1436
  ) {
1437
+ checkDynamicRequire();
1438
+ uses.require = true;
1336
1439
  const requireNode = node.callee.object;
1337
1440
  magicString.appendLeft(
1338
1441
  node.end - 1,
@@ -1340,98 +1443,45 @@ function transformCommonjs(
1340
1443
  path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1341
1444
  )}`
1342
1445
  );
1343
- magicString.overwrite(
1344
- requireNode.start,
1345
- requireNode.end,
1346
- `${HELPERS_NAME}.commonjsRequire`,
1347
- {
1348
- storeName: true
1349
- }
1350
- );
1446
+ replacedDynamicRequires.push(requireNode);
1351
1447
  return;
1352
1448
  }
1353
1449
 
1354
- if (!isStaticRequireStatement(node, scope)) return;
1355
- if (!isDynamicRequireModulesEnabled) {
1356
- skippedNodes.add(node.callee);
1450
+ if (!isRequireExpression(node, scope)) {
1451
+ return;
1357
1452
  }
1358
- if (!isIgnoredRequireStatement(node, ignoreRequire)) {
1359
- skippedNodes.add(node.callee);
1360
- const usesReturnValue = parent.type !== 'ExpressionStatement';
1361
-
1362
- let canConvertRequire = true;
1363
- let shouldRemoveRequireStatement = false;
1364
1453
 
1365
- if (currentTryBlockEnd !== null) {
1366
- ({
1367
- canConvertRequire,
1368
- shouldRemoveRequireStatement
1369
- } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
1370
-
1371
- if (shouldRemoveRequireStatement) {
1372
- hasRemovedRequire = true;
1373
- }
1454
+ skippedNodes.add(node.callee);
1455
+ uses.require = true;
1456
+
1457
+ if (hasDynamicArguments(node)) {
1458
+ if (isDynamicRequireModulesEnabled) {
1459
+ magicString.appendLeft(
1460
+ node.end - 1,
1461
+ `, ${JSON.stringify(
1462
+ path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1463
+ )}`
1464
+ );
1374
1465
  }
1375
-
1376
- let sourceId = getRequireStringArg(node);
1377
- const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1378
- if (isDynamicRegister) {
1379
- sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1380
- if (sourceId.endsWith('.json')) {
1381
- sourceId = DYNAMIC_JSON_PREFIX + sourceId;
1382
- }
1383
- dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
1384
- } else {
1385
- if (
1386
- !sourceId.endsWith('.json') &&
1387
- hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
1388
- ) {
1389
- if (shouldRemoveRequireStatement) {
1390
- magicString.overwrite(node.start, node.end, `undefined`);
1391
- } else if (canConvertRequire) {
1392
- magicString.overwrite(
1393
- node.start,
1394
- node.end,
1395
- `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
1396
- getVirtualPathForDynamicRequirePath(sourceId, commonDir)
1397
- )}, ${JSON.stringify(
1398
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1399
- )})`
1400
- );
1401
- usesDynamicRequire = true;
1402
- }
1403
- return;
1404
- }
1405
-
1406
- if (canConvertRequire) {
1407
- addRequireStatement(sourceId, node, scope, usesReturnValue);
1408
- }
1466
+ if (!ignoreDynamicRequires) {
1467
+ checkDynamicRequire();
1468
+ replacedDynamicRequires.push(node.callee);
1409
1469
  }
1470
+ return;
1471
+ }
1410
1472
 
1411
- if (usesReturnValue) {
1412
- if (shouldRemoveRequireStatement) {
1413
- magicString.overwrite(node.start, node.end, `undefined`);
1414
- return;
1415
- }
1416
-
1417
- if (
1418
- parent.type === 'VariableDeclarator' &&
1419
- !scope.parent &&
1420
- parent.id.type === 'Identifier'
1421
- ) {
1422
- // This will allow us to reuse this variable name as the imported variable if it is not reassigned
1423
- // and does not conflict with variables in other places where this is imported
1424
- topLevelRequireDeclarators.add(parent);
1425
- }
1426
- } else {
1427
- // This is a bare import, e.g. `require('foo');`
1428
-
1429
- if (!canConvertRequire && !shouldRemoveRequireStatement) {
1430
- return;
1431
- }
1432
-
1433
- magicString.remove(parent.start, parent.end);
1434
- }
1473
+ const requireStringArg = getRequireStringArg(node);
1474
+ if (!ignoreRequire(requireStringArg)) {
1475
+ const usesReturnValue = parent.type !== 'ExpressionStatement';
1476
+ addRequireStatement(
1477
+ requireStringArg,
1478
+ node,
1479
+ scope,
1480
+ usesReturnValue,
1481
+ currentTryBlockEnd !== null,
1482
+ currentConditionalNodeEnd !== null,
1483
+ parent.type === 'ExpressionStatement' ? parent : node
1484
+ );
1435
1485
  }
1436
1486
  return;
1437
1487
  }
@@ -1440,45 +1490,44 @@ function transformCommonjs(
1440
1490
  // skip dead branches
1441
1491
  if (isFalsy(node.test)) {
1442
1492
  skippedNodes.add(node.consequent);
1443
- } else if (node.alternate && isTruthy(node.test)) {
1444
- skippedNodes.add(node.alternate);
1493
+ } else if (isTruthy(node.test)) {
1494
+ if (node.alternate) {
1495
+ skippedNodes.add(node.alternate);
1496
+ }
1497
+ } else {
1498
+ conditionalNodes.add(node.consequent);
1499
+ if (node.alternate) {
1500
+ conditionalNodes.add(node.alternate);
1501
+ }
1502
+ }
1503
+ return;
1504
+ case 'ArrowFunctionExpression':
1505
+ case 'FunctionDeclaration':
1506
+ case 'FunctionExpression':
1507
+ // requires in functions should be conditional unless it is an IIFE
1508
+ if (
1509
+ currentConditionalNodeEnd === null &&
1510
+ !(parent.type === 'CallExpression' && parent.callee === node)
1511
+ ) {
1512
+ currentConditionalNodeEnd = node.end;
1445
1513
  }
1446
1514
  return;
1447
1515
  case 'Identifier': {
1448
1516
  const { name } = node;
1449
- if (!(isReference__default['default'](node, parent) && !scope.contains(name))) return;
1517
+ if (!isReference__default["default"](node, parent) || scope.contains(name)) return;
1450
1518
  switch (name) {
1451
1519
  case 'require':
1520
+ uses.require = true;
1452
1521
  if (isNodeRequirePropertyAccess(parent)) {
1453
- if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
1454
- if (parent.property.name === 'cache') {
1455
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1456
- storeName: true
1457
- });
1458
- }
1459
- }
1460
-
1461
1522
  return;
1462
1523
  }
1463
-
1464
- if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
1465
- magicString.appendLeft(
1466
- parent.end - 1,
1467
- `,${JSON.stringify(
1468
- path.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1469
- )}`
1470
- );
1471
- }
1472
1524
  if (!ignoreDynamicRequires) {
1525
+ checkDynamicRequire();
1473
1526
  if (isShorthandProperty(parent)) {
1474
- magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1475
- } else {
1476
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1477
- storeName: true
1478
- });
1527
+ magicString.prependRight(node.start, 'require: ');
1479
1528
  }
1529
+ replacedDynamicRequires.push(node);
1480
1530
  }
1481
- usesDynamicRequire = true;
1482
1531
  return;
1483
1532
  case 'module':
1484
1533
  case 'exports':
@@ -1488,9 +1537,7 @@ function transformCommonjs(
1488
1537
  case 'global':
1489
1538
  uses.global = true;
1490
1539
  if (!ignoreGlobal) {
1491
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1492
- storeName: true
1493
- });
1540
+ replacedGlobal.push(node);
1494
1541
  }
1495
1542
  return;
1496
1543
  case 'define':
@@ -1503,11 +1550,26 @@ function transformCommonjs(
1503
1550
  return;
1504
1551
  }
1505
1552
  }
1553
+ case 'LogicalExpression':
1554
+ // skip dead branches
1555
+ if (node.operator === '&&') {
1556
+ if (isFalsy(node.left)) {
1557
+ skippedNodes.add(node.right);
1558
+ } else if (!isTruthy(node.left)) {
1559
+ conditionalNodes.add(node.right);
1560
+ }
1561
+ } else if (node.operator === '||') {
1562
+ if (isTruthy(node.left)) {
1563
+ skippedNodes.add(node.right);
1564
+ } else if (!isFalsy(node.left)) {
1565
+ conditionalNodes.add(node.right);
1566
+ }
1567
+ }
1568
+ return;
1506
1569
  case 'MemberExpression':
1507
1570
  if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
1508
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1509
- storeName: true
1510
- });
1571
+ uses.require = true;
1572
+ replacedDynamicRequires.push(node);
1511
1573
  skippedNodes.add(node.object);
1512
1574
  skippedNodes.add(node.property);
1513
1575
  }
@@ -1523,12 +1585,18 @@ function transformCommonjs(
1523
1585
  if (lexicalDepth === 0) {
1524
1586
  uses.global = true;
1525
1587
  if (!ignoreGlobal) {
1526
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1527
- storeName: true
1528
- });
1588
+ replacedGlobal.push(node);
1529
1589
  }
1530
1590
  }
1531
1591
  return;
1592
+ case 'TryStatement':
1593
+ if (currentTryBlockEnd === null) {
1594
+ currentTryBlockEnd = node.block.end;
1595
+ }
1596
+ if (currentConditionalNodeEnd === null) {
1597
+ currentConditionalNodeEnd = node.end;
1598
+ }
1599
+ return;
1532
1600
  case 'UnaryExpression':
1533
1601
  // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
1534
1602
  if (node.operator === 'typeof') {
@@ -1565,34 +1633,45 @@ function transformCommonjs(
1565
1633
  const nameBase = getName(id);
1566
1634
  const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
1567
1635
  const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
1636
+ const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1637
+ const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1638
+ const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1639
+ const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
1568
1640
  const deconflictedExportNames = Object.create(null);
1569
1641
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1570
1642
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
1571
1643
  }
1572
1644
 
1645
+ for (const node of replacedGlobal) {
1646
+ magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, {
1647
+ storeName: true
1648
+ });
1649
+ }
1650
+ for (const node of replacedDynamicRequires) {
1651
+ magicString.overwrite(node.start, node.end, dynamicRequireName, {
1652
+ contentOnly: true,
1653
+ storeName: true
1654
+ });
1655
+ }
1656
+
1573
1657
  // We cannot wrap ES/mixed modules
1574
- shouldWrap =
1575
- !isEsModule &&
1576
- !disableWrap &&
1577
- (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1658
+ shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1578
1659
  const detectWrappedDefault =
1579
1660
  shouldWrap &&
1580
1661
  (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
1581
1662
 
1582
1663
  if (
1583
1664
  !(
1584
- requiredSources.length ||
1585
- dynamicRegisterSources.size ||
1665
+ shouldWrap ||
1666
+ isRequired ||
1586
1667
  uses.module ||
1587
1668
  uses.exports ||
1588
1669
  uses.require ||
1589
- usesDynamicRequire ||
1590
- hasRemovedRequire ||
1591
1670
  topLevelDefineCompiledEsmExpressions.length > 0
1592
1671
  ) &&
1593
1672
  (ignoreGlobal || !uses.global)
1594
1673
  ) {
1595
- return { meta: { commonjs: { isCommonJS: false } } };
1674
+ return { meta: { commonjs: { isCommonJS: false, isMixedModule: false } } };
1596
1675
  }
1597
1676
 
1598
1677
  let leadingComment = '';
@@ -1614,19 +1693,22 @@ function transformCommonjs(
1614
1693
  ? 'exports'
1615
1694
  : 'module';
1616
1695
 
1617
- const importBlock = rewriteRequireExpressionsAndGetImportBlock(
1696
+ const { importBlock, usesRequireWrapper } = await rewriteRequireExpressionsAndGetImportBlock(
1618
1697
  magicString,
1619
1698
  topLevelDeclarations,
1620
- topLevelRequireDeclarators,
1621
1699
  reassignedNames,
1622
- HELPERS_NAME,
1623
- dynamicRegisterSources,
1700
+ helpersName,
1701
+ dynamicRequireName,
1624
1702
  moduleName,
1625
1703
  exportsName,
1626
1704
  id,
1627
- exportMode
1705
+ exportMode,
1706
+ resolveRequireSourcesAndGetMeta,
1707
+ needsRequireWrapper,
1708
+ isEsModule,
1709
+ uses.require,
1710
+ getIgnoreTryCatchRequireStatementMode
1628
1711
  );
1629
-
1630
1712
  const exportBlock = isEsModule
1631
1713
  ? ''
1632
1714
  : rewriteExportsAndGetExportsBlock(
@@ -1641,16 +1723,35 @@ function transformCommonjs(
1641
1723
  topLevelDefineCompiledEsmExpressions,
1642
1724
  deconflictedExportNames,
1643
1725
  code,
1644
- HELPERS_NAME,
1726
+ helpersName,
1645
1727
  exportMode,
1646
1728
  detectWrappedDefault,
1647
- defaultIsModuleExports
1729
+ defaultIsModuleExports,
1730
+ usesRequireWrapper,
1731
+ requireName
1648
1732
  );
1649
1733
 
1650
1734
  if (shouldWrap) {
1651
1735
  wrapCode(magicString, uses, moduleName, exportsName);
1652
1736
  }
1653
1737
 
1738
+ if (usesRequireWrapper) {
1739
+ magicString.trim().indent('\t');
1740
+ magicString.prepend(
1741
+ `var ${isRequiredName};
1742
+
1743
+ function ${requireName} () {
1744
+ \tif (${isRequiredName}) return ${exportsName};
1745
+ \t${isRequiredName} = 1;
1746
+ `
1747
+ ).append(`
1748
+ \treturn ${exportsName};
1749
+ }`);
1750
+ if (exportMode === 'replace') {
1751
+ magicString.prepend(`var ${exportsName};\n`);
1752
+ }
1753
+ }
1754
+
1654
1755
  magicString
1655
1756
  .trim()
1656
1757
  .prepend(leadingComment + importBlock)
@@ -1659,24 +1760,32 @@ function transformCommonjs(
1659
1760
  return {
1660
1761
  code: magicString.toString(),
1661
1762
  map: sourceMap ? magicString.generateMap() : null,
1662
- syntheticNamedExports: isEsModule ? false : '__moduleExports',
1663
- meta: { commonjs: { isCommonJS: !isEsModule } }
1763
+ syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
1764
+ meta: {
1765
+ commonjs: {
1766
+ isCommonJS: !isEsModule && (usesRequireWrapper ? IS_WRAPPED_COMMONJS : true),
1767
+ isMixedModule: isEsModule
1768
+ }
1769
+ }
1664
1770
  };
1665
1771
  }
1666
1772
 
1667
1773
  function commonjs(options = {}) {
1668
- const extensions = options.extensions || ['.js'];
1669
- const filter = pluginutils.createFilter(options.include, options.exclude);
1670
1774
  const {
1671
1775
  ignoreGlobal,
1672
1776
  ignoreDynamicRequires,
1673
1777
  requireReturnsDefault: requireReturnsDefaultOption,
1674
1778
  esmExternals
1675
1779
  } = options;
1780
+ const extensions = options.extensions || ['.js'];
1781
+ const filter = pluginutils.createFilter(options.include, options.exclude);
1782
+ const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
1783
+
1676
1784
  const getRequireReturnsDefault =
1677
1785
  typeof requireReturnsDefaultOption === 'function'
1678
1786
  ? requireReturnsDefaultOption
1679
1787
  : () => requireReturnsDefaultOption;
1788
+
1680
1789
  let esmExternalIds;
1681
1790
  const isEsmExternal =
1682
1791
  typeof esmExternals === 'function'
@@ -1684,20 +1793,27 @@ function commonjs(options = {}) {
1684
1793
  : Array.isArray(esmExternals)
1685
1794
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1686
1795
  : () => esmExternals;
1796
+
1687
1797
  const defaultIsModuleExports =
1688
1798
  typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1689
1799
 
1690
- const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1691
- options.dynamicRequireTargets
1800
+ const {
1801
+ resolveRequireSourcesAndGetMeta,
1802
+ getWrappedIds,
1803
+ isRequiredId
1804
+ } = getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional);
1805
+ const dynamicRequireRoot =
1806
+ typeof options.dynamicRequireRoot === 'string'
1807
+ ? path.resolve(options.dynamicRequireRoot)
1808
+ : process.cwd();
1809
+ const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
1810
+ options.dynamicRequireTargets,
1811
+ dynamicRequireRoot
1692
1812
  );
1693
- const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
1694
- const commonDir = isDynamicRequireModulesEnabled
1695
- ? getCommonDir__default['default'](null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1696
- : null;
1813
+ const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1697
1814
 
1698
1815
  const esModulesWithDefaultExport = new Set();
1699
1816
  const esModulesWithNamedExports = new Set();
1700
- const commonJsMetaPromises = new Map();
1701
1817
 
1702
1818
  const ignoreRequire =
1703
1819
  typeof options.ignore === 'function'
@@ -1712,11 +1828,13 @@ function commonjs(options = {}) {
1712
1828
  ? options.ignoreTryCatch(id)
1713
1829
  : Array.isArray(options.ignoreTryCatch)
1714
1830
  ? options.ignoreTryCatch.includes(id)
1715
- : options.ignoreTryCatch || false;
1831
+ : typeof options.ignoreTryCatch !== 'undefined'
1832
+ ? options.ignoreTryCatch
1833
+ : true;
1716
1834
 
1717
1835
  return {
1718
1836
  canConvertRequire: mode !== 'remove' && mode !== true,
1719
- shouldRemoveRequireStatement: mode === 'remove'
1837
+ shouldRemoveRequire: mode === 'remove'
1720
1838
  };
1721
1839
  };
1722
1840
 
@@ -1725,12 +1843,6 @@ function commonjs(options = {}) {
1725
1843
  const sourceMap = options.sourceMap !== false;
1726
1844
 
1727
1845
  function transformAndCheckExports(code, id) {
1728
- if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1729
- // eslint-disable-next-line no-param-reassign
1730
- code =
1731
- getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1732
- }
1733
-
1734
1846
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1735
1847
  this.parse,
1736
1848
  code,
@@ -1744,18 +1856,29 @@ function commonjs(options = {}) {
1744
1856
  }
1745
1857
 
1746
1858
  if (
1747
- !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1748
- (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1859
+ !dynamicRequireModules.has(normalizePathSlashes(id)) &&
1860
+ (!(hasCjsKeywords(code, ignoreGlobal) || isRequiredId(id)) ||
1861
+ (isEsModule && !options.transformMixedEsModules))
1749
1862
  ) {
1750
1863
  return { meta: { commonjs: { isCommonJS: false } } };
1751
1864
  }
1752
1865
 
1753
- // avoid wrapping as this is a commonjsRegister call
1754
- const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
1755
- if (disableWrap) {
1756
- // eslint-disable-next-line no-param-reassign
1757
- id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1758
- }
1866
+ const needsRequireWrapper =
1867
+ !isEsModule &&
1868
+ (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1869
+
1870
+ const checkDynamicRequire = () => {
1871
+ if (id.indexOf(dynamicRequireRoot) !== 0) {
1872
+ this.error({
1873
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1874
+ id,
1875
+ dynamicRequireRoot,
1876
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${path.dirname(
1877
+ id
1878
+ )}" or one of its parent directories.`
1879
+ });
1880
+ }
1881
+ };
1759
1882
 
1760
1883
  return transformCommonjs(
1761
1884
  this.parse,
@@ -1768,17 +1891,37 @@ function commonjs(options = {}) {
1768
1891
  getIgnoreTryCatchRequireStatementMode,
1769
1892
  sourceMap,
1770
1893
  isDynamicRequireModulesEnabled,
1771
- dynamicRequireModuleSet,
1772
- disableWrap,
1894
+ dynamicRequireModules,
1773
1895
  commonDir,
1774
1896
  ast,
1775
- defaultIsModuleExports
1897
+ defaultIsModuleExports,
1898
+ needsRequireWrapper,
1899
+ resolveRequireSourcesAndGetMeta(this),
1900
+ isRequiredId(id),
1901
+ checkDynamicRequire
1776
1902
  );
1777
1903
  }
1778
1904
 
1779
1905
  return {
1780
1906
  name: 'commonjs',
1781
1907
 
1908
+ version,
1909
+
1910
+ options(rawOptions) {
1911
+ // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
1912
+ // do not prevent our plugin from resolving entry points ot proxies.
1913
+ const plugins = Array.isArray(rawOptions.plugins)
1914
+ ? rawOptions.plugins
1915
+ : rawOptions.plugins
1916
+ ? [rawOptions.plugins]
1917
+ : [];
1918
+ plugins.unshift({
1919
+ name: 'commonjs--resolver',
1920
+ resolveId
1921
+ });
1922
+ return { ...rawOptions, plugins };
1923
+ },
1924
+
1782
1925
  buildStart() {
1783
1926
  validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1784
1927
  if (options.namedExports != null) {
@@ -1788,44 +1931,43 @@ function commonjs(options = {}) {
1788
1931
  }
1789
1932
  },
1790
1933
 
1791
- resolveId,
1934
+ buildEnd() {
1935
+ if (options.strictRequires === 'debug') {
1936
+ const wrappedIds = getWrappedIds();
1937
+ if (wrappedIds.length) {
1938
+ this.warn({
1939
+ code: 'WRAPPED_IDS',
1940
+ ids: wrappedIds,
1941
+ message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds
1942
+ .map((id) => `\t${JSON.stringify(path.relative(process.cwd(), id))}`)
1943
+ .join(',\n')}\n]`
1944
+ });
1945
+ } else {
1946
+ this.warn({
1947
+ code: 'WRAPPED_IDS',
1948
+ ids: wrappedIds,
1949
+ message: 'The commonjs plugin did not wrap any files.'
1950
+ });
1951
+ }
1952
+ }
1953
+ },
1792
1954
 
1793
1955
  load(id) {
1794
1956
  if (id === HELPERS_ID) {
1795
- return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
1796
- }
1797
-
1798
- if (id.startsWith(HELPERS_ID)) {
1799
- return getSpecificHelperProxy(id);
1957
+ return getHelpersModule();
1800
1958
  }
1801
1959
 
1802
1960
  if (isWrappedId(id, MODULE_SUFFIX)) {
1803
- const actualId = unwrapId(id, MODULE_SUFFIX);
1804
- let name = getName(actualId);
1805
- let code;
1806
- if (isDynamicRequireModulesEnabled) {
1807
- if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
1808
- name = `${name}_`;
1809
- }
1810
- code =
1811
- `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
1812
- `var ${name} = createModule(${JSON.stringify(
1813
- getVirtualPathForDynamicRequirePath(path.dirname(actualId), commonDir)
1814
- )});\n` +
1815
- `export {${name} as __module}`;
1816
- } else {
1817
- code = `var ${name} = {exports: {}}; export {${name} as __module}`;
1818
- }
1961
+ const name = getName(unwrapId(id, MODULE_SUFFIX));
1819
1962
  return {
1820
- code,
1963
+ code: `var ${name} = {exports: {}}; export {${name} as __module}`,
1821
1964
  syntheticNamedExports: '__module',
1822
1965
  meta: { commonjs: { isCommonJS: false } }
1823
1966
  };
1824
1967
  }
1825
1968
 
1826
1969
  if (isWrappedId(id, EXPORTS_SUFFIX)) {
1827
- const actualId = unwrapId(id, EXPORTS_SUFFIX);
1828
- const name = getName(actualId);
1970
+ const name = getName(unwrapId(id, EXPORTS_SUFFIX));
1829
1971
  return {
1830
1972
  code: `var ${name} = {}; export {${name} as __exports}`,
1831
1973
  meta: { commonjs: { isCommonJS: false } }
@@ -1840,22 +1982,16 @@ function commonjs(options = {}) {
1840
1982
  );
1841
1983
  }
1842
1984
 
1843
- if (id === DYNAMIC_PACKAGES_ID) {
1844
- return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
1845
- }
1846
-
1847
- if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
1848
- return getDynamicJsonProxy(id, commonDir);
1849
- }
1850
-
1851
- if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
1852
- return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
1985
+ if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
1986
+ return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
1853
1987
  }
1854
1988
 
1855
- if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1856
- return getDynamicRequireProxy(
1857
- normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
1858
- commonDir
1989
+ if (id === DYNAMIC_MODULES_ID) {
1990
+ return getDynamicModuleRegistry(
1991
+ isDynamicRequireModulesEnabled,
1992
+ dynamicRequireModules,
1993
+ commonDir,
1994
+ ignoreDynamicRequires
1859
1995
  );
1860
1996
  }
1861
1997
 
@@ -1866,43 +2002,24 @@ function commonjs(options = {}) {
1866
2002
  getRequireReturnsDefault(actualId),
1867
2003
  esModulesWithDefaultExport,
1868
2004
  esModulesWithNamedExports,
1869
- commonJsMetaPromises
2005
+ this.load
1870
2006
  );
1871
2007
  }
1872
2008
 
1873
2009
  return null;
1874
2010
  },
1875
2011
 
1876
- transform(code, rawId) {
1877
- let id = rawId;
1878
-
1879
- if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1880
- id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1881
- }
1882
-
2012
+ transform(code, id) {
1883
2013
  const extName = path.extname(id);
1884
- if (
1885
- extName !== '.cjs' &&
1886
- id !== DYNAMIC_PACKAGES_ID &&
1887
- !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1888
- (!filter(id) || !extensions.includes(extName))
1889
- ) {
2014
+ if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {
1890
2015
  return null;
1891
2016
  }
1892
2017
 
1893
2018
  try {
1894
- return transformAndCheckExports.call(this, code, rawId);
2019
+ return transformAndCheckExports.call(this, code, id);
1895
2020
  } catch (err) {
1896
2021
  return this.error(err, err.loc);
1897
2022
  }
1898
- },
1899
-
1900
- moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
1901
- if (commonjsMeta && commonjsMeta.isCommonJS != null) {
1902
- setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
1903
- return;
1904
- }
1905
- setCommonJSMetaPromise(commonJsMetaPromises, id, null);
1906
2023
  }
1907
2024
  };
1908
2025
  }