@rollup/plugin-commonjs 22.0.0-1 → 22.0.0-10

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.
@@ -7,9 +7,9 @@ import { walk } from 'estree-walker';
7
7
  import MagicString from 'magic-string';
8
8
  import isReference from 'is-reference';
9
9
 
10
- var version = "22.0.0-1";
10
+ var version = " 22.0.0-10";
11
11
  var peerDependencies = {
12
- rollup: "^2.60.0"
12
+ rollup: "^2.67.0"
13
13
  };
14
14
 
15
15
  function tryParse(parse, code, id) {
@@ -194,6 +194,9 @@ function getDynamicRequireModules(patterns, dynamicRequireRoot) {
194
194
 
195
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.');`;
196
196
 
197
+ const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
198
+ const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';
199
+
197
200
  function getDynamicModuleRegistry(
198
201
  isDynamicRequireModulesEnabled,
199
202
  dynamicRequireModules,
@@ -201,7 +204,7 @@ function getDynamicModuleRegistry(
201
204
  ignoreDynamicRequires
202
205
  ) {
203
206
  if (!isDynamicRequireModulesEnabled) {
204
- return `export function commonjsRequire(path) {
207
+ return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
205
208
  ${FAILED_REQUIRE_ERROR}
206
209
  }`;
207
210
  }
@@ -231,25 +234,25 @@ ${dynamicModuleProps}
231
234
  });
232
235
  }
233
236
 
234
- export function commonjsRequire(path, originalModuleDir) {
235
- var resolvedPath = commonjsResolveImpl(path, originalModuleDir);
236
- if (resolvedPath !== null) {
237
- return getDynamicModules()[resolvedPath]();
237
+ export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
238
+ function handleRequire(path) {
239
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
240
+ if (resolvedPath !== null) {
241
+ return getDynamicModules()[resolvedPath]();
242
+ }
243
+ ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
238
244
  }
239
- ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
240
- }
241
-
242
- function commonjsResolve (path, originalModuleDir) {
243
- const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
244
- if (resolvedPath !== null) {
245
- return resolvedPath;
245
+ handleRequire.resolve = function (path) {
246
+ var resolvedPath = commonjsResolve(path, originalModuleDir);
247
+ if (resolvedPath !== null) {
248
+ return resolvedPath;
249
+ }
250
+ return require.resolve(path);
246
251
  }
247
- return require.resolve(path);
252
+ return handleRequire;
248
253
  }
249
254
 
250
- commonjsRequire.resolve = commonjsResolve;
251
-
252
- function commonjsResolveImpl (path, originalModuleDir) {
255
+ function commonjsResolve (path, originalModuleDir) {
253
256
  var shouldTryNodeModules = isPossibleNodeModulesPath(path);
254
257
  path = normalize(path);
255
258
  var relPath;
@@ -325,7 +328,8 @@ const WRAPPED_SUFFIX = '?commonjs-wrapped';
325
328
  const EXTERNAL_SUFFIX = '?commonjs-external';
326
329
  const EXPORTS_SUFFIX = '?commonjs-exports';
327
330
  const MODULE_SUFFIX = '?commonjs-module';
328
- const ES_IMPORT_SUFFIX = '?es-import';
331
+ const ENTRY_SUFFIX = '?commonjs-entry';
332
+ const ES_IMPORT_SUFFIX = '?commonjs-es-import';
329
333
 
330
334
  const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
331
335
  const HELPERS_ID = '\0commonjsHelpers.js';
@@ -393,21 +397,15 @@ function getUnknownRequireProxy(id, requireReturnsDefault) {
393
397
  return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
394
398
  }
395
399
 
396
- async function getStaticRequireProxy(
397
- id,
398
- requireReturnsDefault,
399
- esModulesWithDefaultExport,
400
- esModulesWithNamedExports,
401
- loadModule
402
- ) {
400
+ async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
403
401
  const name = getName(id);
404
402
  const {
405
403
  meta: { commonjs: commonjsMeta }
406
404
  } = await loadModule({ id });
407
- if (commonjsMeta && commonjsMeta.isCommonJS) {
408
- return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
409
- } else if (!commonjsMeta) {
405
+ if (!commonjsMeta) {
410
406
  return getUnknownRequireProxy(id, requireReturnsDefault);
407
+ } else if (commonjsMeta.isCommonJS) {
408
+ return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
411
409
  } else if (!requireReturnsDefault) {
412
410
  return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
413
411
  id
@@ -415,14 +413,30 @@ async function getStaticRequireProxy(
415
413
  } else if (
416
414
  requireReturnsDefault !== true &&
417
415
  (requireReturnsDefault === 'namespace' ||
418
- !esModulesWithDefaultExport.has(id) ||
419
- (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
416
+ !commonjsMeta.hasDefaultExport ||
417
+ (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
420
418
  ) {
421
419
  return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
422
420
  }
423
421
  return `export { default } from ${JSON.stringify(id)};`;
424
422
  }
425
423
 
424
+ function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) {
425
+ const {
426
+ meta: { commonjs: commonjsMeta },
427
+ hasDefaultExport
428
+ } = getModuleInfo(id);
429
+ if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
430
+ const stringifiedId = JSON.stringify(id);
431
+ let code = `export * from ${stringifiedId};`;
432
+ if (hasDefaultExport) {
433
+ code += `export { default } from ${stringifiedId};`;
434
+ }
435
+ return code;
436
+ }
437
+ return getEsImportProxy(id, defaultIsModuleExports);
438
+ }
439
+
426
440
  function getEsImportProxy(id, defaultIsModuleExports) {
427
441
  const name = getName(id);
428
442
  const exportsName = `${name}Exports`;
@@ -478,11 +492,9 @@ function resolveExtensions(importee, importer, extensions) {
478
492
 
479
493
  function getResolveId(extensions) {
480
494
  return async function resolveId(importee, importer, resolveOptions) {
481
- if (
482
- resolveOptions.custom &&
483
- resolveOptions.custom.commonjs &&
484
- resolveOptions.custom.commonjs.skipResolver
485
- ) {
495
+ // We assume that all requires are pre-resolved
496
+ const customOptions = resolveOptions.custom;
497
+ if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
486
498
  return null;
487
499
  }
488
500
  if (isWrappedId(importee, WRAPPED_SUFFIX)) {
@@ -490,6 +502,7 @@ function getResolveId(extensions) {
490
502
  }
491
503
 
492
504
  if (
505
+ importee.endsWith(ENTRY_SUFFIX) ||
493
506
  isWrappedId(importee, MODULE_SUFFIX) ||
494
507
  isWrappedId(importee, EXPORTS_SUFFIX) ||
495
508
  isWrappedId(importee, PROXY_SUFFIX) ||
@@ -506,7 +519,8 @@ function getResolveId(extensions) {
506
519
  importer === DYNAMIC_MODULES_ID ||
507
520
  // Proxies are only importing resolved ids, no need to resolve again
508
521
  isWrappedId(importer, PROXY_SUFFIX) ||
509
- isWrappedId(importer, ES_IMPORT_SUFFIX)
522
+ isWrappedId(importer, ES_IMPORT_SUFFIX) ||
523
+ importer.endsWith(ENTRY_SUFFIX)
510
524
  ) {
511
525
  return importee;
512
526
  }
@@ -526,22 +540,27 @@ function getResolveId(extensions) {
526
540
 
527
541
  // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
528
542
  // if that is the case, we need to add a proxy.
529
- const customOptions = resolveOptions.custom;
530
-
531
- // If this is a require, we do not need a proxy
532
- if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
533
- return null;
534
- }
535
-
536
543
  const resolved =
537
544
  (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
538
545
  resolveExtensions(importee, importer, extensions);
539
- if (!resolved || resolved.external) {
546
+ // Make sure that even if other plugins resolve again, we ignore our own proxies
547
+ if (
548
+ !resolved ||
549
+ resolved.external ||
550
+ resolved.id.endsWith(ENTRY_SUFFIX) ||
551
+ isWrappedId(resolved.id, ES_IMPORT_SUFFIX)
552
+ ) {
540
553
  return resolved;
541
554
  }
555
+ const moduleInfo = await this.load(resolved);
556
+ if (resolveOptions.isEntry) {
557
+ moduleInfo.moduleSideEffects = true;
558
+ // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
559
+ return resolved.id + ENTRY_SUFFIX;
560
+ }
542
561
  const {
543
562
  meta: { commonjs: commonjsMeta }
544
- } = await this.load(resolved);
563
+ } = moduleInfo;
545
564
  if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
546
565
  return wrapId(resolved.id, ES_IMPORT_SUFFIX);
547
566
  }
@@ -549,14 +568,73 @@ function getResolveId(extensions) {
549
568
  };
550
569
  }
551
570
 
552
- function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional) {
571
+ function getRequireResolver(extensions, detectCyclesAndConditional) {
553
572
  const knownCjsModuleTypes = Object.create(null);
554
573
  const requiredIds = Object.create(null);
555
574
  const unconditionallyRequiredIds = Object.create(null);
556
- const parentModules = Object.create(null);
557
- const childModules = Object.create(null);
558
- const getParentModules = (id) => parentModules[id] || (parentModules[id] = Object.create(null));
559
- const getChildModules = (id) => childModules[id] || (childModules[id] = Object.create(null));
575
+ const dependencies = Object.create(null);
576
+ const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
577
+
578
+ const isCyclic = (id) => {
579
+ const dependenciesToCheck = new Set(getDependencies(id));
580
+ for (const dependency of dependenciesToCheck) {
581
+ if (dependency === id) {
582
+ return true;
583
+ }
584
+ for (const childDependency of getDependencies(dependency)) {
585
+ dependenciesToCheck.add(childDependency);
586
+ }
587
+ }
588
+ return false;
589
+ };
590
+
591
+ const fullyAnalyzedModules = Object.create(null);
592
+
593
+ const getTypeForFullyAnalyzedModule = (id) => {
594
+ const knownType = knownCjsModuleTypes[id];
595
+ if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
596
+ return knownType;
597
+ }
598
+ fullyAnalyzedModules[id] = true;
599
+ if (isCyclic(id)) {
600
+ return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
601
+ }
602
+ return knownType;
603
+ };
604
+
605
+ const setInitialParentType = (id, initialCommonJSType) => {
606
+ // It is possible a transformed module is already fully analyzed when using
607
+ // the cache and one dependency introduces a new cycle. Then transform is
608
+ // run for a fully analzyed module again. Fully analyzed modules may never
609
+ // change their type as importers already trust their type.
610
+ knownCjsModuleTypes[id] = fullyAnalyzedModules[id]
611
+ ? knownCjsModuleTypes[id]
612
+ : initialCommonJSType;
613
+ if (
614
+ detectCyclesAndConditional &&
615
+ knownCjsModuleTypes[id] === true &&
616
+ requiredIds[id] &&
617
+ !unconditionallyRequiredIds[id]
618
+ ) {
619
+ knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
620
+ }
621
+ };
622
+
623
+ const setTypesForRequiredModules = async (parentId, resolved, isConditional, loadModule) => {
624
+ const childId = resolved.id;
625
+ requiredIds[childId] = true;
626
+ if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
627
+ unconditionallyRequiredIds[childId] = true;
628
+ }
629
+
630
+ getDependencies(parentId).add(childId);
631
+ if (!isCyclic(childId)) {
632
+ // This makes sure the current transform handler waits for all direct dependencies to be
633
+ // loaded and transformed and therefore for all transitive CommonJS dependencies to be
634
+ // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
635
+ await loadModule(resolved);
636
+ }
637
+ };
560
638
 
561
639
  return {
562
640
  getWrappedIds: () =>
@@ -564,19 +642,40 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
564
642
  (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
565
643
  ),
566
644
  isRequiredId: (id) => requiredIds[id],
567
- resolveRequireSourcesAndGetMeta: (rollupContext) => async (
645
+ async shouldTransformCachedModule({ id: parentId, meta: { commonjs: parentMeta } }) {
646
+ // Ignore modules that did not pass through the original transformer in a previous build
647
+ if (!(parentMeta && parentMeta.requires)) {
648
+ return false;
649
+ }
650
+ setInitialParentType(parentId, parentMeta.initialCommonJSType);
651
+ await Promise.all(
652
+ parentMeta.requires.map(({ resolved, isConditional }) =>
653
+ setTypesForRequiredModules(parentId, resolved, isConditional, this.load)
654
+ )
655
+ );
656
+ if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
657
+ return true;
658
+ }
659
+ for (const {
660
+ resolved: { id }
661
+ } of parentMeta.requires) {
662
+ if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
663
+ return true;
664
+ }
665
+ }
666
+ return false;
667
+ },
668
+ /* eslint-disable no-param-reassign */
669
+ resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (
568
670
  parentId,
569
671
  isParentCommonJS,
672
+ parentMeta,
570
673
  sources
571
674
  ) => {
572
- knownCjsModuleTypes[parentId] = knownCjsModuleTypes[parentId] || isParentCommonJS;
573
- if (
574
- knownCjsModuleTypes[parentId] &&
575
- requiredIds[parentId] &&
576
- !unconditionallyRequiredIds[parentId]
577
- ) {
578
- knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
579
- }
675
+ parentMeta.initialCommonJSType = isParentCommonJS;
676
+ parentMeta.requires = [];
677
+ parentMeta.isRequiredCommonJS = Object.create(null);
678
+ setInitialParentType(parentId, isParentCommonJS);
580
679
  const requireTargets = await Promise.all(
581
680
  sources.map(async ({ source, isConditional }) => {
582
681
  // Never analyze or proxy internal modules
@@ -585,10 +684,7 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
585
684
  }
586
685
  const resolved =
587
686
  (await rollupContext.resolve(source, parentId, {
588
- custom: {
589
- 'node-resolve': { isRequire: true },
590
- commonjs: { skipResolver: true }
591
- }
687
+ custom: { 'node-resolve': { isRequire: true } }
592
688
  })) || resolveExtensions(source, parentId, extensions);
593
689
  if (!resolved) {
594
690
  return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
@@ -597,96 +693,58 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
597
693
  if (resolved.external) {
598
694
  return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
599
695
  }
600
- requiredIds[childId] = true;
601
- if (
602
- !(
603
- detectCyclesAndConditional &&
604
- (isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)
605
- )
606
- ) {
607
- unconditionallyRequiredIds[childId] = true;
608
- }
609
- const parentDependentModules = getParentModules(parentId);
610
- const childDependentModules = getParentModules(childId);
611
-
612
- // Copy the parents of the current parent to the child
613
- for (const dependentId of Object.keys(parentDependentModules)) {
614
- childDependentModules[dependentId] = true;
615
- }
616
-
617
- // Add the current parent to the child as well. If the child module already has known
618
- // dependencies because it has already been loaded, add the current parent module to their
619
- // parent modules
620
- childDependentModules[parentId] = true;
621
- const dependenciesToUpdate = new Set(Object.keys(getChildModules(childId)));
622
- for (const dependencyId of dependenciesToUpdate) {
623
- getParentModules(dependencyId)[parentId] = true;
624
- for (const subDependencyId of Object.keys(getChildModules(dependencyId))) {
625
- dependenciesToUpdate.add(subDependencyId);
626
- }
627
- }
628
-
629
- // Add the child as a dependency to the parent
630
- getChildModules(parentId)[childId] = true;
631
-
632
- // If we depend on one of our dependencies, we have a cycle. Then all modules that
633
- // we depend on that also depend on the same module are part of a cycle as well. Trying
634
- // to wait for loading this module would lead to a deadlock.
635
- if (parentDependentModules[childId]) {
636
- if (detectCyclesAndConditional && isParentCommonJS) {
637
- knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
638
- knownCjsModuleTypes[childId] = IS_WRAPPED_COMMONJS;
639
- for (const dependentId of Object.keys(parentDependentModules)) {
640
- if (getParentModules(dependentId)[childId]) {
641
- knownCjsModuleTypes[dependentId] = IS_WRAPPED_COMMONJS;
642
- }
643
- }
644
- }
645
- } else {
646
- // This makes sure the current transform handler waits for all direct dependencies to be
647
- // loaded and transformed and therefore for all transitive CommonJS dependencies to be
648
- // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
649
- await rollupContext.load(resolved);
650
- }
696
+ parentMeta.requires.push({ resolved, isConditional });
697
+ await setTypesForRequiredModules(parentId, resolved, isConditional, rollupContext.load);
651
698
  return { id: childId, allowProxy: true };
652
699
  })
653
700
  );
654
- return {
655
- requireTargets: requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
656
- const isCommonJS = knownCjsModuleTypes[dependencyId];
657
- return {
658
- source: sources[index].source,
659
- id: allowProxy
660
- ? isCommonJS === IS_WRAPPED_COMMONJS
661
- ? wrapId(dependencyId, WRAPPED_SUFFIX)
662
- : wrapId(dependencyId, PROXY_SUFFIX)
663
- : dependencyId,
664
- isCommonJS
665
- };
666
- }),
667
- usesRequireWrapper: knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS
668
- };
701
+ parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
702
+ return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
703
+ // eslint-disable-next-line no-multi-assign
704
+ const isCommonJS = (parentMeta.isRequiredCommonJS[
705
+ dependencyId
706
+ ] = getTypeForFullyAnalyzedModule(dependencyId));
707
+ return {
708
+ source: sources[index].source,
709
+ id: allowProxy
710
+ ? isCommonJS === IS_WRAPPED_COMMONJS
711
+ ? wrapId(dependencyId, WRAPPED_SUFFIX)
712
+ : wrapId(dependencyId, PROXY_SUFFIX)
713
+ : dependencyId,
714
+ isCommonJS
715
+ };
716
+ });
669
717
  }
670
718
  };
671
719
  }
672
720
 
673
- function validateRollupVersion(rollupVersion, peerDependencyVersion) {
674
- const [major, minor] = rollupVersion.split('.').map(Number);
675
- const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
721
+ function validateVersion(actualVersion, peerDependencyVersion, name) {
722
+ const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
676
723
  let minMajor = Infinity;
677
724
  let minMinor = Infinity;
725
+ let minPatch = Infinity;
678
726
  let foundVersion;
679
727
  // eslint-disable-next-line no-cond-assign
680
728
  while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
681
- const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
729
+ const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
682
730
  if (foundMajor < minMajor) {
683
731
  minMajor = foundMajor;
684
732
  minMinor = foundMinor;
733
+ minPatch = foundPatch;
685
734
  }
686
735
  }
687
- if (major < minMajor || (major === minMajor && minor < minMinor)) {
736
+ if (!actualVersion) {
688
737
  throw new Error(
689
- `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
738
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
739
+ );
740
+ }
741
+ const [major, minor, patch] = actualVersion.split('.').map(Number);
742
+ if (
743
+ major < minMajor ||
744
+ (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
745
+ ) {
746
+ throw new Error(
747
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
690
748
  );
691
749
  }
692
750
  }
@@ -1129,17 +1187,20 @@ function getRequireHandlers() {
1129
1187
  exportsName,
1130
1188
  id,
1131
1189
  exportMode,
1132
- resolveRequireSourcesAndGetMeta,
1190
+ resolveRequireSourcesAndUpdateMeta,
1133
1191
  needsRequireWrapper,
1134
1192
  isEsModule,
1135
- usesRequire,
1136
- getIgnoreTryCatchRequireStatementMode
1193
+ isDynamicRequireModulesEnabled,
1194
+ getIgnoreTryCatchRequireStatementMode,
1195
+ commonjsMeta
1137
1196
  ) {
1138
1197
  const imports = [];
1139
1198
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1140
- if (usesRequire) {
1199
+ if (dynamicRequireName) {
1141
1200
  imports.push(
1142
- `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1201
+ `import { ${
1202
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1203
+ } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1143
1204
  );
1144
1205
  }
1145
1206
  if (exportMode === 'module') {
@@ -1154,9 +1215,10 @@ function getRequireHandlers() {
1154
1215
  );
1155
1216
  }
1156
1217
  const requiresBySource = collectSources(requireExpressions);
1157
- const { requireTargets, usesRequireWrapper } = await resolveRequireSourcesAndGetMeta(
1218
+ const requireTargets = await resolveRequireSourcesAndUpdateMeta(
1158
1219
  id,
1159
1220
  needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
1221
+ commonjsMeta,
1160
1222
  Object.keys(requiresBySource).map((source) => {
1161
1223
  return {
1162
1224
  source,
@@ -1171,10 +1233,7 @@ function getRequireHandlers() {
1171
1233
  getIgnoreTryCatchRequireStatementMode,
1172
1234
  magicString
1173
1235
  );
1174
- return {
1175
- importBlock: imports.length ? `${imports.join('\n')}\n\n` : '',
1176
- usesRequireWrapper
1177
- };
1236
+ return imports.length ? `${imports.join('\n')}\n\n` : '';
1178
1237
  }
1179
1238
 
1180
1239
  return {
@@ -1277,9 +1336,10 @@ async function transformCommonjs(
1277
1336
  astCache,
1278
1337
  defaultIsModuleExports,
1279
1338
  needsRequireWrapper,
1280
- resolveRequireSourcesAndGetMeta,
1339
+ resolveRequireSourcesAndUpdateMeta,
1281
1340
  isRequired,
1282
- checkDynamicRequire
1341
+ checkDynamicRequire,
1342
+ commonjsMeta
1283
1343
  ) {
1284
1344
  const ast = astCache || tryParse(parse, code, id);
1285
1345
  const magicString = new MagicString(code);
@@ -1320,6 +1380,7 @@ async function transformCommonjs(
1320
1380
  const topLevelDefineCompiledEsmExpressions = [];
1321
1381
  const replacedGlobal = [];
1322
1382
  const replacedDynamicRequires = [];
1383
+ const importedVariables = new Set();
1323
1384
 
1324
1385
  walk(ast, {
1325
1386
  enter(node, parent) {
@@ -1425,20 +1486,19 @@ async function transformCommonjs(
1425
1486
  isRequire(node.callee.object, scope) &&
1426
1487
  node.callee.property.name === 'resolve'
1427
1488
  ) {
1428
- checkDynamicRequire();
1489
+ checkDynamicRequire(node.start);
1429
1490
  uses.require = true;
1430
1491
  const requireNode = node.callee.object;
1431
- magicString.appendLeft(
1432
- node.end - 1,
1433
- `,${JSON.stringify(
1434
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1435
- )}`
1436
- );
1437
1492
  replacedDynamicRequires.push(requireNode);
1438
1493
  return;
1439
1494
  }
1440
1495
 
1441
1496
  if (!isRequireExpression(node, scope)) {
1497
+ const keypath = getKeypath(node.callee);
1498
+ if (keypath && importedVariables.has(keypath.name)) {
1499
+ // Heuristic to deoptimize requires after a required function has been called
1500
+ currentConditionalNodeEnd = Infinity;
1501
+ }
1442
1502
  return;
1443
1503
  }
1444
1504
 
@@ -1447,15 +1507,9 @@ async function transformCommonjs(
1447
1507
 
1448
1508
  if (hasDynamicArguments(node)) {
1449
1509
  if (isDynamicRequireModulesEnabled) {
1450
- magicString.appendLeft(
1451
- node.end - 1,
1452
- `, ${JSON.stringify(
1453
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1454
- )}`
1455
- );
1510
+ checkDynamicRequire(node.start);
1456
1511
  }
1457
1512
  if (!ignoreDynamicRequires) {
1458
- checkDynamicRequire();
1459
1513
  replacedDynamicRequires.push(node.callee);
1460
1514
  }
1461
1515
  return;
@@ -1473,6 +1527,11 @@ async function transformCommonjs(
1473
1527
  currentConditionalNodeEnd !== null,
1474
1528
  parent.type === 'ExpressionStatement' ? parent : node
1475
1529
  );
1530
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
1531
+ for (const name of extractAssignedNames(parent.id)) {
1532
+ importedVariables.add(name);
1533
+ }
1534
+ }
1476
1535
  }
1477
1536
  return;
1478
1537
  }
@@ -1513,7 +1572,6 @@ async function transformCommonjs(
1513
1572
  return;
1514
1573
  }
1515
1574
  if (!ignoreDynamicRequires) {
1516
- checkDynamicRequire();
1517
1575
  if (isShorthandProperty(parent)) {
1518
1576
  magicString.prependRight(node.start, 'require: ');
1519
1577
  }
@@ -1597,9 +1655,10 @@ async function transformCommonjs(
1597
1655
  if (scope.contains(flattened.name)) return;
1598
1656
 
1599
1657
  if (
1600
- flattened.keypath === 'module.exports' ||
1601
- flattened.keypath === 'module' ||
1602
- flattened.keypath === 'exports'
1658
+ !isEsModule &&
1659
+ (flattened.keypath === 'module.exports' ||
1660
+ flattened.keypath === 'module' ||
1661
+ flattened.keypath === 'exports')
1603
1662
  ) {
1604
1663
  magicString.overwrite(node.start, node.end, `'object'`, {
1605
1664
  storeName: false
@@ -1627,7 +1686,13 @@ async function transformCommonjs(
1627
1686
  const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1628
1687
  const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1629
1688
  const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1630
- const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
1689
+ const dynamicRequireName =
1690
+ replacedDynamicRequires.length > 0 &&
1691
+ deconflict(
1692
+ [scope],
1693
+ globals,
1694
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1695
+ );
1631
1696
  const deconflictedExportNames = Object.create(null);
1632
1697
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1633
1698
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
@@ -1639,10 +1704,17 @@ async function transformCommonjs(
1639
1704
  });
1640
1705
  }
1641
1706
  for (const node of replacedDynamicRequires) {
1642
- magicString.overwrite(node.start, node.end, dynamicRequireName, {
1643
- contentOnly: true,
1644
- storeName: true
1645
- });
1707
+ magicString.overwrite(
1708
+ node.start,
1709
+ node.end,
1710
+ isDynamicRequireModulesEnabled
1711
+ ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
1712
+ : dynamicRequireName,
1713
+ {
1714
+ contentOnly: true,
1715
+ storeName: true
1716
+ }
1717
+ );
1646
1718
  }
1647
1719
 
1648
1720
  // We cannot wrap ES/mixed modules
@@ -1662,7 +1734,7 @@ async function transformCommonjs(
1662
1734
  ) &&
1663
1735
  (ignoreGlobal || !uses.global)
1664
1736
  ) {
1665
- return { meta: { commonjs: { isCommonJS: false, isMixedModule: false } } };
1737
+ return { meta: { commonjs: { isCommonJS: false } } };
1666
1738
  }
1667
1739
 
1668
1740
  let leadingComment = '';
@@ -1684,7 +1756,7 @@ async function transformCommonjs(
1684
1756
  ? 'exports'
1685
1757
  : 'module';
1686
1758
 
1687
- const { importBlock, usesRequireWrapper } = await rewriteRequireExpressionsAndGetImportBlock(
1759
+ const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
1688
1760
  magicString,
1689
1761
  topLevelDeclarations,
1690
1762
  reassignedNames,
@@ -1694,12 +1766,14 @@ async function transformCommonjs(
1694
1766
  exportsName,
1695
1767
  id,
1696
1768
  exportMode,
1697
- resolveRequireSourcesAndGetMeta,
1769
+ resolveRequireSourcesAndUpdateMeta,
1698
1770
  needsRequireWrapper,
1699
1771
  isEsModule,
1700
- uses.require,
1701
- getIgnoreTryCatchRequireStatementMode
1772
+ isDynamicRequireModulesEnabled,
1773
+ getIgnoreTryCatchRequireStatementMode,
1774
+ commonjsMeta
1702
1775
  );
1776
+ const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
1703
1777
  const exportBlock = isEsModule
1704
1778
  ? ''
1705
1779
  : rewriteExportsAndGetExportsBlock(
@@ -1752,15 +1826,12 @@ function ${requireName} () {
1752
1826
  code: magicString.toString(),
1753
1827
  map: sourceMap ? magicString.generateMap() : null,
1754
1828
  syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
1755
- meta: {
1756
- commonjs: {
1757
- isCommonJS: !isEsModule && (usesRequireWrapper ? IS_WRAPPED_COMMONJS : true),
1758
- isMixedModule: isEsModule
1759
- }
1760
- }
1829
+ meta: { commonjs: commonjsMeta }
1761
1830
  };
1762
1831
  }
1763
1832
 
1833
+ const PLUGIN_NAME = 'commonjs';
1834
+
1764
1835
  function commonjs(options = {}) {
1765
1836
  const {
1766
1837
  ignoreGlobal,
@@ -1788,11 +1859,6 @@ function commonjs(options = {}) {
1788
1859
  const defaultIsModuleExports =
1789
1860
  typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1790
1861
 
1791
- const {
1792
- resolveRequireSourcesAndGetMeta,
1793
- getWrappedIds,
1794
- isRequiredId
1795
- } = getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndConditional);
1796
1862
  const dynamicRequireRoot =
1797
1863
  typeof options.dynamicRequireRoot === 'string'
1798
1864
  ? resolve(options.dynamicRequireRoot)
@@ -1803,9 +1869,6 @@ function commonjs(options = {}) {
1803
1869
  );
1804
1870
  const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
1805
1871
 
1806
- const esModulesWithDefaultExport = new Set();
1807
- const esModulesWithNamedExports = new Set();
1808
-
1809
1872
  const ignoreRequire =
1810
1873
  typeof options.ignore === 'function'
1811
1874
  ? options.ignore
@@ -1833,41 +1896,50 @@ function commonjs(options = {}) {
1833
1896
 
1834
1897
  const sourceMap = options.sourceMap !== false;
1835
1898
 
1899
+ // Initialized in buildStart
1900
+ let requireResolver;
1901
+
1836
1902
  function transformAndCheckExports(code, id) {
1837
1903
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
1838
1904
  this.parse,
1839
1905
  code,
1840
1906
  id
1841
1907
  );
1908
+
1909
+ const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
1842
1910
  if (hasDefaultExport) {
1843
- esModulesWithDefaultExport.add(id);
1911
+ commonjsMeta.hasDefaultExport = true;
1844
1912
  }
1845
1913
  if (hasNamedExports) {
1846
- esModulesWithNamedExports.add(id);
1914
+ commonjsMeta.hasNamedExports = true;
1847
1915
  }
1848
1916
 
1849
1917
  if (
1850
1918
  !dynamicRequireModules.has(normalizePathSlashes(id)) &&
1851
- (!(hasCjsKeywords(code, ignoreGlobal) || isRequiredId(id)) ||
1919
+ (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
1852
1920
  (isEsModule && !options.transformMixedEsModules))
1853
1921
  ) {
1854
- return { meta: { commonjs: { isCommonJS: false } } };
1922
+ commonjsMeta.isCommonJS = false;
1923
+ return { meta: { commonjs: commonjsMeta } };
1855
1924
  }
1856
1925
 
1857
1926
  const needsRequireWrapper =
1858
1927
  !isEsModule &&
1859
1928
  (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1860
1929
 
1861
- const checkDynamicRequire = () => {
1930
+ const checkDynamicRequire = (position) => {
1862
1931
  if (id.indexOf(dynamicRequireRoot) !== 0) {
1863
- this.error({
1864
- code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1865
- id,
1866
- dynamicRequireRoot,
1867
- message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(
1868
- id
1869
- )}" or one of its parent directories.`
1870
- });
1932
+ this.error(
1933
+ {
1934
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1935
+ id,
1936
+ dynamicRequireRoot,
1937
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(
1938
+ id
1939
+ )}" or one of its parent directories.`
1940
+ },
1941
+ position
1942
+ );
1871
1943
  }
1872
1944
  };
1873
1945
 
@@ -1887,14 +1959,15 @@ function commonjs(options = {}) {
1887
1959
  ast,
1888
1960
  defaultIsModuleExports,
1889
1961
  needsRequireWrapper,
1890
- resolveRequireSourcesAndGetMeta(this),
1891
- isRequiredId(id),
1892
- checkDynamicRequire
1962
+ requireResolver.resolveRequireSourcesAndUpdateMeta(this),
1963
+ requireResolver.isRequiredId(id),
1964
+ checkDynamicRequire,
1965
+ commonjsMeta
1893
1966
  );
1894
1967
  }
1895
1968
 
1896
1969
  return {
1897
- name: 'commonjs',
1970
+ name: PLUGIN_NAME,
1898
1971
 
1899
1972
  version,
1900
1973
 
@@ -1902,7 +1975,7 @@ function commonjs(options = {}) {
1902
1975
  // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
1903
1976
  // do not prevent our plugin from resolving entry points ot proxies.
1904
1977
  const plugins = Array.isArray(rawOptions.plugins)
1905
- ? rawOptions.plugins
1978
+ ? [...rawOptions.plugins]
1906
1979
  : rawOptions.plugins
1907
1980
  ? [rawOptions.plugins]
1908
1981
  : [];
@@ -1913,18 +1986,23 @@ function commonjs(options = {}) {
1913
1986
  return { ...rawOptions, plugins };
1914
1987
  },
1915
1988
 
1916
- buildStart() {
1917
- validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1989
+ buildStart({ plugins }) {
1990
+ validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
1991
+ const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
1992
+ if (nodeResolve) {
1993
+ validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
1994
+ }
1918
1995
  if (options.namedExports != null) {
1919
1996
  this.warn(
1920
1997
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1921
1998
  );
1922
1999
  }
2000
+ requireResolver = getRequireResolver(extensions, detectCyclesAndConditional);
1923
2001
  },
1924
2002
 
1925
2003
  buildEnd() {
1926
2004
  if (options.strictRequires === 'debug') {
1927
- const wrappedIds = getWrappedIds();
2005
+ const wrappedIds = requireResolver.getWrappedIds();
1928
2006
  if (wrappedIds.length) {
1929
2007
  this.warn({
1930
2008
  code: 'WRAPPED_IDS',
@@ -1973,6 +2051,15 @@ function commonjs(options = {}) {
1973
2051
  );
1974
2052
  }
1975
2053
 
2054
+ // entry suffix is just appended to not mess up relative external resolution
2055
+ if (id.endsWith(ENTRY_SUFFIX)) {
2056
+ return getEntryProxy(
2057
+ id.slice(0, -ENTRY_SUFFIX.length),
2058
+ defaultIsModuleExports,
2059
+ this.getModuleInfo
2060
+ );
2061
+ }
2062
+
1976
2063
  if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
1977
2064
  return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
1978
2065
  }
@@ -1988,18 +2075,16 @@ function commonjs(options = {}) {
1988
2075
 
1989
2076
  if (isWrappedId(id, PROXY_SUFFIX)) {
1990
2077
  const actualId = unwrapId(id, PROXY_SUFFIX);
1991
- return getStaticRequireProxy(
1992
- actualId,
1993
- getRequireReturnsDefault(actualId),
1994
- esModulesWithDefaultExport,
1995
- esModulesWithNamedExports,
1996
- this.load
1997
- );
2078
+ return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
1998
2079
  }
1999
2080
 
2000
2081
  return null;
2001
2082
  },
2002
2083
 
2084
+ shouldTransformCachedModule(...args) {
2085
+ return requireResolver.shouldTransformCachedModule.call(this, ...args);
2086
+ },
2087
+
2003
2088
  transform(code, id) {
2004
2089
  const extName = extname(id);
2005
2090
  if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {
@@ -2016,4 +2101,4 @@ function commonjs(options = {}) {
2016
2101
  }
2017
2102
 
2018
2103
  export { commonjs as default };
2019
- //# sourceMappingURL=index.es.js.map
2104
+ //# sourceMappingURL=index.js.map