@rollup/plugin-commonjs 21.0.0 → 22.0.0-2

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