@rollup/plugin-commonjs 19.0.2 → 22.0.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,15 +1,15 @@
1
- import { basename, extname, dirname, sep, join, resolve } 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-0";
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) {
@@ -366,21 +101,42 @@ function getName(id) {
366
101
  if (name !== 'index') {
367
102
  return name;
368
103
  }
369
- const segments = dirname(id).split(sep);
370
- return makeLegalIdentifier(segments[segments.length - 1]);
104
+ return makeLegalIdentifier(basename(dirname(id)));
371
105
  }
372
106
 
373
107
  function normalizePathSlashes(path) {
374
108
  return path.replace(/\\/g, '/');
375
109
  }
376
110
 
377
- const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
378
- const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
379
- const normalizedPath = normalizePathSlashes(path);
380
- return normalizedPath.startsWith(commonDir)
381
- ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
382
- : normalizedPath;
383
- };
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
+ }
384
140
 
385
141
  function getPackageEntryPoint(dirPath) {
386
142
  let entryPoint = 'index.js';
@@ -398,41 +154,6 @@ function getPackageEntryPoint(dirPath) {
398
154
  return entryPoint;
399
155
  }
400
156
 
401
- function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
402
- let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`;
403
- for (const dir of dynamicRequireModuleDirPaths) {
404
- const entryPoint = getPackageEntryPoint(dir);
405
-
406
- code += `\ncommonjsRegisterOrShort(${JSON.stringify(
407
- getVirtualPathForDynamicRequirePath(dir, commonDir)
408
- )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(join(dir, entryPoint), commonDir))});`;
409
- }
410
- return code;
411
- }
412
-
413
- function getDynamicPackagesEntryIntro(
414
- dynamicRequireModuleDirPaths,
415
- dynamicRequireModuleSet
416
- ) {
417
- let dynamicImports = Array.from(
418
- dynamicRequireModuleSet,
419
- (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`
420
- ).join('\n');
421
-
422
- if (dynamicRequireModuleDirPaths.length) {
423
- dynamicImports += `require(${JSON.stringify(
424
- wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)
425
- )});`;
426
- }
427
-
428
- return dynamicImports;
429
- }
430
-
431
- function isDynamicModuleImport(id, dynamicRequireModuleSet) {
432
- const normalizedPath = normalizePathSlashes(id);
433
- return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
434
- }
435
-
436
157
  function isDirectory(path) {
437
158
  try {
438
159
  if (statSync(path).isDirectory()) return true;
@@ -442,102 +163,250 @@ function isDirectory(path) {
442
163
  return false;
443
164
  }
444
165
 
445
- function getDynamicRequirePaths(patterns) {
446
- const dynamicRequireModuleSet = new Set();
166
+ function getDynamicRequireModules(patterns, dynamicRequireRoot) {
167
+ const dynamicRequireModules = new Map();
168
+ const dirNames = new Set();
447
169
  for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
448
170
  const isNegated = pattern.startsWith('!');
449
- 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);
450
175
  for (const path of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
451
- modifySet(normalizePathSlashes(resolve(path)));
452
- if (isDirectory(path)) {
453
- 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);
454
186
  }
455
187
  }
456
188
  }
457
- const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>
458
- isDirectory(path)
459
- );
460
- return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
189
+ return {
190
+ commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null,
191
+ dynamicRequireModules
192
+ };
461
193
  }
462
194
 
463
- function getCommonJSMetaPromise(commonJSMetaPromises, id) {
464
- let commonJSMetaPromise = commonJSMetaPromises.get(id);
465
- 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.');`;
466
196
 
467
- const promise = new Promise((resolve) => {
468
- commonJSMetaPromise = {
469
- resolve,
470
- promise: null
471
- };
472
- commonJSMetaPromises.set(id, commonJSMetaPromise);
473
- });
474
- 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
+ }
475
233
 
476
- 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}
477
240
  }
478
241
 
479
- function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) {
480
- const commonJSMetaPromise = commonJSMetaPromises.get(id);
481
- if (commonJSMetaPromise) {
482
- if (commonJSMetaPromise.resolve) {
483
- commonJSMetaPromise.resolve(commonjsMeta);
484
- commonJSMetaPromise.resolve = null;
485
- }
486
- } else {
487
- commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });
488
- }
242
+ function commonjsResolve (path, originalModuleDir) {
243
+ const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
244
+ if (resolvedPath !== null) {
245
+ return resolvedPath;
246
+ }
247
+ return require.resolve(path);
489
248
  }
490
249
 
491
- // e.g. id === "commonjsHelpers?commonjsRegister"
492
- function getSpecificHelperProxy(id) {
493
- 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;
494
378
  }
495
379
 
496
380
  function getUnknownRequireProxy(id, requireReturnsDefault) {
497
381
  if (requireReturnsDefault === true || id.endsWith('.json')) {
498
- return `export {default} from ${JSON.stringify(id)};`;
382
+ return `export { default } from ${JSON.stringify(id)};`;
499
383
  }
500
384
  const name = getName(id);
501
385
  const exported =
502
386
  requireReturnsDefault === 'auto'
503
- ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
387
+ ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
504
388
  : requireReturnsDefault === 'preferred'
505
- ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
389
+ ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
506
390
  : !requireReturnsDefault
507
- ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
391
+ ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
508
392
  : `export default ${name};`;
509
393
  return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
510
394
  }
511
395
 
512
- function getDynamicJsonProxy(id, commonDir) {
513
- const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
514
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
515
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
516
- )}, function (module, exports) {
517
- module.exports = require(${JSON.stringify(normalizedPath)});
518
- });`;
519
- }
520
-
521
- function getDynamicRequireProxy(normalizedPath, commonDir) {
522
- return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
523
- getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
524
- )}, function (module, exports) {
525
- ${readFileSync(normalizedPath, { encoding: 'utf8' })}
526
- });`;
527
- }
528
-
529
396
  async function getStaticRequireProxy(
530
397
  id,
531
398
  requireReturnsDefault,
532
399
  esModulesWithDefaultExport,
533
400
  esModulesWithNamedExports,
534
- commonJsMetaPromises
401
+ loadModule
535
402
  ) {
536
403
  const name = getName(id);
537
- const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id);
404
+ const {
405
+ meta: { commonjs: commonjsMeta }
406
+ } = await loadModule({ id });
538
407
  if (commonjsMeta && commonjsMeta.isCommonJS) {
539
408
  return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
540
- } else if (commonjsMeta === null) {
409
+ } else if (!commonjsMeta) {
541
410
  return getUnknownRequireProxy(id, requireReturnsDefault);
542
411
  } else if (!requireReturnsDefault) {
543
412
  return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
@@ -554,6 +423,27 @@ async function getStaticRequireProxy(
554
423
  return `export { default } from ${JSON.stringify(id)};`;
555
424
  }
556
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
+
557
447
  /* eslint-disable no-param-reassign, no-undefined */
558
448
 
559
449
  function getCandidatesForExtension(resolved, extension) {
@@ -567,86 +457,189 @@ function getCandidates(resolved, extensions) {
567
457
  );
568
458
  }
569
459
 
570
- function getResolveId(extensions) {
571
- function resolveExtensions(importee, importer) {
572
- // not our problem
573
- if (importee[0] !== '.' || !importer) return undefined;
574
-
575
- const resolved = resolve(dirname(importer), importee);
576
- const candidates = getCandidates(resolved, extensions);
577
-
578
- for (let i = 0; i < candidates.length; i += 1) {
579
- try {
580
- const stats = statSync(candidates[i]);
581
- if (stats.isFile()) return { id: candidates[i] };
582
- } catch (err) {
583
- /* noop */
584
- }
585
- }
586
-
587
- return undefined;
588
- }
589
-
590
- return function resolveId(importee, rawImporter) {
591
- if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
592
- return importee;
593
- }
594
-
595
- const importer =
596
- rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
597
- ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
598
- : rawImporter;
460
+ function resolveExtensions(importee, importer, extensions) {
461
+ // not our problem
462
+ if (importee[0] !== '.' || !importer) return undefined;
599
463
 
600
- // Except for exports, proxies are only importing resolved ids,
601
- // no need to resolve again
602
- if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
603
- return importee;
604
- }
464
+ const resolved = resolve(dirname(importer), importee);
465
+ const candidates = getCandidates(resolved, extensions);
605
466
 
606
- const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
607
- const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
608
- let isModuleRegistration = false;
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
+ }
609
475
 
610
- if (isProxyModule) {
611
- importee = unwrapId(importee, PROXY_SUFFIX);
612
- } else if (isRequiredModule) {
613
- importee = unwrapId(importee, REQUIRE_SUFFIX);
476
+ return undefined;
477
+ }
614
478
 
615
- isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
616
- if (isModuleRegistration) {
617
- importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
618
- }
479
+ function getResolveId(extensions) {
480
+ return async function resolveId(importee, importer, resolveOptions) {
481
+ if (isWrappedId(importee, WRAPPED_SUFFIX)) {
482
+ return unwrapId(importee, WRAPPED_SUFFIX);
619
483
  }
620
484
 
621
485
  if (
486
+ isWrappedId(importee, MODULE_SUFFIX) ||
487
+ isWrappedId(importee, EXPORTS_SUFFIX) ||
488
+ isWrappedId(importee, PROXY_SUFFIX) ||
489
+ isWrappedId(importee, ES_IMPORT_SUFFIX) ||
490
+ isWrappedId(importee, EXTERNAL_SUFFIX) ||
622
491
  importee.startsWith(HELPERS_ID) ||
623
- importee === DYNAMIC_PACKAGES_ID ||
624
- importee.startsWith(DYNAMIC_JSON_PREFIX)
492
+ importee === DYNAMIC_MODULES_ID
625
493
  ) {
626
494
  return importee;
627
495
  }
628
496
 
497
+ if (importer) {
498
+ if (
499
+ importer === DYNAMIC_MODULES_ID ||
500
+ // Except for exports, proxies are only importing resolved ids, no need to resolve again
501
+ isWrappedId(importer, PROXY_SUFFIX) ||
502
+ isWrappedId(importer, ES_IMPORT_SUFFIX)
503
+ ) {
504
+ return importee;
505
+ }
506
+ if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
507
+ // We need to return null for unresolved imports so that the proper warning is shown
508
+ if (!(await this.resolve(importee, importer, { skipSelf: true }))) {
509
+ return null;
510
+ }
511
+ // For other external imports, we need to make sure they are handled as external
512
+ return { id: importee, external: true };
513
+ }
514
+ }
515
+
629
516
  if (importee.startsWith('\0')) {
630
517
  return null;
631
518
  }
632
519
 
633
- return this.resolve(importee, importer, {
634
- skipSelf: true,
635
- custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
636
- }).then((resolved) => {
637
- if (!resolved) {
638
- resolved = resolveExtensions(importee, importer);
639
- }
640
- if (resolved && isProxyModule) {
641
- resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
642
- resolved.external = false;
643
- } else if (resolved && isModuleRegistration) {
644
- resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
645
- } else if (!resolved && (isProxyModule || isRequiredModule)) {
646
- return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
647
- }
520
+ // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
521
+ // if that is the case, we need to add a proxy.
522
+ const customOptions = resolveOptions.custom;
523
+
524
+ // If this is a require, we do not need a proxy
525
+ if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
526
+ return null;
527
+ }
528
+
529
+ const resolved =
530
+ (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
531
+ resolveExtensions(importee, importer, extensions);
532
+ if (!resolved || resolved.external) {
648
533
  return resolved;
649
- });
534
+ }
535
+ const {
536
+ meta: { commonjs: commonjsMeta }
537
+ } = await this.load(resolved);
538
+ if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
539
+ return wrapId(resolved.id, ES_IMPORT_SUFFIX);
540
+ }
541
+ return resolved;
542
+ };
543
+ }
544
+
545
+ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional) {
546
+ const knownCjsModuleTypes = Object.create(null);
547
+ const requiredIds = Object.create(null);
548
+ const unconditionallyRequiredIds = Object.create(null);
549
+ const dependentModules = Object.create(null);
550
+ const getDependentModules = (id) =>
551
+ dependentModules[id] || (dependentModules[id] = Object.create(null));
552
+
553
+ return {
554
+ getWrappedIds: () =>
555
+ Object.keys(knownCjsModuleTypes).filter(
556
+ (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
557
+ ),
558
+ isRequiredId: (id) => requiredIds[id],
559
+ resolveRequireSourcesAndGetMeta: (rollupContext) => async (
560
+ parentId,
561
+ isParentCommonJS,
562
+ sources
563
+ ) => {
564
+ knownCjsModuleTypes[parentId] = knownCjsModuleTypes[parentId] || isParentCommonJS;
565
+ if (
566
+ knownCjsModuleTypes[parentId] &&
567
+ requiredIds[parentId] &&
568
+ !unconditionallyRequiredIds[parentId]
569
+ ) {
570
+ knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
571
+ }
572
+ const requireTargets = await Promise.all(
573
+ sources.map(async ({ source, isConditional }) => {
574
+ // Never analyze or proxy internal modules
575
+ if (source.startsWith('\0')) {
576
+ return { id: source, allowProxy: false };
577
+ }
578
+ const resolved =
579
+ (await rollupContext.resolve(source, parentId, {
580
+ custom: {
581
+ 'node-resolve': { isRequire: true }
582
+ }
583
+ })) || resolveExtensions(source, parentId, extensions);
584
+ if (!resolved) {
585
+ return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
586
+ }
587
+ const childId = resolved.id;
588
+ if (resolved.external) {
589
+ return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
590
+ }
591
+ requiredIds[childId] = true;
592
+ if (
593
+ !(
594
+ detectCyclesAndConditional &&
595
+ (isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)
596
+ )
597
+ ) {
598
+ unconditionallyRequiredIds[childId] = true;
599
+ }
600
+ const parentDependentModules = getDependentModules(parentId);
601
+ const childDependentModules = getDependentModules(childId);
602
+ childDependentModules[parentId] = true;
603
+ for (const dependentId of Object.keys(parentDependentModules)) {
604
+ childDependentModules[dependentId] = true;
605
+ }
606
+ if (parentDependentModules[childId]) {
607
+ // If we depend on one of our dependencies, we have a cycle. Then all modules that
608
+ // we depend on that also depend on the same module are part of a cycle as well.
609
+ if (detectCyclesAndConditional && isParentCommonJS) {
610
+ knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
611
+ knownCjsModuleTypes[childId] = IS_WRAPPED_COMMONJS;
612
+ for (const dependentId of Object.keys(parentDependentModules)) {
613
+ if (getDependentModules(dependentId)[childId]) {
614
+ knownCjsModuleTypes[dependentId] = IS_WRAPPED_COMMONJS;
615
+ }
616
+ }
617
+ }
618
+ } else {
619
+ // This makes sure the current transform handler waits for all direct dependencies to be
620
+ // loaded and transformed and therefore for all transitive CommonJS dependencies to be
621
+ // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
622
+ await rollupContext.load(resolved);
623
+ }
624
+ return { id: childId, allowProxy: true };
625
+ })
626
+ );
627
+ return {
628
+ requireTargets: requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
629
+ const isCommonJS = knownCjsModuleTypes[dependencyId];
630
+ return {
631
+ source: sources[index].source,
632
+ id: allowProxy
633
+ ? isCommonJS === IS_WRAPPED_COMMONJS
634
+ ? wrapId(dependencyId, WRAPPED_SUFFIX)
635
+ : wrapId(dependencyId, PROXY_SUFFIX)
636
+ : dependencyId,
637
+ isCommonJS
638
+ };
639
+ }),
640
+ usesRequireWrapper: knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS
641
+ };
642
+ }
650
643
  };
651
644
  }
652
645
 
@@ -806,8 +799,9 @@ function wrapCode(magicString, uses, moduleName, exportsName) {
806
799
  }
807
800
  magicString
808
801
  .trim()
802
+ .indent('\t')
809
803
  .prepend(`(function (${args.join(', ')}) {\n`)
810
- .append(`\n}(${passedArgs.join(', ')}));`);
804
+ .append(`\n} (${passedArgs.join(', ')}));`);
811
805
  }
812
806
 
813
807
  function rewriteExportsAndGetExportsBlock(
@@ -825,12 +819,27 @@ function rewriteExportsAndGetExportsBlock(
825
819
  HELPERS_NAME,
826
820
  exportMode,
827
821
  detectWrappedDefault,
828
- defaultIsModuleExports
822
+ defaultIsModuleExports,
823
+ usesRequireWrapper,
824
+ requireName
829
825
  ) {
830
826
  const exports = [];
831
827
  const exportDeclarations = [];
832
828
 
833
- if (exportMode === 'replace') {
829
+ if (usesRequireWrapper) {
830
+ getExportsWhenUsingRequireWrapper(
831
+ magicString,
832
+ wrapped,
833
+ exportMode,
834
+ exports,
835
+ moduleExportsAssignments,
836
+ exportsAssignmentsByName,
837
+ moduleName,
838
+ exportsName,
839
+ requireName,
840
+ defineCompiledEsmExpressions
841
+ );
842
+ } else if (exportMode === 'replace') {
834
843
  getExportsForReplacedModuleExports(
835
844
  magicString,
836
845
  exports,
@@ -873,6 +882,49 @@ function rewriteExportsAndGetExportsBlock(
873
882
  return `\n\n${exportDeclarations.join('\n')}`;
874
883
  }
875
884
 
885
+ function getExportsWhenUsingRequireWrapper(
886
+ magicString,
887
+ wrapped,
888
+ exportMode,
889
+ exports,
890
+ moduleExportsAssignments,
891
+ exportsAssignmentsByName,
892
+ moduleName,
893
+ exportsName,
894
+ requireName,
895
+ defineCompiledEsmExpressions
896
+ ) {
897
+ if (!wrapped) {
898
+ if (exportMode === 'replace') {
899
+ for (const { left } of moduleExportsAssignments) {
900
+ magicString.overwrite(left.start, left.end, exportsName);
901
+ }
902
+ } else {
903
+ // Collect and rewrite module.exports assignments
904
+ for (const { left } of moduleExportsAssignments) {
905
+ magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
906
+ }
907
+ // Collect and rewrite named exports
908
+ for (const [exportName, { nodes }] of exportsAssignmentsByName) {
909
+ for (const node of nodes) {
910
+ magicString.overwrite(node.start, node.left.end, `${exportsName}.${exportName}`);
911
+ }
912
+ }
913
+ // Collect and rewrite exports.__esModule assignments
914
+ for (const expression of defineCompiledEsmExpressions) {
915
+ const moduleExportsExpression =
916
+ expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
917
+ magicString.overwrite(
918
+ moduleExportsExpression.start,
919
+ moduleExportsExpression.end,
920
+ exportsName
921
+ );
922
+ }
923
+ }
924
+ }
925
+ exports.push(`${requireName} as __require`);
926
+ }
927
+
876
928
  function getExportsForReplacedModuleExports(
877
929
  magicString,
878
930
  exports,
@@ -960,7 +1012,7 @@ function getExports(
960
1012
  }
961
1013
 
962
1014
  if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
963
- exportDeclarations.push(`export default ${exportsName};`);
1015
+ exports.push(`${exportsName} as default`);
964
1016
  } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
965
1017
  exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
966
1018
  } else {
@@ -970,7 +1022,7 @@ function getExports(
970
1022
  }
971
1023
  }
972
1024
 
973
- function isRequireStatement(node, scope) {
1025
+ function isRequireExpression(node, scope) {
974
1026
  if (!node) return false;
975
1027
  if (node.type !== 'CallExpression') return false;
976
1028
 
@@ -997,11 +1049,6 @@ function isModuleRequire({ object, property }, scope) {
997
1049
  );
998
1050
  }
999
1051
 
1000
- function isStaticRequireStatement(node, scope) {
1001
- if (!isRequireStatement(node, scope)) return false;
1002
- return !hasDynamicArguments(node);
1003
- }
1004
-
1005
1052
  function hasDynamicArguments(node) {
1006
1053
  return (
1007
1054
  node.arguments.length > 1 ||
@@ -1016,89 +1063,58 @@ function isNodeRequirePropertyAccess(parent) {
1016
1063
  return parent && parent.property && reservedMethod[parent.property.name];
1017
1064
  }
1018
1065
 
1019
- function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
1020
- return ignoreRequire(requiredNode.arguments[0].value);
1021
- }
1022
-
1023
1066
  function getRequireStringArg(node) {
1024
1067
  return node.arguments[0].type === 'Literal'
1025
1068
  ? node.arguments[0].value
1026
1069
  : node.arguments[0].quasis[0].value.cooked;
1027
1070
  }
1028
1071
 
1029
- function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
1030
- if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
1031
- try {
1032
- const resolvedPath = normalizePathSlashes(sync(source, { basedir: dirname(id) }));
1033
- if (dynamicRequireModuleSet.has(resolvedPath)) {
1034
- return true;
1035
- }
1036
- } catch (ex) {
1037
- // Probably a node.js internal module
1038
- return false;
1039
- }
1040
-
1041
- return false;
1042
- }
1043
-
1044
- for (const attemptExt of ['', '.js', '.json']) {
1045
- const resolvedPath = normalizePathSlashes(resolve(dirname(id), source + attemptExt));
1046
- if (dynamicRequireModuleSet.has(resolvedPath)) {
1047
- return true;
1048
- }
1049
- }
1050
-
1051
- return false;
1052
- }
1053
-
1054
1072
  function getRequireHandlers() {
1055
- const requiredSources = [];
1056
- const requiredBySource = Object.create(null);
1057
- const requiredByNode = new Map();
1058
- const requireExpressionsWithUsedReturnValue = [];
1059
-
1060
- function addRequireStatement(sourceId, node, scope, usesReturnValue) {
1061
- const required = getRequired(sourceId);
1062
- requiredByNode.set(node, { scope, required });
1063
- if (usesReturnValue) {
1064
- required.nodesUsingRequired.push(node);
1065
- requireExpressionsWithUsedReturnValue.push(node);
1066
- }
1067
- }
1068
-
1069
- function getRequired(sourceId) {
1070
- if (!requiredBySource[sourceId]) {
1071
- requiredSources.push(sourceId);
1072
-
1073
- requiredBySource[sourceId] = {
1074
- source: sourceId,
1075
- name: null,
1076
- nodesUsingRequired: []
1077
- };
1078
- }
1079
-
1080
- return requiredBySource[sourceId];
1073
+ const requireExpressions = [];
1074
+
1075
+ function addRequireStatement(
1076
+ sourceId,
1077
+ node,
1078
+ scope,
1079
+ usesReturnValue,
1080
+ isInsideTryBlock,
1081
+ isInsideConditional,
1082
+ toBeRemoved
1083
+ ) {
1084
+ requireExpressions.push({
1085
+ sourceId,
1086
+ node,
1087
+ scope,
1088
+ usesReturnValue,
1089
+ isInsideTryBlock,
1090
+ isInsideConditional,
1091
+ toBeRemoved
1092
+ });
1081
1093
  }
1082
1094
 
1083
- function rewriteRequireExpressionsAndGetImportBlock(
1095
+ async function rewriteRequireExpressionsAndGetImportBlock(
1084
1096
  magicString,
1085
1097
  topLevelDeclarations,
1086
- topLevelRequireDeclarators,
1087
1098
  reassignedNames,
1088
1099
  helpersName,
1089
- dynamicRegisterSources,
1100
+ dynamicRequireName,
1090
1101
  moduleName,
1091
1102
  exportsName,
1092
1103
  id,
1093
- exportMode
1104
+ exportMode,
1105
+ resolveRequireSourcesAndGetMeta,
1106
+ needsRequireWrapper,
1107
+ isEsModule,
1108
+ usesRequire,
1109
+ getIgnoreTryCatchRequireStatementMode
1094
1110
  ) {
1095
- setRemainingImportNamesAndRewriteRequires(
1096
- requireExpressionsWithUsedReturnValue,
1097
- requiredByNode,
1098
- magicString
1099
- );
1100
1111
  const imports = [];
1101
1112
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1113
+ if (usesRequire) {
1114
+ imports.push(
1115
+ `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1116
+ );
1117
+ }
1102
1118
  if (exportMode === 'module') {
1103
1119
  imports.push(
1104
1120
  `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
@@ -1110,58 +1126,115 @@ function getRequireHandlers() {
1110
1126
  `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
1111
1127
  );
1112
1128
  }
1113
- for (const source of dynamicRegisterSources) {
1114
- imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1115
- }
1116
- for (const source of requiredSources) {
1117
- if (!source.startsWith('\0')) {
1118
- imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
1119
- }
1120
- const { name, nodesUsingRequired } = requiredBySource[source];
1121
- imports.push(
1122
- `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
1123
- source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
1124
- )};`
1125
- );
1126
- }
1127
- return imports.length ? `${imports.join('\n')}\n\n` : '';
1129
+ const requiresBySource = collectSources(requireExpressions);
1130
+ const { requireTargets, usesRequireWrapper } = await resolveRequireSourcesAndGetMeta(
1131
+ id,
1132
+ needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1133
+ Object.keys(requiresBySource).map((source) => {
1134
+ return {
1135
+ source,
1136
+ isConditional: requiresBySource[source].every((require) => require.isInsideConditional)
1137
+ };
1138
+ })
1139
+ );
1140
+ processRequireExpressions(
1141
+ imports,
1142
+ requireTargets,
1143
+ requiresBySource,
1144
+ getIgnoreTryCatchRequireStatementMode,
1145
+ magicString
1146
+ );
1147
+ return {
1148
+ importBlock: imports.length ? `${imports.join('\n')}\n\n` : '',
1149
+ usesRequireWrapper
1150
+ };
1128
1151
  }
1129
1152
 
1130
1153
  return {
1131
1154
  addRequireStatement,
1132
- requiredSources,
1133
1155
  rewriteRequireExpressionsAndGetImportBlock
1134
1156
  };
1135
1157
  }
1136
1158
 
1137
- function setRemainingImportNamesAndRewriteRequires(
1138
- requireExpressionsWithUsedReturnValue,
1139
- requiredByNode,
1159
+ function collectSources(requireExpressions) {
1160
+ const requiresBySource = Object.create(null);
1161
+ for (const requireExpression of requireExpressions) {
1162
+ const { sourceId } = requireExpression;
1163
+ if (!requiresBySource[sourceId]) {
1164
+ requiresBySource[sourceId] = [];
1165
+ }
1166
+ const requires = requiresBySource[sourceId];
1167
+ requires.push(requireExpression);
1168
+ }
1169
+ return requiresBySource;
1170
+ }
1171
+
1172
+ function processRequireExpressions(
1173
+ imports,
1174
+ requireTargets,
1175
+ requiresBySource,
1176
+ getIgnoreTryCatchRequireStatementMode,
1140
1177
  magicString
1141
1178
  ) {
1142
- let uid = 0;
1143
- for (const requireExpression of requireExpressionsWithUsedReturnValue) {
1144
- const { required } = requiredByNode.get(requireExpression);
1145
- if (!required.name) {
1146
- let potentialName;
1147
- const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
1148
- do {
1149
- potentialName = `require$$${uid}`;
1150
- uid += 1;
1151
- } while (required.nodesUsingRequired.some(isUsedName));
1152
- required.name = potentialName;
1179
+ const generateRequireName = getGenerateRequireName();
1180
+ for (const { source, id: resolvedId, isCommonJS } of requireTargets) {
1181
+ const requires = requiresBySource[source];
1182
+ const name = generateRequireName(requires);
1183
+ let usesRequired = false;
1184
+ let needsImport = false;
1185
+ for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
1186
+ const { canConvertRequire, shouldRemoveRequire } =
1187
+ isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX)
1188
+ ? getIgnoreTryCatchRequireStatementMode(source)
1189
+ : { canConvertRequire: true, shouldRemoveRequire: false };
1190
+ if (shouldRemoveRequire) {
1191
+ if (usesReturnValue) {
1192
+ magicString.overwrite(node.start, node.end, 'undefined');
1193
+ } else {
1194
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1195
+ }
1196
+ } else if (canConvertRequire) {
1197
+ needsImport = true;
1198
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1199
+ magicString.overwrite(node.start, node.end, `${name}()`);
1200
+ } else if (usesReturnValue) {
1201
+ usesRequired = true;
1202
+ magicString.overwrite(node.start, node.end, name);
1203
+ } else {
1204
+ magicString.remove(toBeRemoved.start, toBeRemoved.end);
1205
+ }
1206
+ }
1207
+ }
1208
+ if (needsImport) {
1209
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
1210
+ imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)};`);
1211
+ } else {
1212
+ imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)};`);
1213
+ }
1153
1214
  }
1154
- magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
1155
1215
  }
1156
1216
  }
1157
1217
 
1218
+ function getGenerateRequireName() {
1219
+ let uid = 0;
1220
+ return (requires) => {
1221
+ let name;
1222
+ const hasNameConflict = ({ scope }) => scope.contains(name);
1223
+ do {
1224
+ name = `require$$${uid}`;
1225
+ uid += 1;
1226
+ } while (requires.some(hasNameConflict));
1227
+ return name;
1228
+ };
1229
+ }
1230
+
1158
1231
  /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
1159
1232
 
1160
1233
  const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
1161
1234
 
1162
1235
  const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
1163
1236
 
1164
- function transformCommonjs(
1237
+ async function transformCommonjs(
1165
1238
  parse,
1166
1239
  code,
1167
1240
  id,
@@ -1172,11 +1245,14 @@ function transformCommonjs(
1172
1245
  getIgnoreTryCatchRequireStatementMode,
1173
1246
  sourceMap,
1174
1247
  isDynamicRequireModulesEnabled,
1175
- dynamicRequireModuleSet,
1176
- disableWrap,
1248
+ dynamicRequireModules,
1177
1249
  commonDir,
1178
1250
  astCache,
1179
- defaultIsModuleExports
1251
+ defaultIsModuleExports,
1252
+ needsRequireWrapper,
1253
+ resolveRequireSourcesAndGetMeta,
1254
+ isRequired,
1255
+ checkDynamicRequire
1180
1256
  ) {
1181
1257
  const ast = astCache || tryParse(parse, code, id);
1182
1258
  const magicString = new MagicString(code);
@@ -1186,7 +1262,6 @@ function transformCommonjs(
1186
1262
  global: false,
1187
1263
  require: false
1188
1264
  };
1189
- let usesDynamicRequire = false;
1190
1265
  const virtualDynamicRequirePath =
1191
1266
  isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);
1192
1267
  let scope = attachScopes(ast, 'scope');
@@ -1196,24 +1271,18 @@ function transformCommonjs(
1196
1271
  let shouldWrap = false;
1197
1272
 
1198
1273
  const globals = new Set();
1199
-
1200
- // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
1201
- const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');
1202
- const dynamicRegisterSources = new Set();
1203
- let hasRemovedRequire = false;
1204
-
1205
- const {
1206
- addRequireStatement,
1207
- requiredSources,
1208
- rewriteRequireExpressionsAndGetImportBlock
1209
- } = getRequireHandlers();
1274
+ // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
1275
+ // or contains nested requires, those should be handled as function calls unless there is an
1276
+ // unconditional require elsewhere.
1277
+ let currentConditionalNodeEnd = null;
1278
+ const conditionalNodes = new Set();
1279
+ const { addRequireStatement, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1210
1280
 
1211
1281
  // See which names are assigned to. This is necessary to prevent
1212
1282
  // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
1213
1283
  // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
1214
1284
  const reassignedNames = new Set();
1215
1285
  const topLevelDeclarations = [];
1216
- const topLevelRequireDeclarators = new Set();
1217
1286
  const skippedNodes = new Set();
1218
1287
  const moduleAccessScopes = new Set([scope]);
1219
1288
  const exportsAccessScopes = new Set([scope]);
@@ -1222,6 +1291,8 @@ function transformCommonjs(
1222
1291
  const exportsAssignmentsByName = new Map();
1223
1292
  const topLevelAssignments = new Set();
1224
1293
  const topLevelDefineCompiledEsmExpressions = [];
1294
+ const replacedGlobal = [];
1295
+ const replacedDynamicRequires = [];
1225
1296
 
1226
1297
  walk(ast, {
1227
1298
  enter(node, parent) {
@@ -1233,6 +1304,12 @@ function transformCommonjs(
1233
1304
  if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
1234
1305
  currentTryBlockEnd = null;
1235
1306
  }
1307
+ if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) {
1308
+ currentConditionalNodeEnd = null;
1309
+ }
1310
+ if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) {
1311
+ currentConditionalNodeEnd = node.end;
1312
+ }
1236
1313
 
1237
1314
  programDepth += 1;
1238
1315
  if (node.scope) ({ scope } = node);
@@ -1244,11 +1321,6 @@ function transformCommonjs(
1244
1321
 
1245
1322
  // eslint-disable-next-line default-case
1246
1323
  switch (node.type) {
1247
- case 'TryStatement':
1248
- if (currentTryBlockEnd === null) {
1249
- currentTryBlockEnd = node.block.end;
1250
- }
1251
- return;
1252
1324
  case 'AssignmentExpression':
1253
1325
  if (node.left.type === 'MemberExpression') {
1254
1326
  const flattened = getKeypath(node.left);
@@ -1319,12 +1391,15 @@ function transformCommonjs(
1319
1391
  return;
1320
1392
  }
1321
1393
 
1394
+ // Transform require.resolve
1322
1395
  if (
1396
+ isDynamicRequireModulesEnabled &&
1323
1397
  node.callee.object &&
1324
- node.callee.object.name === 'require' &&
1325
- node.callee.property.name === 'resolve' &&
1326
- hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
1398
+ isRequire(node.callee.object, scope) &&
1399
+ node.callee.property.name === 'resolve'
1327
1400
  ) {
1401
+ checkDynamicRequire();
1402
+ uses.require = true;
1328
1403
  const requireNode = node.callee.object;
1329
1404
  magicString.appendLeft(
1330
1405
  node.end - 1,
@@ -1332,98 +1407,45 @@ function transformCommonjs(
1332
1407
  dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1333
1408
  )}`
1334
1409
  );
1335
- magicString.overwrite(
1336
- requireNode.start,
1337
- requireNode.end,
1338
- `${HELPERS_NAME}.commonjsRequire`,
1339
- {
1340
- storeName: true
1341
- }
1342
- );
1410
+ replacedDynamicRequires.push(requireNode);
1343
1411
  return;
1344
1412
  }
1345
1413
 
1346
- if (!isStaticRequireStatement(node, scope)) return;
1347
- if (!isDynamicRequireModulesEnabled) {
1348
- skippedNodes.add(node.callee);
1414
+ if (!isRequireExpression(node, scope)) {
1415
+ return;
1349
1416
  }
1350
- if (!isIgnoredRequireStatement(node, ignoreRequire)) {
1351
- skippedNodes.add(node.callee);
1352
- const usesReturnValue = parent.type !== 'ExpressionStatement';
1353
-
1354
- let canConvertRequire = true;
1355
- let shouldRemoveRequireStatement = false;
1356
1417
 
1357
- if (currentTryBlockEnd !== null) {
1358
- ({
1359
- canConvertRequire,
1360
- shouldRemoveRequireStatement
1361
- } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
1362
-
1363
- if (shouldRemoveRequireStatement) {
1364
- hasRemovedRequire = true;
1365
- }
1418
+ skippedNodes.add(node.callee);
1419
+ uses.require = true;
1420
+
1421
+ if (hasDynamicArguments(node)) {
1422
+ if (isDynamicRequireModulesEnabled) {
1423
+ magicString.appendLeft(
1424
+ node.end - 1,
1425
+ `, ${JSON.stringify(
1426
+ dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1427
+ )}`
1428
+ );
1366
1429
  }
1367
-
1368
- let sourceId = getRequireStringArg(node);
1369
- const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1370
- if (isDynamicRegister) {
1371
- sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
1372
- if (sourceId.endsWith('.json')) {
1373
- sourceId = DYNAMIC_JSON_PREFIX + sourceId;
1374
- }
1375
- dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
1376
- } else {
1377
- if (
1378
- !sourceId.endsWith('.json') &&
1379
- hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
1380
- ) {
1381
- if (shouldRemoveRequireStatement) {
1382
- magicString.overwrite(node.start, node.end, `undefined`);
1383
- } else if (canConvertRequire) {
1384
- magicString.overwrite(
1385
- node.start,
1386
- node.end,
1387
- `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
1388
- getVirtualPathForDynamicRequirePath(sourceId, commonDir)
1389
- )}, ${JSON.stringify(
1390
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1391
- )})`
1392
- );
1393
- usesDynamicRequire = true;
1394
- }
1395
- return;
1396
- }
1397
-
1398
- if (canConvertRequire) {
1399
- addRequireStatement(sourceId, node, scope, usesReturnValue);
1400
- }
1430
+ if (!ignoreDynamicRequires) {
1431
+ checkDynamicRequire();
1432
+ replacedDynamicRequires.push(node.callee);
1401
1433
  }
1434
+ return;
1435
+ }
1402
1436
 
1403
- if (usesReturnValue) {
1404
- if (shouldRemoveRequireStatement) {
1405
- magicString.overwrite(node.start, node.end, `undefined`);
1406
- return;
1407
- }
1408
-
1409
- if (
1410
- parent.type === 'VariableDeclarator' &&
1411
- !scope.parent &&
1412
- parent.id.type === 'Identifier'
1413
- ) {
1414
- // This will allow us to reuse this variable name as the imported variable if it is not reassigned
1415
- // and does not conflict with variables in other places where this is imported
1416
- topLevelRequireDeclarators.add(parent);
1417
- }
1418
- } else {
1419
- // This is a bare import, e.g. `require('foo');`
1420
-
1421
- if (!canConvertRequire && !shouldRemoveRequireStatement) {
1422
- return;
1423
- }
1424
-
1425
- magicString.remove(parent.start, parent.end);
1426
- }
1437
+ const requireStringArg = getRequireStringArg(node);
1438
+ if (!ignoreRequire(requireStringArg)) {
1439
+ const usesReturnValue = parent.type !== 'ExpressionStatement';
1440
+ addRequireStatement(
1441
+ requireStringArg,
1442
+ node,
1443
+ scope,
1444
+ usesReturnValue,
1445
+ currentTryBlockEnd !== null,
1446
+ currentConditionalNodeEnd !== null,
1447
+ parent.type === 'ExpressionStatement' ? parent : node
1448
+ );
1427
1449
  }
1428
1450
  return;
1429
1451
  }
@@ -1432,45 +1454,44 @@ function transformCommonjs(
1432
1454
  // skip dead branches
1433
1455
  if (isFalsy(node.test)) {
1434
1456
  skippedNodes.add(node.consequent);
1435
- } else if (node.alternate && isTruthy(node.test)) {
1436
- skippedNodes.add(node.alternate);
1457
+ } else if (isTruthy(node.test)) {
1458
+ if (node.alternate) {
1459
+ skippedNodes.add(node.alternate);
1460
+ }
1461
+ } else {
1462
+ conditionalNodes.add(node.consequent);
1463
+ if (node.alternate) {
1464
+ conditionalNodes.add(node.alternate);
1465
+ }
1466
+ }
1467
+ return;
1468
+ case 'ArrowFunctionExpression':
1469
+ case 'FunctionDeclaration':
1470
+ case 'FunctionExpression':
1471
+ // requires in functions should be conditional unless it is an IIFE
1472
+ if (
1473
+ currentConditionalNodeEnd === null &&
1474
+ !(parent.type === 'CallExpression' && parent.callee === node)
1475
+ ) {
1476
+ currentConditionalNodeEnd = node.end;
1437
1477
  }
1438
1478
  return;
1439
1479
  case 'Identifier': {
1440
1480
  const { name } = node;
1441
- if (!(isReference(node, parent) && !scope.contains(name))) return;
1481
+ if (!isReference(node, parent) || scope.contains(name)) return;
1442
1482
  switch (name) {
1443
1483
  case 'require':
1484
+ uses.require = true;
1444
1485
  if (isNodeRequirePropertyAccess(parent)) {
1445
- if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
1446
- if (parent.property.name === 'cache') {
1447
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1448
- storeName: true
1449
- });
1450
- }
1451
- }
1452
-
1453
1486
  return;
1454
1487
  }
1455
-
1456
- if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
1457
- magicString.appendLeft(
1458
- parent.end - 1,
1459
- `,${JSON.stringify(
1460
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1461
- )}`
1462
- );
1463
- }
1464
1488
  if (!ignoreDynamicRequires) {
1489
+ checkDynamicRequire();
1465
1490
  if (isShorthandProperty(parent)) {
1466
- magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
1467
- } else {
1468
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1469
- storeName: true
1470
- });
1491
+ magicString.prependRight(node.start, 'require: ');
1471
1492
  }
1493
+ replacedDynamicRequires.push(node);
1472
1494
  }
1473
- usesDynamicRequire = true;
1474
1495
  return;
1475
1496
  case 'module':
1476
1497
  case 'exports':
@@ -1480,9 +1501,7 @@ function transformCommonjs(
1480
1501
  case 'global':
1481
1502
  uses.global = true;
1482
1503
  if (!ignoreGlobal) {
1483
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1484
- storeName: true
1485
- });
1504
+ replacedGlobal.push(node);
1486
1505
  }
1487
1506
  return;
1488
1507
  case 'define':
@@ -1495,11 +1514,26 @@ function transformCommonjs(
1495
1514
  return;
1496
1515
  }
1497
1516
  }
1517
+ case 'LogicalExpression':
1518
+ // skip dead branches
1519
+ if (node.operator === '&&') {
1520
+ if (isFalsy(node.left)) {
1521
+ skippedNodes.add(node.right);
1522
+ } else if (!isTruthy(node.left)) {
1523
+ conditionalNodes.add(node.right);
1524
+ }
1525
+ } else if (node.operator === '||') {
1526
+ if (isTruthy(node.left)) {
1527
+ skippedNodes.add(node.right);
1528
+ } else if (!isFalsy(node.left)) {
1529
+ conditionalNodes.add(node.right);
1530
+ }
1531
+ }
1532
+ return;
1498
1533
  case 'MemberExpression':
1499
1534
  if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
1500
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
1501
- storeName: true
1502
- });
1535
+ uses.require = true;
1536
+ replacedDynamicRequires.push(node);
1503
1537
  skippedNodes.add(node.object);
1504
1538
  skippedNodes.add(node.property);
1505
1539
  }
@@ -1515,12 +1549,18 @@ function transformCommonjs(
1515
1549
  if (lexicalDepth === 0) {
1516
1550
  uses.global = true;
1517
1551
  if (!ignoreGlobal) {
1518
- magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
1519
- storeName: true
1520
- });
1552
+ replacedGlobal.push(node);
1521
1553
  }
1522
1554
  }
1523
1555
  return;
1556
+ case 'TryStatement':
1557
+ if (currentTryBlockEnd === null) {
1558
+ currentTryBlockEnd = node.block.end;
1559
+ }
1560
+ if (currentConditionalNodeEnd === null) {
1561
+ currentConditionalNodeEnd = node.end;
1562
+ }
1563
+ return;
1524
1564
  case 'UnaryExpression':
1525
1565
  // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
1526
1566
  if (node.operator === 'typeof') {
@@ -1557,34 +1597,45 @@ function transformCommonjs(
1557
1597
  const nameBase = getName(id);
1558
1598
  const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
1559
1599
  const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
1600
+ const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1601
+ const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1602
+ const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1603
+ const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
1560
1604
  const deconflictedExportNames = Object.create(null);
1561
1605
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1562
1606
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
1563
1607
  }
1564
1608
 
1609
+ for (const node of replacedGlobal) {
1610
+ magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, {
1611
+ storeName: true
1612
+ });
1613
+ }
1614
+ for (const node of replacedDynamicRequires) {
1615
+ magicString.overwrite(node.start, node.end, dynamicRequireName, {
1616
+ contentOnly: true,
1617
+ storeName: true
1618
+ });
1619
+ }
1620
+
1565
1621
  // We cannot wrap ES/mixed modules
1566
- shouldWrap =
1567
- !isEsModule &&
1568
- !disableWrap &&
1569
- (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1622
+ shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1570
1623
  const detectWrappedDefault =
1571
1624
  shouldWrap &&
1572
1625
  (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
1573
1626
 
1574
1627
  if (
1575
1628
  !(
1576
- requiredSources.length ||
1577
- dynamicRegisterSources.size ||
1629
+ shouldWrap ||
1630
+ isRequired ||
1578
1631
  uses.module ||
1579
1632
  uses.exports ||
1580
1633
  uses.require ||
1581
- usesDynamicRequire ||
1582
- hasRemovedRequire ||
1583
1634
  topLevelDefineCompiledEsmExpressions.length > 0
1584
1635
  ) &&
1585
1636
  (ignoreGlobal || !uses.global)
1586
1637
  ) {
1587
- return { meta: { commonjs: { isCommonJS: false } } };
1638
+ return { meta: { commonjs: { isCommonJS: false, isMixedModule: false } } };
1588
1639
  }
1589
1640
 
1590
1641
  let leadingComment = '';
@@ -1606,19 +1657,22 @@ function transformCommonjs(
1606
1657
  ? 'exports'
1607
1658
  : 'module';
1608
1659
 
1609
- const importBlock = rewriteRequireExpressionsAndGetImportBlock(
1660
+ const { importBlock, usesRequireWrapper } = await rewriteRequireExpressionsAndGetImportBlock(
1610
1661
  magicString,
1611
1662
  topLevelDeclarations,
1612
- topLevelRequireDeclarators,
1613
1663
  reassignedNames,
1614
- HELPERS_NAME,
1615
- dynamicRegisterSources,
1664
+ helpersName,
1665
+ dynamicRequireName,
1616
1666
  moduleName,
1617
1667
  exportsName,
1618
1668
  id,
1619
- exportMode
1669
+ exportMode,
1670
+ resolveRequireSourcesAndGetMeta,
1671
+ needsRequireWrapper,
1672
+ isEsModule,
1673
+ uses.require,
1674
+ getIgnoreTryCatchRequireStatementMode
1620
1675
  );
1621
-
1622
1676
  const exportBlock = isEsModule
1623
1677
  ? ''
1624
1678
  : rewriteExportsAndGetExportsBlock(
@@ -1633,16 +1687,35 @@ function transformCommonjs(
1633
1687
  topLevelDefineCompiledEsmExpressions,
1634
1688
  deconflictedExportNames,
1635
1689
  code,
1636
- HELPERS_NAME,
1690
+ helpersName,
1637
1691
  exportMode,
1638
1692
  detectWrappedDefault,
1639
- defaultIsModuleExports
1693
+ defaultIsModuleExports,
1694
+ usesRequireWrapper,
1695
+ requireName
1640
1696
  );
1641
1697
 
1642
1698
  if (shouldWrap) {
1643
1699
  wrapCode(magicString, uses, moduleName, exportsName);
1644
1700
  }
1645
1701
 
1702
+ if (usesRequireWrapper) {
1703
+ magicString.trim().indent('\t');
1704
+ magicString.prepend(
1705
+ `var ${isRequiredName};
1706
+
1707
+ function ${requireName} () {
1708
+ \tif (${isRequiredName}) return ${exportsName};
1709
+ \t${isRequiredName} = 1;
1710
+ `
1711
+ ).append(`
1712
+ \treturn ${exportsName};
1713
+ }`);
1714
+ if (exportMode === 'replace') {
1715
+ magicString.prepend(`var ${exportsName};\n`);
1716
+ }
1717
+ }
1718
+
1646
1719
  magicString
1647
1720
  .trim()
1648
1721
  .prepend(leadingComment + importBlock)
@@ -1651,24 +1724,32 @@ function transformCommonjs(
1651
1724
  return {
1652
1725
  code: magicString.toString(),
1653
1726
  map: sourceMap ? magicString.generateMap() : null,
1654
- syntheticNamedExports: isEsModule ? false : '__moduleExports',
1655
- meta: { commonjs: { isCommonJS: !isEsModule } }
1727
+ syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
1728
+ meta: {
1729
+ commonjs: {
1730
+ isCommonJS: !isEsModule && (usesRequireWrapper ? IS_WRAPPED_COMMONJS : true),
1731
+ isMixedModule: isEsModule
1732
+ }
1733
+ }
1656
1734
  };
1657
1735
  }
1658
1736
 
1659
1737
  function commonjs(options = {}) {
1660
- const extensions = options.extensions || ['.js'];
1661
- const filter = createFilter(options.include, options.exclude);
1662
1738
  const {
1663
1739
  ignoreGlobal,
1664
1740
  ignoreDynamicRequires,
1665
1741
  requireReturnsDefault: requireReturnsDefaultOption,
1666
1742
  esmExternals
1667
1743
  } = options;
1744
+ const extensions = options.extensions || ['.js'];
1745
+ const filter = createFilter(options.include, options.exclude);
1746
+ const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
1747
+
1668
1748
  const getRequireReturnsDefault =
1669
1749
  typeof requireReturnsDefaultOption === 'function'
1670
1750
  ? requireReturnsDefaultOption
1671
1751
  : () => requireReturnsDefaultOption;
1752
+
1672
1753
  let esmExternalIds;
1673
1754
  const isEsmExternal =
1674
1755
  typeof esmExternals === 'function'
@@ -1676,20 +1757,27 @@ function commonjs(options = {}) {
1676
1757
  : Array.isArray(esmExternals)
1677
1758
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1678
1759
  : () => esmExternals;
1760
+
1679
1761
  const defaultIsModuleExports =
1680
1762
  typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1681
1763
 
1682
- const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
1683
- options.dynamicRequireTargets
1764
+ const {
1765
+ resolveRequireSourcesAndGetMeta,
1766
+ getWrappedIds,
1767
+ isRequiredId
1768
+ } = getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional);
1769
+ const dynamicRequireRoot =
1770
+ typeof options.dynamicRequireRoot === 'string'
1771
+ ? resolve(options.dynamicRequireRoot)
1772
+ : process.cwd();
1773
+ const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
1774
+ options.dynamicRequireTargets,
1775
+ dynamicRequireRoot
1684
1776
  );
1685
- const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
1686
- const commonDir = isDynamicRequireModulesEnabled
1687
- ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1688
- : null;
1777
+ const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1689
1778
 
1690
1779
  const esModulesWithDefaultExport = new Set();
1691
1780
  const esModulesWithNamedExports = new Set();
1692
- const commonJsMetaPromises = new Map();
1693
1781
 
1694
1782
  const ignoreRequire =
1695
1783
  typeof options.ignore === 'function'
@@ -1704,11 +1792,13 @@ function commonjs(options = {}) {
1704
1792
  ? options.ignoreTryCatch(id)
1705
1793
  : Array.isArray(options.ignoreTryCatch)
1706
1794
  ? options.ignoreTryCatch.includes(id)
1707
- : options.ignoreTryCatch || false;
1795
+ : typeof options.ignoreTryCatch !== 'undefined'
1796
+ ? options.ignoreTryCatch
1797
+ : true;
1708
1798
 
1709
1799
  return {
1710
1800
  canConvertRequire: mode !== 'remove' && mode !== true,
1711
- shouldRemoveRequireStatement: mode === 'remove'
1801
+ shouldRemoveRequire: mode === 'remove'
1712
1802
  };
1713
1803
  };
1714
1804
 
@@ -1717,12 +1807,6 @@ function commonjs(options = {}) {
1717
1807
  const sourceMap = options.sourceMap !== false;
1718
1808
 
1719
1809
  function transformAndCheckExports(code, id) {
1720
- if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1721
- // eslint-disable-next-line no-param-reassign
1722
- code =
1723
- getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1724
- }
1725
-
1726
1810
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1727
1811
  this.parse,
1728
1812
  code,
@@ -1736,18 +1820,29 @@ function commonjs(options = {}) {
1736
1820
  }
1737
1821
 
1738
1822
  if (
1739
- !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1740
- (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1823
+ !dynamicRequireModules.has(normalizePathSlashes(id)) &&
1824
+ (!(hasCjsKeywords(code, ignoreGlobal) || isRequiredId(id)) ||
1825
+ (isEsModule && !options.transformMixedEsModules))
1741
1826
  ) {
1742
1827
  return { meta: { commonjs: { isCommonJS: false } } };
1743
1828
  }
1744
1829
 
1745
- // avoid wrapping as this is a commonjsRegister call
1746
- const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
1747
- if (disableWrap) {
1748
- // eslint-disable-next-line no-param-reassign
1749
- id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1750
- }
1830
+ const needsRequireWrapper =
1831
+ !isEsModule &&
1832
+ (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1833
+
1834
+ const checkDynamicRequire = () => {
1835
+ if (id.indexOf(dynamicRequireRoot) !== 0) {
1836
+ this.error({
1837
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1838
+ id,
1839
+ dynamicRequireRoot,
1840
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(
1841
+ id
1842
+ )}" or one of its parent directories.`
1843
+ });
1844
+ }
1845
+ };
1751
1846
 
1752
1847
  return transformCommonjs(
1753
1848
  this.parse,
@@ -1760,17 +1855,37 @@ function commonjs(options = {}) {
1760
1855
  getIgnoreTryCatchRequireStatementMode,
1761
1856
  sourceMap,
1762
1857
  isDynamicRequireModulesEnabled,
1763
- dynamicRequireModuleSet,
1764
- disableWrap,
1858
+ dynamicRequireModules,
1765
1859
  commonDir,
1766
1860
  ast,
1767
- defaultIsModuleExports
1861
+ defaultIsModuleExports,
1862
+ needsRequireWrapper,
1863
+ resolveRequireSourcesAndGetMeta(this),
1864
+ isRequiredId(id),
1865
+ checkDynamicRequire
1768
1866
  );
1769
1867
  }
1770
1868
 
1771
1869
  return {
1772
1870
  name: 'commonjs',
1773
1871
 
1872
+ version,
1873
+
1874
+ options(rawOptions) {
1875
+ // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
1876
+ // do not prevent our plugin from resolving entry points ot proxies.
1877
+ const plugins = Array.isArray(rawOptions.plugins)
1878
+ ? rawOptions.plugins
1879
+ : rawOptions.plugins
1880
+ ? [rawOptions.plugins]
1881
+ : [];
1882
+ plugins.unshift({
1883
+ name: 'commonjs--resolver',
1884
+ resolveId
1885
+ });
1886
+ return { ...rawOptions, plugins };
1887
+ },
1888
+
1774
1889
  buildStart() {
1775
1890
  validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1776
1891
  if (options.namedExports != null) {
@@ -1780,44 +1895,43 @@ function commonjs(options = {}) {
1780
1895
  }
1781
1896
  },
1782
1897
 
1783
- resolveId,
1898
+ buildEnd() {
1899
+ if (options.strictRequires === 'debug') {
1900
+ const wrappedIds = getWrappedIds();
1901
+ if (wrappedIds.length) {
1902
+ this.warn({
1903
+ code: 'WRAPPED_IDS',
1904
+ ids: wrappedIds,
1905
+ message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds
1906
+ .map((id) => `\t${JSON.stringify(relative(process.cwd(), id))}`)
1907
+ .join(',\n')}\n]`
1908
+ });
1909
+ } else {
1910
+ this.warn({
1911
+ code: 'WRAPPED_IDS',
1912
+ ids: wrappedIds,
1913
+ message: 'The commonjs plugin did not wrap any files.'
1914
+ });
1915
+ }
1916
+ }
1917
+ },
1784
1918
 
1785
1919
  load(id) {
1786
1920
  if (id === HELPERS_ID) {
1787
- return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
1788
- }
1789
-
1790
- if (id.startsWith(HELPERS_ID)) {
1791
- return getSpecificHelperProxy(id);
1921
+ return getHelpersModule();
1792
1922
  }
1793
1923
 
1794
1924
  if (isWrappedId(id, MODULE_SUFFIX)) {
1795
- const actualId = unwrapId(id, MODULE_SUFFIX);
1796
- let name = getName(actualId);
1797
- let code;
1798
- if (isDynamicRequireModulesEnabled) {
1799
- if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
1800
- name = `${name}_`;
1801
- }
1802
- code =
1803
- `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
1804
- `var ${name} = createModule(${JSON.stringify(
1805
- getVirtualPathForDynamicRequirePath(dirname(actualId), commonDir)
1806
- )});\n` +
1807
- `export {${name} as __module}`;
1808
- } else {
1809
- code = `var ${name} = {exports: {}}; export {${name} as __module}`;
1810
- }
1925
+ const name = getName(unwrapId(id, MODULE_SUFFIX));
1811
1926
  return {
1812
- code,
1927
+ code: `var ${name} = {exports: {}}; export {${name} as __module}`,
1813
1928
  syntheticNamedExports: '__module',
1814
1929
  meta: { commonjs: { isCommonJS: false } }
1815
1930
  };
1816
1931
  }
1817
1932
 
1818
1933
  if (isWrappedId(id, EXPORTS_SUFFIX)) {
1819
- const actualId = unwrapId(id, EXPORTS_SUFFIX);
1820
- const name = getName(actualId);
1934
+ const name = getName(unwrapId(id, EXPORTS_SUFFIX));
1821
1935
  return {
1822
1936
  code: `var ${name} = {}; export {${name} as __exports}`,
1823
1937
  meta: { commonjs: { isCommonJS: false } }
@@ -1832,22 +1946,16 @@ function commonjs(options = {}) {
1832
1946
  );
1833
1947
  }
1834
1948
 
1835
- if (id === DYNAMIC_PACKAGES_ID) {
1836
- return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
1837
- }
1838
-
1839
- if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
1840
- return getDynamicJsonProxy(id, commonDir);
1841
- }
1842
-
1843
- if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
1844
- return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
1949
+ if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
1950
+ return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
1845
1951
  }
1846
1952
 
1847
- if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1848
- return getDynamicRequireProxy(
1849
- normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
1850
- commonDir
1953
+ if (id === DYNAMIC_MODULES_ID) {
1954
+ return getDynamicModuleRegistry(
1955
+ isDynamicRequireModulesEnabled,
1956
+ dynamicRequireModules,
1957
+ commonDir,
1958
+ ignoreDynamicRequires
1851
1959
  );
1852
1960
  }
1853
1961
 
@@ -1858,46 +1966,27 @@ function commonjs(options = {}) {
1858
1966
  getRequireReturnsDefault(actualId),
1859
1967
  esModulesWithDefaultExport,
1860
1968
  esModulesWithNamedExports,
1861
- commonJsMetaPromises
1969
+ this.load
1862
1970
  );
1863
1971
  }
1864
1972
 
1865
1973
  return null;
1866
1974
  },
1867
1975
 
1868
- transform(code, rawId) {
1869
- let id = rawId;
1870
-
1871
- if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
1872
- id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
1873
- }
1874
-
1976
+ transform(code, id) {
1875
1977
  const extName = extname(id);
1876
- if (
1877
- extName !== '.cjs' &&
1878
- id !== DYNAMIC_PACKAGES_ID &&
1879
- !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1880
- (!filter(id) || !extensions.includes(extName))
1881
- ) {
1978
+ if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {
1882
1979
  return null;
1883
1980
  }
1884
1981
 
1885
1982
  try {
1886
- return transformAndCheckExports.call(this, code, rawId);
1983
+ return transformAndCheckExports.call(this, code, id);
1887
1984
  } catch (err) {
1888
1985
  return this.error(err, err.loc);
1889
1986
  }
1890
- },
1891
-
1892
- moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
1893
- if (commonjsMeta && commonjsMeta.isCommonJS != null) {
1894
- setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
1895
- return;
1896
- }
1897
- setCommonJSMetaPromise(commonJsMetaPromises, id, null);
1898
1987
  }
1899
1988
  };
1900
1989
  }
1901
1990
 
1902
- export default commonjs;
1991
+ export { commonjs as default };
1903
1992
  //# sourceMappingURL=index.es.js.map