@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.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 = "22.0.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);
488
248
  }
489
249
 
490
- // e.g. id === "commonjsHelpers?commonjsRegister"
491
- function getSpecificHelperProxy(id) {
492
- return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
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;
373
+ }
374
+ `;
375
+
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,86 +457,216 @@ 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
+ if (
482
+ resolveOptions.custom &&
483
+ resolveOptions.custom.commonjs &&
484
+ resolveOptions.custom.commonjs.skipResolver
485
+ ) {
486
+ return null;
487
+ }
488
+ if (isWrappedId(importee, WRAPPED_SUFFIX)) {
489
+ return unwrapId(importee, WRAPPED_SUFFIX);
490
+ }
573
491
 
574
- const resolved = resolve(dirname(importer), importee);
575
- const candidates = getCandidates(resolved, extensions);
492
+ if (
493
+ isWrappedId(importee, MODULE_SUFFIX) ||
494
+ isWrappedId(importee, EXPORTS_SUFFIX) ||
495
+ isWrappedId(importee, PROXY_SUFFIX) ||
496
+ isWrappedId(importee, ES_IMPORT_SUFFIX) ||
497
+ isWrappedId(importee, EXTERNAL_SUFFIX) ||
498
+ importee.startsWith(HELPERS_ID) ||
499
+ importee === DYNAMIC_MODULES_ID
500
+ ) {
501
+ return importee;
502
+ }
576
503
 
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 */
504
+ if (importer) {
505
+ if (
506
+ importer === DYNAMIC_MODULES_ID ||
507
+ // Proxies are only importing resolved ids, no need to resolve again
508
+ isWrappedId(importer, PROXY_SUFFIX) ||
509
+ isWrappedId(importer, ES_IMPORT_SUFFIX)
510
+ ) {
511
+ return importee;
512
+ }
513
+ if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
514
+ // We need to return null for unresolved imports so that the proper warning is shown
515
+ if (!(await this.resolve(importee, importer, { skipSelf: true }))) {
516
+ return null;
517
+ }
518
+ // For other external imports, we need to make sure they are handled as external
519
+ return { id: importee, external: true };
583
520
  }
584
521
  }
585
522
 
586
- return undefined;
587
- }
588
-
589
- return function resolveId(importee, rawImporter) {
590
- if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
591
- return importee;
523
+ if (importee.startsWith('\0')) {
524
+ return null;
592
525
  }
593
526
 
594
- const importer =
595
- rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
596
- ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
597
- : rawImporter;
527
+ // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
528
+ // if that is the case, we need to add a proxy.
529
+ const customOptions = resolveOptions.custom;
598
530
 
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;
531
+ // If this is a require, we do not need a proxy
532
+ if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
533
+ return null;
603
534
  }
604
535
 
605
- const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
606
- const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
607
- let isModuleRegistration = false;
536
+ const resolved =
537
+ (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
538
+ resolveExtensions(importee, importer, extensions);
539
+ if (!resolved || resolved.external) {
540
+ return resolved;
541
+ }
542
+ const {
543
+ meta: { commonjs: commonjsMeta }
544
+ } = await this.load(resolved);
545
+ if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
546
+ return wrapId(resolved.id, ES_IMPORT_SUFFIX);
547
+ }
548
+ return resolved;
549
+ };
550
+ }
608
551
 
609
- if (isProxyModule) {
610
- importee = unwrapId(importee, PROXY_SUFFIX);
611
- } else if (isRequiredModule) {
612
- importee = unwrapId(importee, REQUIRE_SUFFIX);
552
+ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional) {
553
+ const knownCjsModuleTypes = Object.create(null);
554
+ const requiredIds = Object.create(null);
555
+ const unconditionallyRequiredIds = Object.create(null);
556
+ const parentModules = Object.create(null);
557
+ const childModules = Object.create(null);
558
+ const getParentModules = (id) => parentModules[id] || (parentModules[id] = Object.create(null));
559
+ const getChildModules = (id) => childModules[id] || (childModules[id] = Object.create(null));
613
560
 
614
- isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
615
- if (isModuleRegistration) {
616
- importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
561
+ return {
562
+ getWrappedIds: () =>
563
+ Object.keys(knownCjsModuleTypes).filter(
564
+ (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
565
+ ),
566
+ isRequiredId: (id) => requiredIds[id],
567
+ resolveRequireSourcesAndGetMeta: (rollupContext) => async (
568
+ parentId,
569
+ isParentCommonJS,
570
+ sources
571
+ ) => {
572
+ knownCjsModuleTypes[parentId] = knownCjsModuleTypes[parentId] || isParentCommonJS;
573
+ if (
574
+ knownCjsModuleTypes[parentId] &&
575
+ requiredIds[parentId] &&
576
+ !unconditionallyRequiredIds[parentId]
577
+ ) {
578
+ knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
617
579
  }
618
- }
580
+ const requireTargets = await Promise.all(
581
+ sources.map(async ({ source, isConditional }) => {
582
+ // Never analyze or proxy internal modules
583
+ if (source.startsWith('\0')) {
584
+ return { id: source, allowProxy: false };
585
+ }
586
+ const resolved =
587
+ (await rollupContext.resolve(source, parentId, {
588
+ custom: {
589
+ 'node-resolve': { isRequire: true },
590
+ commonjs: { skipResolver: true }
591
+ }
592
+ })) || resolveExtensions(source, parentId, extensions);
593
+ if (!resolved) {
594
+ return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
595
+ }
596
+ const childId = resolved.id;
597
+ if (resolved.external) {
598
+ return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
599
+ }
600
+ requiredIds[childId] = true;
601
+ if (
602
+ !(
603
+ detectCyclesAndConditional &&
604
+ (isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)
605
+ )
606
+ ) {
607
+ unconditionallyRequiredIds[childId] = true;
608
+ }
609
+ const parentDependentModules = getParentModules(parentId);
610
+ const childDependentModules = getParentModules(childId);
619
611
 
620
- if (
621
- importee.startsWith(HELPERS_ID) ||
622
- importee === DYNAMIC_PACKAGES_ID ||
623
- importee.startsWith(DYNAMIC_JSON_PREFIX)
624
- ) {
625
- return importee;
626
- }
612
+ // Copy the parents of the current parent to the child
613
+ for (const dependentId of Object.keys(parentDependentModules)) {
614
+ childDependentModules[dependentId] = true;
615
+ }
627
616
 
628
- if (importee.startsWith('\0')) {
629
- return null;
630
- }
617
+ // Add the current parent to the child as well. If the child module already has known
618
+ // dependencies because it has already been loaded, add the current parent module to their
619
+ // parent modules
620
+ childDependentModules[parentId] = true;
621
+ const dependenciesToUpdate = new Set(Object.keys(getChildModules(childId)));
622
+ for (const dependencyId of dependenciesToUpdate) {
623
+ getParentModules(dependencyId)[parentId] = true;
624
+ for (const subDependencyId of Object.keys(getChildModules(dependencyId))) {
625
+ dependenciesToUpdate.add(subDependencyId);
626
+ }
627
+ }
631
628
 
632
- return this.resolve(importee, importer, {
633
- skipSelf: true,
634
- custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
635
- }).then((resolved) => {
636
- if (!resolved) {
637
- resolved = resolveExtensions(importee, importer);
638
- }
639
- if (resolved && isProxyModule) {
640
- resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
641
- resolved.external = false;
642
- } else if (resolved && isModuleRegistration) {
643
- resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
644
- } else if (!resolved && (isProxyModule || isRequiredModule)) {
645
- return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
646
- }
647
- return resolved;
648
- });
629
+ // Add the child as a dependency to the parent
630
+ getChildModules(parentId)[childId] = true;
631
+
632
+ // If we depend on one of our dependencies, we have a cycle. Then all modules that
633
+ // we depend on that also depend on the same module are part of a cycle as well. Trying
634
+ // to wait for loading this module would lead to a deadlock.
635
+ if (parentDependentModules[childId]) {
636
+ if (detectCyclesAndConditional && isParentCommonJS) {
637
+ knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
638
+ knownCjsModuleTypes[childId] = IS_WRAPPED_COMMONJS;
639
+ for (const dependentId of Object.keys(parentDependentModules)) {
640
+ if (getParentModules(dependentId)[childId]) {
641
+ knownCjsModuleTypes[dependentId] = IS_WRAPPED_COMMONJS;
642
+ }
643
+ }
644
+ }
645
+ } else {
646
+ // This makes sure the current transform handler waits for all direct dependencies to be
647
+ // loaded and transformed and therefore for all transitive CommonJS dependencies to be
648
+ // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
649
+ await rollupContext.load(resolved);
650
+ }
651
+ return { id: childId, allowProxy: true };
652
+ })
653
+ );
654
+ return {
655
+ requireTargets: requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
656
+ const isCommonJS = knownCjsModuleTypes[dependencyId];
657
+ return {
658
+ source: sources[index].source,
659
+ id: allowProxy
660
+ ? isCommonJS === IS_WRAPPED_COMMONJS
661
+ ? wrapId(dependencyId, WRAPPED_SUFFIX)
662
+ : wrapId(dependencyId, PROXY_SUFFIX)
663
+ : dependencyId,
664
+ isCommonJS
665
+ };
666
+ }),
667
+ usesRequireWrapper: knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS
668
+ };
669
+ }
649
670
  };
650
671
  }
651
672
 
@@ -805,8 +826,9 @@ function wrapCode(magicString, uses, moduleName, exportsName) {
805
826
  }
806
827
  magicString
807
828
  .trim()
829
+ .indent('\t')
808
830
  .prepend(`(function (${args.join(', ')}) {\n`)
809
- .append(`\n}(${passedArgs.join(', ')}));`);
831
+ .append(`\n} (${passedArgs.join(', ')}));`);
810
832
  }
811
833
 
812
834
  function rewriteExportsAndGetExportsBlock(
@@ -824,12 +846,27 @@ function rewriteExportsAndGetExportsBlock(
824
846
  HELPERS_NAME,
825
847
  exportMode,
826
848
  detectWrappedDefault,
827
- defaultIsModuleExports
849
+ defaultIsModuleExports,
850
+ usesRequireWrapper,
851
+ requireName
828
852
  ) {
829
853
  const exports = [];
830
854
  const exportDeclarations = [];
831
855
 
832
- if (exportMode === 'replace') {
856
+ if (usesRequireWrapper) {
857
+ getExportsWhenUsingRequireWrapper(
858
+ magicString,
859
+ wrapped,
860
+ exportMode,
861
+ exports,
862
+ moduleExportsAssignments,
863
+ exportsAssignmentsByName,
864
+ moduleName,
865
+ exportsName,
866
+ requireName,
867
+ defineCompiledEsmExpressions
868
+ );
869
+ } else if (exportMode === 'replace') {
833
870
  getExportsForReplacedModuleExports(
834
871
  magicString,
835
872
  exports,
@@ -872,6 +909,49 @@ function rewriteExportsAndGetExportsBlock(
872
909
  return `\n\n${exportDeclarations.join('\n')}`;
873
910
  }
874
911
 
912
+ function getExportsWhenUsingRequireWrapper(
913
+ magicString,
914
+ wrapped,
915
+ exportMode,
916
+ exports,
917
+ moduleExportsAssignments,
918
+ exportsAssignmentsByName,
919
+ moduleName,
920
+ exportsName,
921
+ requireName,
922
+ defineCompiledEsmExpressions
923
+ ) {
924
+ if (!wrapped) {
925
+ if (exportMode === 'replace') {
926
+ for (const { left } of moduleExportsAssignments) {
927
+ magicString.overwrite(left.start, left.end, exportsName);
928
+ }
929
+ } else {
930
+ // Collect and rewrite module.exports assignments
931
+ for (const { left } of moduleExportsAssignments) {
932
+ magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
933
+ }
934
+ // Collect and rewrite named exports
935
+ for (const [exportName, { nodes }] of exportsAssignmentsByName) {
936
+ for (const node of nodes) {
937
+ magicString.overwrite(node.start, node.left.end, `${exportsName}.${exportName}`);
938
+ }
939
+ }
940
+ // Collect and rewrite exports.__esModule assignments
941
+ for (const expression of defineCompiledEsmExpressions) {
942
+ const moduleExportsExpression =
943
+ expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
944
+ magicString.overwrite(
945
+ moduleExportsExpression.start,
946
+ moduleExportsExpression.end,
947
+ exportsName
948
+ );
949
+ }
950
+ }
951
+ }
952
+ exports.push(`${requireName} as __require`);
953
+ }
954
+
875
955
  function getExportsForReplacedModuleExports(
876
956
  magicString,
877
957
  exports,
@@ -959,7 +1039,7 @@ function getExports(
959
1039
  }
960
1040
 
961
1041
  if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
962
- exportDeclarations.push(`export default ${exportsName};`);
1042
+ exports.push(`${exportsName} as default`);
963
1043
  } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
964
1044
  exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
965
1045
  } else {
@@ -969,7 +1049,7 @@ function getExports(
969
1049
  }
970
1050
  }
971
1051
 
972
- function isRequireStatement(node, scope) {
1052
+ function isRequireExpression(node, scope) {
973
1053
  if (!node) return false;
974
1054
  if (node.type !== 'CallExpression') return false;
975
1055
 
@@ -996,11 +1076,6 @@ function isModuleRequire({ object, property }, scope) {
996
1076
  );
997
1077
  }
998
1078
 
999
- function isStaticRequireStatement(node, scope) {
1000
- if (!isRequireStatement(node, scope)) return false;
1001
- return !hasDynamicArguments(node);
1002
- }
1003
-
1004
1079
  function hasDynamicArguments(node) {
1005
1080
  return (
1006
1081
  node.arguments.length > 1 ||
@@ -1015,89 +1090,58 @@ function isNodeRequirePropertyAccess(parent) {
1015
1090
  return parent && parent.property && reservedMethod[parent.property.name];
1016
1091
  }
1017
1092
 
1018
- function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
1019
- return ignoreRequire(requiredNode.arguments[0].value);
1020
- }
1021
-
1022
1093
  function getRequireStringArg(node) {
1023
1094
  return node.arguments[0].type === 'Literal'
1024
1095
  ? node.arguments[0].value
1025
1096
  : node.arguments[0].quasis[0].value.cooked;
1026
1097
  }
1027
1098
 
1028
- function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
1029
- if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
1030
- try {
1031
- const resolvedPath = normalizePathSlashes(sync(source, { basedir: dirname(id) }));
1032
- if (dynamicRequireModuleSet.has(resolvedPath)) {
1033
- return true;
1034
- }
1035
- } catch (ex) {
1036
- // Probably a node.js internal module
1037
- return false;
1038
- }
1039
-
1040
- return false;
1041
- }
1042
-
1043
- for (const attemptExt of ['', '.js', '.json']) {
1044
- const resolvedPath = normalizePathSlashes(resolve(dirname(id), source + attemptExt));
1045
- if (dynamicRequireModuleSet.has(resolvedPath)) {
1046
- return true;
1047
- }
1048
- }
1049
-
1050
- return false;
1051
- }
1052
-
1053
1099
  function getRequireHandlers() {
1054
- const requiredSources = [];
1055
- const requiredBySource = Object.create(null);
1056
- const requiredByNode = new Map();
1057
- const requireExpressionsWithUsedReturnValue = [];
1058
-
1059
- function addRequireStatement(sourceId, node, scope, usesReturnValue) {
1060
- const required = getRequired(sourceId);
1061
- requiredByNode.set(node, { scope, required });
1062
- if (usesReturnValue) {
1063
- required.nodesUsingRequired.push(node);
1064
- requireExpressionsWithUsedReturnValue.push(node);
1065
- }
1066
- }
1067
-
1068
- function getRequired(sourceId) {
1069
- if (!requiredBySource[sourceId]) {
1070
- requiredSources.push(sourceId);
1071
-
1072
- requiredBySource[sourceId] = {
1073
- source: sourceId,
1074
- name: null,
1075
- nodesUsingRequired: []
1076
- };
1077
- }
1078
-
1079
- return requiredBySource[sourceId];
1100
+ const requireExpressions = [];
1101
+
1102
+ function addRequireStatement(
1103
+ sourceId,
1104
+ node,
1105
+ scope,
1106
+ usesReturnValue,
1107
+ isInsideTryBlock,
1108
+ isInsideConditional,
1109
+ toBeRemoved
1110
+ ) {
1111
+ requireExpressions.push({
1112
+ sourceId,
1113
+ node,
1114
+ scope,
1115
+ usesReturnValue,
1116
+ isInsideTryBlock,
1117
+ isInsideConditional,
1118
+ toBeRemoved
1119
+ });
1080
1120
  }
1081
1121
 
1082
- function rewriteRequireExpressionsAndGetImportBlock(
1122
+ async function rewriteRequireExpressionsAndGetImportBlock(
1083
1123
  magicString,
1084
1124
  topLevelDeclarations,
1085
- topLevelRequireDeclarators,
1086
1125
  reassignedNames,
1087
1126
  helpersName,
1088
- dynamicRegisterSources,
1127
+ dynamicRequireName,
1089
1128
  moduleName,
1090
1129
  exportsName,
1091
1130
  id,
1092
- exportMode
1131
+ exportMode,
1132
+ resolveRequireSourcesAndGetMeta,
1133
+ needsRequireWrapper,
1134
+ isEsModule,
1135
+ usesRequire,
1136
+ getIgnoreTryCatchRequireStatementMode
1093
1137
  ) {
1094
- setRemainingImportNamesAndRewriteRequires(
1095
- requireExpressionsWithUsedReturnValue,
1096
- requiredByNode,
1097
- magicString
1098
- );
1099
1138
  const imports = [];
1100
1139
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1140
+ if (usesRequire) {
1141
+ imports.push(
1142
+ `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1143
+ );
1144
+ }
1101
1145
  if (exportMode === 'module') {
1102
1146
  imports.push(
1103
1147
  `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
@@ -1109,58 +1153,115 @@ function getRequireHandlers() {
1109
1153
  `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
1110
1154
  );
1111
1155
  }
1112
- for (const source of dynamicRegisterSources) {
1113
- imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1114
- }
1115
- for (const source of requiredSources) {
1116
- if (!source.startsWith('\0')) {
1117
- imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1118
- }
1119
- const { name, nodesUsingRequired } = requiredBySource[source];
1120
- imports.push(
1121
- `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
1122
- source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
1123
- )};`
1124
- );
1125
- }
1126
- return imports.length ? `${imports.join('\n')}\n\n` : '';
1156
+ const requiresBySource = collectSources(requireExpressions);
1157
+ const { requireTargets, usesRequireWrapper } = await resolveRequireSourcesAndGetMeta(
1158
+ id,
1159
+ needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1160
+ Object.keys(requiresBySource).map((source) => {
1161
+ return {
1162
+ source,
1163
+ isConditional: requiresBySource[source].every((require) => require.isInsideConditional)
1164
+ };
1165
+ })
1166
+ );
1167
+ processRequireExpressions(
1168
+ imports,
1169
+ requireTargets,
1170
+ requiresBySource,
1171
+ getIgnoreTryCatchRequireStatementMode,
1172
+ magicString
1173
+ );
1174
+ return {
1175
+ importBlock: imports.length ? `${imports.join('\n')}\n\n` : '',
1176
+ usesRequireWrapper
1177
+ };
1127
1178
  }
1128
1179
 
1129
1180
  return {
1130
1181
  addRequireStatement,
1131
- requiredSources,
1132
1182
  rewriteRequireExpressionsAndGetImportBlock
1133
1183
  };
1134
1184
  }
1135
1185
 
1136
- function setRemainingImportNamesAndRewriteRequires(
1137
- requireExpressionsWithUsedReturnValue,
1138
- requiredByNode,
1186
+ function collectSources(requireExpressions) {
1187
+ const requiresBySource = Object.create(null);
1188
+ for (const requireExpression of requireExpressions) {
1189
+ const { sourceId } = requireExpression;
1190
+ if (!requiresBySource[sourceId]) {
1191
+ requiresBySource[sourceId] = [];
1192
+ }
1193
+ const requires = requiresBySource[sourceId];
1194
+ requires.push(requireExpression);
1195
+ }
1196
+ return requiresBySource;
1197
+ }
1198
+
1199
+ function processRequireExpressions(
1200
+ imports,
1201
+ requireTargets,
1202
+ requiresBySource,
1203
+ getIgnoreTryCatchRequireStatementMode,
1139
1204
  magicString
1140
1205
  ) {
1141
- let uid = 0;
1142
- for (const requireExpression of requireExpressionsWithUsedReturnValue) {
1143
- const { required } = requiredByNode.get(requireExpression);
1144
- if (!required.name) {
1145
- let potentialName;
1146
- const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
1147
- do {
1148
- potentialName = `require$$${uid}`;
1149
- uid += 1;
1150
- } while (required.nodesUsingRequired.some(isUsedName));
1151
- required.name = potentialName;
1206
+ const generateRequireName = getGenerateRequireName();
1207
+ for (const { source, id: resolvedId, isCommonJS } of requireTargets) {
1208
+ const requires = requiresBySource[source];
1209
+ const name = generateRequireName(requires);
1210
+ let usesRequired = false;
1211
+ let needsImport = false;
1212
+ for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
1213
+ const { canConvertRequire, shouldRemoveRequire } =
1214
+ isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX)
1215
+ ? getIgnoreTryCatchRequireStatementMode(source)
1216
+ : { canConvertRequire: true, shouldRemoveRequire: false };
1217
+ if (shouldRemoveRequire) {
1218
+ if (usesReturnValue) {
1219
+ magicString.overwrite(node.start, node.end, 'undefined');
1220
+ } else {
1221
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1222
+ }
1223
+ } else if (canConvertRequire) {
1224
+ needsImport = true;
1225
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1226
+ magicString.overwrite(node.start, node.end, `${name}()`);
1227
+ } else if (usesReturnValue) {
1228
+ usesRequired = true;
1229
+ magicString.overwrite(node.start, node.end, name);
1230
+ } else {
1231
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1232
+ }
1233
+ }
1234
+ }
1235
+ if (needsImport) {
1236
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1237
+ imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)};`);
1238
+ } else {
1239
+ imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)};`);
1240
+ }
1152
1241
  }
1153
- magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
1154
1242
  }
1155
1243
  }
1156
1244
 
1245
+ function getGenerateRequireName() {
1246
+ let uid = 0;
1247
+ return (requires) => {
1248
+ let name;
1249
+ const hasNameConflict = ({ scope }) => scope.contains(name);
1250
+ do {
1251
+ name = `require$$${uid}`;
1252
+ uid += 1;
1253
+ } while (requires.some(hasNameConflict));
1254
+ return name;
1255
+ };
1256
+ }
1257
+
1157
1258
  /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
1158
1259
 
1159
1260
  const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
1160
1261
 
1161
1262
  const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
1162
1263
 
1163
- function transformCommonjs(
1264
+ async function transformCommonjs(
1164
1265
  parse,
1165
1266
  code,
1166
1267
  id,
@@ -1171,11 +1272,14 @@ function transformCommonjs(
1171
1272
  getIgnoreTryCatchRequireStatementMode,
1172
1273
  sourceMap,
1173
1274
  isDynamicRequireModulesEnabled,
1174
- dynamicRequireModuleSet,
1175
- disableWrap,
1275
+ dynamicRequireModules,
1176
1276
  commonDir,
1177
1277
  astCache,
1178
- defaultIsModuleExports
1278
+ defaultIsModuleExports,
1279
+ needsRequireWrapper,
1280
+ resolveRequireSourcesAndGetMeta,
1281
+ isRequired,
1282
+ checkDynamicRequire
1179
1283
  ) {
1180
1284
  const ast = astCache || tryParse(parse, code, id);
1181
1285
  const magicString = new MagicString(code);
@@ -1185,7 +1289,6 @@ function transformCommonjs(
1185
1289
  global: false,
1186
1290
  require: false
1187
1291
  };
1188
- let usesDynamicRequire = false;
1189
1292
  const virtualDynamicRequirePath =
1190
1293
  isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);
1191
1294
  let scope = attachScopes(ast, 'scope');
@@ -1195,24 +1298,18 @@ function transformCommonjs(
1195
1298
  let shouldWrap = false;
1196
1299
 
1197
1300
  const globals = new Set();
1198
-
1199
- // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
1200
- const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');
1201
- const dynamicRegisterSources = new Set();
1202
- let hasRemovedRequire = false;
1203
-
1204
- const {
1205
- addRequireStatement,
1206
- requiredSources,
1207
- rewriteRequireExpressionsAndGetImportBlock
1208
- } = getRequireHandlers();
1301
+ // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
1302
+ // or contains nested requires, those should be handled as function calls unless there is an
1303
+ // unconditional require elsewhere.
1304
+ let currentConditionalNodeEnd = null;
1305
+ const conditionalNodes = new Set();
1306
+ const { addRequireStatement, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1209
1307
 
1210
1308
  // See which names are assigned to. This is necessary to prevent
1211
1309
  // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
1212
1310
  // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
1213
1311
  const reassignedNames = new Set();
1214
1312
  const topLevelDeclarations = [];
1215
- const topLevelRequireDeclarators = new Set();
1216
1313
  const skippedNodes = new Set();
1217
1314
  const moduleAccessScopes = new Set([scope]);
1218
1315
  const exportsAccessScopes = new Set([scope]);
@@ -1221,6 +1318,8 @@ function transformCommonjs(
1221
1318
  const exportsAssignmentsByName = new Map();
1222
1319
  const topLevelAssignments = new Set();
1223
1320
  const topLevelDefineCompiledEsmExpressions = [];
1321
+ const replacedGlobal = [];
1322
+ const replacedDynamicRequires = [];
1224
1323
 
1225
1324
  walk(ast, {
1226
1325
  enter(node, parent) {
@@ -1232,6 +1331,12 @@ function transformCommonjs(
1232
1331
  if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
1233
1332
  currentTryBlockEnd = null;
1234
1333
  }
1334
+ if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) {
1335
+ currentConditionalNodeEnd = null;
1336
+ }
1337
+ if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) {
1338
+ currentConditionalNodeEnd = node.end;
1339
+ }
1235
1340
 
1236
1341
  programDepth += 1;
1237
1342
  if (node.scope) ({ scope } = node);
@@ -1243,11 +1348,6 @@ function transformCommonjs(
1243
1348
 
1244
1349
  // eslint-disable-next-line default-case
1245
1350
  switch (node.type) {
1246
- case 'TryStatement':
1247
- if (currentTryBlockEnd === null) {
1248
- currentTryBlockEnd = node.block.end;
1249
- }
1250
- return;
1251
1351
  case 'AssignmentExpression':
1252
1352
  if (node.left.type === 'MemberExpression') {
1253
1353
  const flattened = getKeypath(node.left);
@@ -1318,12 +1418,15 @@ function transformCommonjs(
1318
1418
  return;
1319
1419
  }
1320
1420
 
1421
+ // Transform require.resolve
1321
1422
  if (
1423
+ isDynamicRequireModulesEnabled &&
1322
1424
  node.callee.object &&
1323
- node.callee.object.name === 'require' &&
1324
- node.callee.property.name === 'resolve' &&
1325
- hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
1425
+ isRequire(node.callee.object, scope) &&
1426
+ node.callee.property.name === 'resolve'
1326
1427
  ) {
1428
+ checkDynamicRequire();
1429
+ uses.require = true;
1327
1430
  const requireNode = node.callee.object;
1328
1431
  magicString.appendLeft(
1329
1432
  node.end - 1,
@@ -1331,98 +1434,45 @@ function transformCommonjs(
1331
1434
  dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1332
1435
  )}`
1333
1436
  );
1334
- magicString.overwrite(
1335
- requireNode.start,
1336
- requireNode.end,
1337
- `${HELPERS_NAME}.commonjsRequire`,
1338
- {
1339
- storeName: true
1340
- }
1341
- );
1437
+ replacedDynamicRequires.push(requireNode);
1342
1438
  return;
1343
1439
  }
1344
1440
 
1345
- if (!isStaticRequireStatement(node, scope)) return;
1346
- if (!isDynamicRequireModulesEnabled) {
1347
- skippedNodes.add(node.callee);
1441
+ if (!isRequireExpression(node, scope)) {
1442
+ return;
1348
1443
  }
1349
- if (!isIgnoredRequireStatement(node, ignoreRequire)) {
1350
- skippedNodes.add(node.callee);
1351
- const usesReturnValue = parent.type !== 'ExpressionStatement';
1352
-
1353
- let canConvertRequire = true;
1354
- let shouldRemoveRequireStatement = false;
1355
1444
 
1356
- if (currentTryBlockEnd !== null) {
1357
- ({
1358
- canConvertRequire,
1359
- shouldRemoveRequireStatement
1360
- } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
1361
-
1362
- if (shouldRemoveRequireStatement) {
1363
- hasRemovedRequire = true;
1364
- }
1445
+ skippedNodes.add(node.callee);
1446
+ uses.require = true;
1447
+
1448
+ if (hasDynamicArguments(node)) {
1449
+ if (isDynamicRequireModulesEnabled) {
1450
+ magicString.appendLeft(
1451
+ node.end - 1,
1452
+ `, ${JSON.stringify(
1453
+ dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1454
+ )}`
1455
+ );
1365
1456
  }
1366
-
1367
- let sourceId = getRequireStringArg(node);
1368
- const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1369
- if (isDynamicRegister) {
1370
- sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1371
- if (sourceId.endsWith('.json')) {
1372
- sourceId = DYNAMIC_JSON_PREFIX + sourceId;
1373
- }
1374
- dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
1375
- } else {
1376
- if (
1377
- !sourceId.endsWith('.json') &&
1378
- hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
1379
- ) {
1380
- if (shouldRemoveRequireStatement) {
1381
- magicString.overwrite(node.start, node.end, `undefined`);
1382
- } else if (canConvertRequire) {
1383
- magicString.overwrite(
1384
- node.start,
1385
- node.end,
1386
- `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
1387
- getVirtualPathForDynamicRequirePath(sourceId, commonDir)
1388
- )}, ${JSON.stringify(
1389
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1390
- )})`
1391
- );
1392
- usesDynamicRequire = true;
1393
- }
1394
- return;
1395
- }
1396
-
1397
- if (canConvertRequire) {
1398
- addRequireStatement(sourceId, node, scope, usesReturnValue);
1399
- }
1457
+ if (!ignoreDynamicRequires) {
1458
+ checkDynamicRequire();
1459
+ replacedDynamicRequires.push(node.callee);
1400
1460
  }
1461
+ return;
1462
+ }
1401
1463
 
1402
- if (usesReturnValue) {
1403
- if (shouldRemoveRequireStatement) {
1404
- magicString.overwrite(node.start, node.end, `undefined`);
1405
- return;
1406
- }
1407
-
1408
- if (
1409
- parent.type === 'VariableDeclarator' &&
1410
- !scope.parent &&
1411
- parent.id.type === 'Identifier'
1412
- ) {
1413
- // This will allow us to reuse this variable name as the imported variable if it is not reassigned
1414
- // and does not conflict with variables in other places where this is imported
1415
- topLevelRequireDeclarators.add(parent);
1416
- }
1417
- } else {
1418
- // This is a bare import, e.g. `require('foo');`
1419
-
1420
- if (!canConvertRequire && !shouldRemoveRequireStatement) {
1421
- return;
1422
- }
1423
-
1424
- magicString.remove(parent.start, parent.end);
1425
- }
1464
+ const requireStringArg = getRequireStringArg(node);
1465
+ if (!ignoreRequire(requireStringArg)) {
1466
+ const usesReturnValue = parent.type !== 'ExpressionStatement';
1467
+ addRequireStatement(
1468
+ requireStringArg,
1469
+ node,
1470
+ scope,
1471
+ usesReturnValue,
1472
+ currentTryBlockEnd !== null,
1473
+ currentConditionalNodeEnd !== null,
1474
+ parent.type === 'ExpressionStatement' ? parent : node
1475
+ );
1426
1476
  }
1427
1477
  return;
1428
1478
  }
@@ -1431,45 +1481,44 @@ function transformCommonjs(
1431
1481
  // skip dead branches
1432
1482
  if (isFalsy(node.test)) {
1433
1483
  skippedNodes.add(node.consequent);
1434
- } else if (node.alternate && isTruthy(node.test)) {
1435
- skippedNodes.add(node.alternate);
1484
+ } else if (isTruthy(node.test)) {
1485
+ if (node.alternate) {
1486
+ skippedNodes.add(node.alternate);
1487
+ }
1488
+ } else {
1489
+ conditionalNodes.add(node.consequent);
1490
+ if (node.alternate) {
1491
+ conditionalNodes.add(node.alternate);
1492
+ }
1493
+ }
1494
+ return;
1495
+ case 'ArrowFunctionExpression':
1496
+ case 'FunctionDeclaration':
1497
+ case 'FunctionExpression':
1498
+ // requires in functions should be conditional unless it is an IIFE
1499
+ if (
1500
+ currentConditionalNodeEnd === null &&
1501
+ !(parent.type === 'CallExpression' && parent.callee === node)
1502
+ ) {
1503
+ currentConditionalNodeEnd = node.end;
1436
1504
  }
1437
1505
  return;
1438
1506
  case 'Identifier': {
1439
1507
  const { name } = node;
1440
- if (!(isReference(node, parent) && !scope.contains(name))) return;
1508
+ if (!isReference(node, parent) || scope.contains(name)) return;
1441
1509
  switch (name) {
1442
1510
  case 'require':
1511
+ uses.require = true;
1443
1512
  if (isNodeRequirePropertyAccess(parent)) {
1444
- if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
1445
- if (parent.property.name === 'cache') {
1446
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1447
- storeName: true
1448
- });
1449
- }
1450
- }
1451
-
1452
1513
  return;
1453
1514
  }
1454
-
1455
- if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
1456
- magicString.appendLeft(
1457
- parent.end - 1,
1458
- `,${JSON.stringify(
1459
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1460
- )}`
1461
- );
1462
- }
1463
1515
  if (!ignoreDynamicRequires) {
1516
+ checkDynamicRequire();
1464
1517
  if (isShorthandProperty(parent)) {
1465
- magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1466
- } else {
1467
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1468
- storeName: true
1469
- });
1518
+ magicString.prependRight(node.start, 'require: ');
1470
1519
  }
1520
+ replacedDynamicRequires.push(node);
1471
1521
  }
1472
- usesDynamicRequire = true;
1473
1522
  return;
1474
1523
  case 'module':
1475
1524
  case 'exports':
@@ -1479,9 +1528,7 @@ function transformCommonjs(
1479
1528
  case 'global':
1480
1529
  uses.global = true;
1481
1530
  if (!ignoreGlobal) {
1482
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1483
- storeName: true
1484
- });
1531
+ replacedGlobal.push(node);
1485
1532
  }
1486
1533
  return;
1487
1534
  case 'define':
@@ -1494,11 +1541,26 @@ function transformCommonjs(
1494
1541
  return;
1495
1542
  }
1496
1543
  }
1544
+ case 'LogicalExpression':
1545
+ // skip dead branches
1546
+ if (node.operator === '&&') {
1547
+ if (isFalsy(node.left)) {
1548
+ skippedNodes.add(node.right);
1549
+ } else if (!isTruthy(node.left)) {
1550
+ conditionalNodes.add(node.right);
1551
+ }
1552
+ } else if (node.operator === '||') {
1553
+ if (isTruthy(node.left)) {
1554
+ skippedNodes.add(node.right);
1555
+ } else if (!isFalsy(node.left)) {
1556
+ conditionalNodes.add(node.right);
1557
+ }
1558
+ }
1559
+ return;
1497
1560
  case 'MemberExpression':
1498
1561
  if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
1499
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1500
- storeName: true
1501
- });
1562
+ uses.require = true;
1563
+ replacedDynamicRequires.push(node);
1502
1564
  skippedNodes.add(node.object);
1503
1565
  skippedNodes.add(node.property);
1504
1566
  }
@@ -1514,12 +1576,18 @@ function transformCommonjs(
1514
1576
  if (lexicalDepth === 0) {
1515
1577
  uses.global = true;
1516
1578
  if (!ignoreGlobal) {
1517
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1518
- storeName: true
1519
- });
1579
+ replacedGlobal.push(node);
1520
1580
  }
1521
1581
  }
1522
1582
  return;
1583
+ case 'TryStatement':
1584
+ if (currentTryBlockEnd === null) {
1585
+ currentTryBlockEnd = node.block.end;
1586
+ }
1587
+ if (currentConditionalNodeEnd === null) {
1588
+ currentConditionalNodeEnd = node.end;
1589
+ }
1590
+ return;
1523
1591
  case 'UnaryExpression':
1524
1592
  // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
1525
1593
  if (node.operator === 'typeof') {
@@ -1556,34 +1624,45 @@ function transformCommonjs(
1556
1624
  const nameBase = getName(id);
1557
1625
  const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
1558
1626
  const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
1627
+ const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1628
+ const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1629
+ const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1630
+ const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
1559
1631
  const deconflictedExportNames = Object.create(null);
1560
1632
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1561
1633
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
1562
1634
  }
1563
1635
 
1636
+ for (const node of replacedGlobal) {
1637
+ magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, {
1638
+ storeName: true
1639
+ });
1640
+ }
1641
+ for (const node of replacedDynamicRequires) {
1642
+ magicString.overwrite(node.start, node.end, dynamicRequireName, {
1643
+ contentOnly: true,
1644
+ storeName: true
1645
+ });
1646
+ }
1647
+
1564
1648
  // We cannot wrap ES/mixed modules
1565
- shouldWrap =
1566
- !isEsModule &&
1567
- !disableWrap &&
1568
- (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1649
+ shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1569
1650
  const detectWrappedDefault =
1570
1651
  shouldWrap &&
1571
1652
  (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
1572
1653
 
1573
1654
  if (
1574
1655
  !(
1575
- requiredSources.length ||
1576
- dynamicRegisterSources.size ||
1656
+ shouldWrap ||
1657
+ isRequired ||
1577
1658
  uses.module ||
1578
1659
  uses.exports ||
1579
1660
  uses.require ||
1580
- usesDynamicRequire ||
1581
- hasRemovedRequire ||
1582
1661
  topLevelDefineCompiledEsmExpressions.length > 0
1583
1662
  ) &&
1584
1663
  (ignoreGlobal || !uses.global)
1585
1664
  ) {
1586
- return { meta: { commonjs: { isCommonJS: false } } };
1665
+ return { meta: { commonjs: { isCommonJS: false, isMixedModule: false } } };
1587
1666
  }
1588
1667
 
1589
1668
  let leadingComment = '';
@@ -1605,19 +1684,22 @@ function transformCommonjs(
1605
1684
  ? 'exports'
1606
1685
  : 'module';
1607
1686
 
1608
- const importBlock = rewriteRequireExpressionsAndGetImportBlock(
1687
+ const { importBlock, usesRequireWrapper } = await rewriteRequireExpressionsAndGetImportBlock(
1609
1688
  magicString,
1610
1689
  topLevelDeclarations,
1611
- topLevelRequireDeclarators,
1612
1690
  reassignedNames,
1613
- HELPERS_NAME,
1614
- dynamicRegisterSources,
1691
+ helpersName,
1692
+ dynamicRequireName,
1615
1693
  moduleName,
1616
1694
  exportsName,
1617
1695
  id,
1618
- exportMode
1696
+ exportMode,
1697
+ resolveRequireSourcesAndGetMeta,
1698
+ needsRequireWrapper,
1699
+ isEsModule,
1700
+ uses.require,
1701
+ getIgnoreTryCatchRequireStatementMode
1619
1702
  );
1620
-
1621
1703
  const exportBlock = isEsModule
1622
1704
  ? ''
1623
1705
  : rewriteExportsAndGetExportsBlock(
@@ -1632,16 +1714,35 @@ function transformCommonjs(
1632
1714
  topLevelDefineCompiledEsmExpressions,
1633
1715
  deconflictedExportNames,
1634
1716
  code,
1635
- HELPERS_NAME,
1717
+ helpersName,
1636
1718
  exportMode,
1637
1719
  detectWrappedDefault,
1638
- defaultIsModuleExports
1720
+ defaultIsModuleExports,
1721
+ usesRequireWrapper,
1722
+ requireName
1639
1723
  );
1640
1724
 
1641
1725
  if (shouldWrap) {
1642
1726
  wrapCode(magicString, uses, moduleName, exportsName);
1643
1727
  }
1644
1728
 
1729
+ if (usesRequireWrapper) {
1730
+ magicString.trim().indent('\t');
1731
+ magicString.prepend(
1732
+ `var ${isRequiredName};
1733
+
1734
+ function ${requireName} () {
1735
+ \tif (${isRequiredName}) return ${exportsName};
1736
+ \t${isRequiredName} = 1;
1737
+ `
1738
+ ).append(`
1739
+ \treturn ${exportsName};
1740
+ }`);
1741
+ if (exportMode === 'replace') {
1742
+ magicString.prepend(`var ${exportsName};\n`);
1743
+ }
1744
+ }
1745
+
1645
1746
  magicString
1646
1747
  .trim()
1647
1748
  .prepend(leadingComment + importBlock)
@@ -1650,24 +1751,32 @@ function transformCommonjs(
1650
1751
  return {
1651
1752
  code: magicString.toString(),
1652
1753
  map: sourceMap ? magicString.generateMap() : null,
1653
- syntheticNamedExports: isEsModule ? false : '__moduleExports',
1654
- meta: { commonjs: { isCommonJS: !isEsModule } }
1754
+ syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
1755
+ meta: {
1756
+ commonjs: {
1757
+ isCommonJS: !isEsModule && (usesRequireWrapper ? IS_WRAPPED_COMMONJS : true),
1758
+ isMixedModule: isEsModule
1759
+ }
1760
+ }
1655
1761
  };
1656
1762
  }
1657
1763
 
1658
1764
  function commonjs(options = {}) {
1659
- const extensions = options.extensions || ['.js'];
1660
- const filter = createFilter(options.include, options.exclude);
1661
1765
  const {
1662
1766
  ignoreGlobal,
1663
1767
  ignoreDynamicRequires,
1664
1768
  requireReturnsDefault: requireReturnsDefaultOption,
1665
1769
  esmExternals
1666
1770
  } = options;
1771
+ const extensions = options.extensions || ['.js'];
1772
+ const filter = createFilter(options.include, options.exclude);
1773
+ const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
1774
+
1667
1775
  const getRequireReturnsDefault =
1668
1776
  typeof requireReturnsDefaultOption === 'function'
1669
1777
  ? requireReturnsDefaultOption
1670
1778
  : () => requireReturnsDefaultOption;
1779
+
1671
1780
  let esmExternalIds;
1672
1781
  const isEsmExternal =
1673
1782
  typeof esmExternals === 'function'
@@ -1675,20 +1784,27 @@ function commonjs(options = {}) {
1675
1784
  : Array.isArray(esmExternals)
1676
1785
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1677
1786
  : () => esmExternals;
1787
+
1678
1788
  const defaultIsModuleExports =
1679
1789
  typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1680
1790
 
1681
- const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1682
- options.dynamicRequireTargets
1791
+ const {
1792
+ resolveRequireSourcesAndGetMeta,
1793
+ getWrappedIds,
1794
+ isRequiredId
1795
+ } = getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional);
1796
+ const dynamicRequireRoot =
1797
+ typeof options.dynamicRequireRoot === 'string'
1798
+ ? resolve(options.dynamicRequireRoot)
1799
+ : process.cwd();
1800
+ const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
1801
+ options.dynamicRequireTargets,
1802
+ dynamicRequireRoot
1683
1803
  );
1684
- const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
1685
- const commonDir = isDynamicRequireModulesEnabled
1686
- ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1687
- : null;
1804
+ const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1688
1805
 
1689
1806
  const esModulesWithDefaultExport = new Set();
1690
1807
  const esModulesWithNamedExports = new Set();
1691
- const commonJsMetaPromises = new Map();
1692
1808
 
1693
1809
  const ignoreRequire =
1694
1810
  typeof options.ignore === 'function'
@@ -1703,11 +1819,13 @@ function commonjs(options = {}) {
1703
1819
  ? options.ignoreTryCatch(id)
1704
1820
  : Array.isArray(options.ignoreTryCatch)
1705
1821
  ? options.ignoreTryCatch.includes(id)
1706
- : options.ignoreTryCatch || false;
1822
+ : typeof options.ignoreTryCatch !== 'undefined'
1823
+ ? options.ignoreTryCatch
1824
+ : true;
1707
1825
 
1708
1826
  return {
1709
1827
  canConvertRequire: mode !== 'remove' && mode !== true,
1710
- shouldRemoveRequireStatement: mode === 'remove'
1828
+ shouldRemoveRequire: mode === 'remove'
1711
1829
  };
1712
1830
  };
1713
1831
 
@@ -1716,12 +1834,6 @@ function commonjs(options = {}) {
1716
1834
  const sourceMap = options.sourceMap !== false;
1717
1835
 
1718
1836
  function transformAndCheckExports(code, id) {
1719
- if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1720
- // eslint-disable-next-line no-param-reassign
1721
- code =
1722
- getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1723
- }
1724
-
1725
1837
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1726
1838
  this.parse,
1727
1839
  code,
@@ -1735,18 +1847,29 @@ function commonjs(options = {}) {
1735
1847
  }
1736
1848
 
1737
1849
  if (
1738
- !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1739
- (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1850
+ !dynamicRequireModules.has(normalizePathSlashes(id)) &&
1851
+ (!(hasCjsKeywords(code, ignoreGlobal) || isRequiredId(id)) ||
1852
+ (isEsModule && !options.transformMixedEsModules))
1740
1853
  ) {
1741
1854
  return { meta: { commonjs: { isCommonJS: false } } };
1742
1855
  }
1743
1856
 
1744
- // avoid wrapping as this is a commonjsRegister call
1745
- const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
1746
- if (disableWrap) {
1747
- // eslint-disable-next-line no-param-reassign
1748
- id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1749
- }
1857
+ const needsRequireWrapper =
1858
+ !isEsModule &&
1859
+ (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1860
+
1861
+ const checkDynamicRequire = () => {
1862
+ if (id.indexOf(dynamicRequireRoot) !== 0) {
1863
+ this.error({
1864
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1865
+ id,
1866
+ dynamicRequireRoot,
1867
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(
1868
+ id
1869
+ )}" or one of its parent directories.`
1870
+ });
1871
+ }
1872
+ };
1750
1873
 
1751
1874
  return transformCommonjs(
1752
1875
  this.parse,
@@ -1759,17 +1882,37 @@ function commonjs(options = {}) {
1759
1882
  getIgnoreTryCatchRequireStatementMode,
1760
1883
  sourceMap,
1761
1884
  isDynamicRequireModulesEnabled,
1762
- dynamicRequireModuleSet,
1763
- disableWrap,
1885
+ dynamicRequireModules,
1764
1886
  commonDir,
1765
1887
  ast,
1766
- defaultIsModuleExports
1888
+ defaultIsModuleExports,
1889
+ needsRequireWrapper,
1890
+ resolveRequireSourcesAndGetMeta(this),
1891
+ isRequiredId(id),
1892
+ checkDynamicRequire
1767
1893
  );
1768
1894
  }
1769
1895
 
1770
1896
  return {
1771
1897
  name: 'commonjs',
1772
1898
 
1899
+ version,
1900
+
1901
+ options(rawOptions) {
1902
+ // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
1903
+ // do not prevent our plugin from resolving entry points ot proxies.
1904
+ const plugins = Array.isArray(rawOptions.plugins)
1905
+ ? rawOptions.plugins
1906
+ : rawOptions.plugins
1907
+ ? [rawOptions.plugins]
1908
+ : [];
1909
+ plugins.unshift({
1910
+ name: 'commonjs--resolver',
1911
+ resolveId
1912
+ });
1913
+ return { ...rawOptions, plugins };
1914
+ },
1915
+
1773
1916
  buildStart() {
1774
1917
  validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1775
1918
  if (options.namedExports != null) {
@@ -1779,44 +1922,43 @@ function commonjs(options = {}) {
1779
1922
  }
1780
1923
  },
1781
1924
 
1782
- resolveId,
1925
+ buildEnd() {
1926
+ if (options.strictRequires === 'debug') {
1927
+ const wrappedIds = getWrappedIds();
1928
+ if (wrappedIds.length) {
1929
+ this.warn({
1930
+ code: 'WRAPPED_IDS',
1931
+ ids: wrappedIds,
1932
+ message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds
1933
+ .map((id) => `\t${JSON.stringify(relative(process.cwd(), id))}`)
1934
+ .join(',\n')}\n]`
1935
+ });
1936
+ } else {
1937
+ this.warn({
1938
+ code: 'WRAPPED_IDS',
1939
+ ids: wrappedIds,
1940
+ message: 'The commonjs plugin did not wrap any files.'
1941
+ });
1942
+ }
1943
+ }
1944
+ },
1783
1945
 
1784
1946
  load(id) {
1785
1947
  if (id === HELPERS_ID) {
1786
- return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
1787
- }
1788
-
1789
- if (id.startsWith(HELPERS_ID)) {
1790
- return getSpecificHelperProxy(id);
1948
+ return getHelpersModule();
1791
1949
  }
1792
1950
 
1793
1951
  if (isWrappedId(id, MODULE_SUFFIX)) {
1794
- const actualId = unwrapId(id, MODULE_SUFFIX);
1795
- let name = getName(actualId);
1796
- let code;
1797
- if (isDynamicRequireModulesEnabled) {
1798
- if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
1799
- name = `${name}_`;
1800
- }
1801
- code =
1802
- `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
1803
- `var ${name} = createModule(${JSON.stringify(
1804
- getVirtualPathForDynamicRequirePath(dirname(actualId), commonDir)
1805
- )});\n` +
1806
- `export {${name} as __module}`;
1807
- } else {
1808
- code = `var ${name} = {exports: {}}; export {${name} as __module}`;
1809
- }
1952
+ const name = getName(unwrapId(id, MODULE_SUFFIX));
1810
1953
  return {
1811
- code,
1954
+ code: `var ${name} = {exports: {}}; export {${name} as __module}`,
1812
1955
  syntheticNamedExports: '__module',
1813
1956
  meta: { commonjs: { isCommonJS: false } }
1814
1957
  };
1815
1958
  }
1816
1959
 
1817
1960
  if (isWrappedId(id, EXPORTS_SUFFIX)) {
1818
- const actualId = unwrapId(id, EXPORTS_SUFFIX);
1819
- const name = getName(actualId);
1961
+ const name = getName(unwrapId(id, EXPORTS_SUFFIX));
1820
1962
  return {
1821
1963
  code: `var ${name} = {}; export {${name} as __exports}`,
1822
1964
  meta: { commonjs: { isCommonJS: false } }
@@ -1831,22 +1973,16 @@ function commonjs(options = {}) {
1831
1973
  );
1832
1974
  }
1833
1975
 
1834
- if (id === DYNAMIC_PACKAGES_ID) {
1835
- return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
1836
- }
1837
-
1838
- if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
1839
- return getDynamicJsonProxy(id, commonDir);
1840
- }
1841
-
1842
- if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
1843
- return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
1976
+ if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
1977
+ return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
1844
1978
  }
1845
1979
 
1846
- if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1847
- return getDynamicRequireProxy(
1848
- normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
1849
- commonDir
1980
+ if (id === DYNAMIC_MODULES_ID) {
1981
+ return getDynamicModuleRegistry(
1982
+ isDynamicRequireModulesEnabled,
1983
+ dynamicRequireModules,
1984
+ commonDir,
1985
+ ignoreDynamicRequires
1850
1986
  );
1851
1987
  }
1852
1988
 
@@ -1857,46 +1993,27 @@ function commonjs(options = {}) {
1857
1993
  getRequireReturnsDefault(actualId),
1858
1994
  esModulesWithDefaultExport,
1859
1995
  esModulesWithNamedExports,
1860
- commonJsMetaPromises
1996
+ this.load
1861
1997
  );
1862
1998
  }
1863
1999
 
1864
2000
  return null;
1865
2001
  },
1866
2002
 
1867
- transform(code, rawId) {
1868
- let id = rawId;
1869
-
1870
- if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1871
- id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1872
- }
1873
-
2003
+ transform(code, id) {
1874
2004
  const extName = extname(id);
1875
- if (
1876
- extName !== '.cjs' &&
1877
- id !== DYNAMIC_PACKAGES_ID &&
1878
- !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1879
- (!filter(id) || !extensions.includes(extName))
1880
- ) {
2005
+ if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {
1881
2006
  return null;
1882
2007
  }
1883
2008
 
1884
2009
  try {
1885
- return transformAndCheckExports.call(this, code, rawId);
2010
+ return transformAndCheckExports.call(this, code, id);
1886
2011
  } catch (err) {
1887
2012
  return this.error(err, err.loc);
1888
2013
  }
1889
- },
1890
-
1891
- moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
1892
- if (commonjsMeta && commonjsMeta.isCommonJS != null) {
1893
- setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
1894
- return;
1895
- }
1896
- setCommonJSMetaPromise(commonJsMetaPromises, id, null);
1897
2014
  }
1898
2015
  };
1899
2016
  }
1900
2017
 
1901
- export default commonjs;
2018
+ export { commonjs as default };
1902
2019
  //# sourceMappingURL=index.es.js.map