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