@rollup/plugin-commonjs 21.0.1 → 22.0.0-3

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