@rollup/plugin-commonjs 22.0.0-8 → 22.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/es/index.js CHANGED
@@ -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-8";
10
+ var version = "22.0.1";
11
11
  var peerDependencies = {
12
- rollup: "^2.66.1"
12
+ rollup: "^2.68.0"
13
13
  };
14
14
 
15
15
  function tryParse(parse, code, id) {
@@ -421,11 +421,11 @@ async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
421
421
  return `export { default } from ${JSON.stringify(id)};`;
422
422
  }
423
423
 
424
- async function getEntryProxy(id, defaultIsModuleExports, loadModule) {
424
+ function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) {
425
425
  const {
426
426
  meta: { commonjs: commonjsMeta },
427
427
  hasDefaultExport
428
- } = await loadModule({ id, moduleSideEffects: true });
428
+ } = getModuleInfo(id);
429
429
  if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
430
430
  const stringifiedId = JSON.stringify(id);
431
431
  let code = `export * from ${stringifiedId};`;
@@ -453,8 +453,7 @@ function getEsImportProxy(id, defaultIsModuleExports) {
453
453
  }
454
454
  return {
455
455
  code,
456
- syntheticNamedExports: '__moduleExports',
457
- meta: { commonjs: { isCommonJS: false } }
456
+ syntheticNamedExports: '__moduleExports'
458
457
  };
459
458
  }
460
459
 
@@ -490,93 +489,126 @@ function resolveExtensions(importee, importer, extensions) {
490
489
  return undefined;
491
490
  }
492
491
 
493
- function getResolveId(extensions) {
494
- return async function resolveId(importee, importer, resolveOptions) {
495
- // We assume that all requires are pre-resolved
496
- if (
497
- resolveOptions.custom &&
498
- resolveOptions.custom['node-resolve'] &&
499
- resolveOptions.custom['node-resolve'].isRequire
500
- ) {
501
- return null;
502
- }
503
- if (isWrappedId(importee, WRAPPED_SUFFIX)) {
504
- return unwrapId(importee, WRAPPED_SUFFIX);
505
- }
492
+ function getResolveId(extensions, isPossibleCjsId) {
493
+ const currentlyResolving = new Map();
506
494
 
507
- if (
508
- importee.endsWith(ENTRY_SUFFIX) ||
509
- isWrappedId(importee, MODULE_SUFFIX) ||
510
- isWrappedId(importee, EXPORTS_SUFFIX) ||
511
- isWrappedId(importee, PROXY_SUFFIX) ||
512
- isWrappedId(importee, ES_IMPORT_SUFFIX) ||
513
- isWrappedId(importee, EXTERNAL_SUFFIX) ||
514
- importee.startsWith(HELPERS_ID) ||
515
- importee === DYNAMIC_MODULES_ID
516
- ) {
517
- return importee;
518
- }
495
+ return {
496
+ /**
497
+ * This is a Maps of importers to Sets of require sources being resolved at
498
+ * the moment by resolveRequireSourcesAndUpdateMeta
499
+ */
500
+ currentlyResolving,
501
+ async resolveId(importee, importer, resolveOptions) {
502
+ const customOptions = resolveOptions.custom;
503
+ // All logic below is specific to ES imports.
504
+ // Also, if we do not skip this logic for requires that are resolved while
505
+ // transforming a commonjs file, it can easily lead to deadlocks.
506
+ if (
507
+ customOptions &&
508
+ customOptions['node-resolve'] &&
509
+ customOptions['node-resolve'].isRequire
510
+ ) {
511
+ return null;
512
+ }
513
+ const currentlyResolvingForParent = currentlyResolving.get(importer);
514
+ if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
515
+ this.warn({
516
+ code: 'THIS_RESOLVE_WITHOUT_OPTIONS',
517
+ message:
518
+ 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.',
519
+ url: 'https://rollupjs.org/guide/en/#resolveid'
520
+ });
521
+ return null;
522
+ }
523
+
524
+ if (isWrappedId(importee, WRAPPED_SUFFIX)) {
525
+ return unwrapId(importee, WRAPPED_SUFFIX);
526
+ }
519
527
 
520
- if (importer) {
521
528
  if (
522
- importer === DYNAMIC_MODULES_ID ||
523
- // Proxies are only importing resolved ids, no need to resolve again
524
- isWrappedId(importer, PROXY_SUFFIX) ||
525
- isWrappedId(importer, ES_IMPORT_SUFFIX) ||
526
- importer.endsWith(ENTRY_SUFFIX)
529
+ importee.endsWith(ENTRY_SUFFIX) ||
530
+ isWrappedId(importee, MODULE_SUFFIX) ||
531
+ isWrappedId(importee, EXPORTS_SUFFIX) ||
532
+ isWrappedId(importee, PROXY_SUFFIX) ||
533
+ isWrappedId(importee, ES_IMPORT_SUFFIX) ||
534
+ isWrappedId(importee, EXTERNAL_SUFFIX) ||
535
+ importee.startsWith(HELPERS_ID) ||
536
+ importee === DYNAMIC_MODULES_ID
527
537
  ) {
528
538
  return importee;
529
539
  }
530
- if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
531
- // We need to return null for unresolved imports so that the proper warning is shown
532
- if (!(await this.resolve(importee, importer, { skipSelf: true }))) {
533
- return null;
540
+
541
+ if (importer) {
542
+ if (
543
+ importer === DYNAMIC_MODULES_ID ||
544
+ // Proxies are only importing resolved ids, no need to resolve again
545
+ isWrappedId(importer, PROXY_SUFFIX) ||
546
+ isWrappedId(importer, ES_IMPORT_SUFFIX) ||
547
+ importer.endsWith(ENTRY_SUFFIX)
548
+ ) {
549
+ return importee;
550
+ }
551
+ if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
552
+ // We need to return null for unresolved imports so that the proper warning is shown
553
+ if (
554
+ !(await this.resolve(
555
+ importee,
556
+ importer,
557
+ Object.assign({ skipSelf: true }, resolveOptions)
558
+ ))
559
+ ) {
560
+ return null;
561
+ }
562
+ // For other external imports, we need to make sure they are handled as external
563
+ return { id: importee, external: true };
534
564
  }
535
- // For other external imports, we need to make sure they are handled as external
536
- return { id: importee, external: true };
537
565
  }
538
- }
539
-
540
- if (importee.startsWith('\0')) {
541
- return null;
542
- }
543
-
544
- // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
545
- // if that is the case, we need to add a proxy.
546
- const customOptions = resolveOptions.custom;
547
566
 
548
- // If this is a require, we do not need a proxy
549
- if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
550
- return null;
551
- }
567
+ if (importee.startsWith('\0')) {
568
+ return null;
569
+ }
552
570
 
553
- const resolved =
554
- (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
555
- resolveExtensions(importee, importer, extensions);
556
- // Make sure that even if other plugins resolve again, we ignore our own proxies
557
- if (
558
- !resolved ||
559
- resolved.external ||
560
- resolved.id.endsWith(ENTRY_SUFFIX) ||
561
- isWrappedId(resolved.id, ES_IMPORT_SUFFIX)
562
- ) {
571
+ // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
572
+ // if that is the case, we need to add a proxy.
573
+ const resolved =
574
+ (await this.resolve(
575
+ importee,
576
+ importer,
577
+ Object.assign({ skipSelf: true }, resolveOptions)
578
+ )) || resolveExtensions(importee, importer, extensions);
579
+ // Make sure that even if other plugins resolve again, we ignore our own proxies
580
+ if (
581
+ !resolved ||
582
+ resolved.external ||
583
+ resolved.id.endsWith(ENTRY_SUFFIX) ||
584
+ isWrappedId(resolved.id, ES_IMPORT_SUFFIX) ||
585
+ !isPossibleCjsId(resolved.id)
586
+ ) {
587
+ return resolved;
588
+ }
589
+ const moduleInfo = await this.load(resolved);
590
+ const {
591
+ meta: { commonjs: commonjsMeta }
592
+ } = moduleInfo;
593
+ if (commonjsMeta) {
594
+ const { isCommonJS } = commonjsMeta;
595
+ if (isCommonJS) {
596
+ if (resolveOptions.isEntry) {
597
+ moduleInfo.moduleSideEffects = true;
598
+ // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
599
+ return resolved.id + ENTRY_SUFFIX;
600
+ }
601
+ if (isCommonJS === IS_WRAPPED_COMMONJS) {
602
+ return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
603
+ }
604
+ }
605
+ }
563
606
  return resolved;
564
607
  }
565
- if (resolveOptions.isEntry) {
566
- // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
567
- return resolved.id + ENTRY_SUFFIX;
568
- }
569
- const {
570
- meta: { commonjs: commonjsMeta }
571
- } = await this.load(resolved);
572
- if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
573
- return wrapId(resolved.id, ES_IMPORT_SUFFIX);
574
- }
575
- return resolved;
576
608
  };
577
609
  }
578
610
 
579
- function getRequireResolver(extensions, detectCyclesAndConditional) {
611
+ function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) {
580
612
  const knownCjsModuleTypes = Object.create(null);
581
613
  const requiredIds = Object.create(null);
582
614
  const unconditionallyRequiredIds = Object.create(null);
@@ -596,6 +628,9 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
596
628
  return false;
597
629
  };
598
630
 
631
+ // Once a module is listed here, its type (wrapped or not) is fixed and may
632
+ // not change for the rest of the current build, to not break already
633
+ // transformed modules.
599
634
  const fullyAnalyzedModules = Object.create(null);
600
635
 
601
636
  const getTypeForFullyAnalyzedModule = (id) => {
@@ -603,7 +638,6 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
603
638
  if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
604
639
  return knownType;
605
640
  }
606
- fullyAnalyzedModules[id] = true;
607
641
  if (isCyclic(id)) {
608
642
  return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
609
643
  }
@@ -611,13 +645,11 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
611
645
  };
612
646
 
613
647
  const setInitialParentType = (id, initialCommonJSType) => {
614
- // It is possible a transformed module is already fully analyzed when using
615
- // the cache and one dependency introduces a new cycle. Then transform is
616
- // run for a fully analzyed module again. Fully analyzed modules may never
617
- // change their type as importers already trust their type.
618
- knownCjsModuleTypes[id] = fullyAnalyzedModules[id]
619
- ? knownCjsModuleTypes[id]
620
- : initialCommonJSType;
648
+ // Fully analyzed modules may never change type
649
+ if (fullyAnalyzedModules[id]) {
650
+ return;
651
+ }
652
+ knownCjsModuleTypes[id] = initialCommonJSType;
621
653
  if (
622
654
  detectCyclesAndConditional &&
623
655
  knownCjsModuleTypes[id] === true &&
@@ -628,7 +660,7 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
628
660
  }
629
661
  };
630
662
 
631
- const setTypesForRequiredModules = async (parentId, resolved, isConditional, loadModule) => {
663
+ const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
632
664
  const childId = resolved.id;
633
665
  requiredIds[childId] = true;
634
666
  if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
@@ -637,41 +669,85 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
637
669
 
638
670
  getDependencies(parentId).add(childId);
639
671
  if (!isCyclic(childId)) {
640
- // This makes sure the current transform handler waits for all direct dependencies to be
641
- // loaded and transformed and therefore for all transitive CommonJS dependencies to be
642
- // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
672
+ // This makes sure the current transform handler waits for all direct
673
+ // dependencies to be loaded and transformed and therefore for all
674
+ // transitive CommonJS dependencies to be loaded as well so that all
675
+ // cycles have been found and knownCjsModuleTypes is reliable.
643
676
  await loadModule(resolved);
644
677
  }
645
678
  };
646
679
 
680
+ const getTypeForImportedModule = async (resolved, loadModule) => {
681
+ if (resolved.id in knownCjsModuleTypes) {
682
+ // This handles cyclic ES dependencies
683
+ return knownCjsModuleTypes[resolved.id];
684
+ }
685
+ const {
686
+ meta: { commonjs }
687
+ } = await loadModule(resolved);
688
+ return (commonjs && commonjs.isCommonJS) || false;
689
+ };
690
+
647
691
  return {
648
692
  getWrappedIds: () =>
649
693
  Object.keys(knownCjsModuleTypes).filter(
650
694
  (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
651
695
  ),
652
696
  isRequiredId: (id) => requiredIds[id],
653
- async shouldTransformCachedModule({ id: parentId, meta: { commonjs: parentMeta } }) {
654
- // Ignore modules that did not pass through the original transformer in a previous build
655
- if (!(parentMeta && parentMeta.requires)) {
656
- return false;
657
- }
658
- setInitialParentType(parentId, parentMeta.initialCommonJSType);
659
- await Promise.all(
660
- parentMeta.requires.map(({ resolved, isConditional }) =>
661
- setTypesForRequiredModules(parentId, resolved, isConditional, this.load)
662
- )
663
- );
664
- if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
665
- return true;
666
- }
667
- for (const {
668
- resolved: { id }
669
- } of parentMeta.requires) {
670
- if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
697
+ async shouldTransformCachedModule({
698
+ id: parentId,
699
+ resolvedSources,
700
+ meta: { commonjs: parentMeta }
701
+ }) {
702
+ // We explicitly track ES modules to handle circular imports
703
+ if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
704
+ if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
705
+ const parentRequires = parentMeta && parentMeta.requires;
706
+ if (parentRequires) {
707
+ setInitialParentType(parentId, parentMeta.initialCommonJSType);
708
+ await Promise.all(
709
+ parentRequires.map(({ resolved, isConditional }) =>
710
+ analyzeRequiredModule(parentId, resolved, isConditional, this.load)
711
+ )
712
+ );
713
+ if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
671
714
  return true;
672
715
  }
716
+ for (const {
717
+ resolved: { id }
718
+ } of parentRequires) {
719
+ if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
720
+ return true;
721
+ }
722
+ }
723
+ // Now that we decided to go with the cached copy, neither the parent
724
+ // module nor any of its children may change types anymore
725
+ fullyAnalyzedModules[parentId] = true;
726
+ for (const {
727
+ resolved: { id }
728
+ } of parentRequires) {
729
+ fullyAnalyzedModules[id] = true;
730
+ }
673
731
  }
674
- return false;
732
+ const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
733
+ return (
734
+ await Promise.all(
735
+ Object.keys(resolvedSources)
736
+ .map((source) => resolvedSources[source])
737
+ .filter(({ id, external }) => !(external || parentRequireSet.has(id)))
738
+ .map(async (resolved) => {
739
+ if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
740
+ return (
741
+ (await getTypeForImportedModule(
742
+ (await this.load({ id: resolved.id })).meta.commonjs.resolved,
743
+ this.load
744
+ )) !== IS_WRAPPED_COMMONJS
745
+ );
746
+ }
747
+ return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS;
748
+ })
749
+ )
750
+ ).some((shouldTransform) => shouldTransform);
675
751
  },
676
752
  /* eslint-disable no-param-reassign */
677
753
  resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (
@@ -684,16 +760,20 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
684
760
  parentMeta.requires = [];
685
761
  parentMeta.isRequiredCommonJS = Object.create(null);
686
762
  setInitialParentType(parentId, isParentCommonJS);
763
+ const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set();
764
+ currentlyResolving.set(parentId, currentlyResolvingForParent);
687
765
  const requireTargets = await Promise.all(
688
766
  sources.map(async ({ source, isConditional }) => {
689
767
  // Never analyze or proxy internal modules
690
768
  if (source.startsWith('\0')) {
691
769
  return { id: source, allowProxy: false };
692
770
  }
771
+ currentlyResolvingForParent.add(source);
693
772
  const resolved =
694
773
  (await rollupContext.resolve(source, parentId, {
695
774
  custom: { 'node-resolve': { isRequire: true } }
696
775
  })) || resolveExtensions(source, parentId, extensions);
776
+ currentlyResolvingForParent.delete(source);
697
777
  if (!resolved) {
698
778
  return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
699
779
  }
@@ -702,16 +782,18 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
702
782
  return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
703
783
  }
704
784
  parentMeta.requires.push({ resolved, isConditional });
705
- await setTypesForRequiredModules(parentId, resolved, isConditional, rollupContext.load);
785
+ await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
706
786
  return { id: childId, allowProxy: true };
707
787
  })
708
788
  );
709
789
  parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
790
+ fullyAnalyzedModules[parentId] = true;
710
791
  return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
711
792
  // eslint-disable-next-line no-multi-assign
712
793
  const isCommonJS = (parentMeta.isRequiredCommonJS[
713
794
  dependencyId
714
795
  ] = getTypeForFullyAnalyzedModule(dependencyId));
796
+ fullyAnalyzedModules[dependencyId] = true;
715
797
  return {
716
798
  source: sources[index].source,
717
799
  id: allowProxy
@@ -722,6 +804,10 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
722
804
  isCommonJS
723
805
  };
724
806
  });
807
+ },
808
+ isCurrentlyResolving(source, parentId) {
809
+ const currentlyResolvingForParent = currentlyResolving.get(parentId);
810
+ return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
725
811
  }
726
812
  };
727
813
  }
@@ -1165,7 +1251,7 @@ function getRequireStringArg(node) {
1165
1251
  function getRequireHandlers() {
1166
1252
  const requireExpressions = [];
1167
1253
 
1168
- function addRequireStatement(
1254
+ function addRequireExpression(
1169
1255
  sourceId,
1170
1256
  node,
1171
1257
  scope,
@@ -1245,7 +1331,7 @@ function getRequireHandlers() {
1245
1331
  }
1246
1332
 
1247
1333
  return {
1248
- addRequireStatement,
1334
+ addRequireExpression,
1249
1335
  rewriteRequireExpressionsAndGetImportBlock
1250
1336
  };
1251
1337
  }
@@ -1364,6 +1450,7 @@ async function transformCommonjs(
1364
1450
  let programDepth = 0;
1365
1451
  let currentTryBlockEnd = null;
1366
1452
  let shouldWrap = false;
1453
+ let reexports = false;
1367
1454
 
1368
1455
  const globals = new Set();
1369
1456
  // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
@@ -1371,7 +1458,7 @@ async function transformCommonjs(
1371
1458
  // unconditional require elsewhere.
1372
1459
  let currentConditionalNodeEnd = null;
1373
1460
  const conditionalNodes = new Set();
1374
- const { addRequireStatement, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1461
+ const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1375
1462
 
1376
1463
  // See which names are assigned to. This is necessary to prevent
1377
1464
  // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
@@ -1388,6 +1475,7 @@ async function transformCommonjs(
1388
1475
  const topLevelDefineCompiledEsmExpressions = [];
1389
1476
  const replacedGlobal = [];
1390
1477
  const replacedDynamicRequires = [];
1478
+ const importedVariables = new Set();
1391
1479
 
1392
1480
  walk(ast, {
1393
1481
  enter(node, parent) {
@@ -1443,8 +1531,9 @@ async function transformCommonjs(
1443
1531
  if (hasDefineEsmProperty(node.right)) {
1444
1532
  shouldWrap = true;
1445
1533
  }
1446
- } else if (defaultIsModuleExports === false) {
1534
+ } else if (isRequireExpression(node.right, scope)) {
1447
1535
  shouldWrap = true;
1536
+ reexports = true;
1448
1537
  }
1449
1538
  }
1450
1539
  } else if (exportName === KEY_COMPILED_ESM) {
@@ -1501,6 +1590,11 @@ async function transformCommonjs(
1501
1590
  }
1502
1591
 
1503
1592
  if (!isRequireExpression(node, scope)) {
1593
+ const keypath = getKeypath(node.callee);
1594
+ if (keypath && importedVariables.has(keypath.name)) {
1595
+ // Heuristic to deoptimize requires after a required function has been called
1596
+ currentConditionalNodeEnd = Infinity;
1597
+ }
1504
1598
  return;
1505
1599
  }
1506
1600
 
@@ -1520,15 +1614,28 @@ async function transformCommonjs(
1520
1614
  const requireStringArg = getRequireStringArg(node);
1521
1615
  if (!ignoreRequire(requireStringArg)) {
1522
1616
  const usesReturnValue = parent.type !== 'ExpressionStatement';
1523
- addRequireStatement(
1617
+ const toBeRemoved =
1618
+ parent.type === 'ExpressionStatement' &&
1619
+ (!currentConditionalNodeEnd ||
1620
+ // We should completely remove requires directly in a try-catch
1621
+ // so that Rollup can remove up the try-catch
1622
+ (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd))
1623
+ ? parent
1624
+ : node;
1625
+ addRequireExpression(
1524
1626
  requireStringArg,
1525
1627
  node,
1526
1628
  scope,
1527
1629
  usesReturnValue,
1528
1630
  currentTryBlockEnd !== null,
1529
1631
  currentConditionalNodeEnd !== null,
1530
- parent.type === 'ExpressionStatement' ? parent : node
1632
+ toBeRemoved
1531
1633
  );
1634
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
1635
+ for (const name of extractAssignedNames(parent.id)) {
1636
+ importedVariables.add(name);
1637
+ }
1638
+ }
1532
1639
  }
1533
1640
  return;
1534
1641
  }
@@ -1718,12 +1825,15 @@ async function transformCommonjs(
1718
1825
  shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1719
1826
  const detectWrappedDefault =
1720
1827
  shouldWrap &&
1721
- (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
1828
+ (reexports ||
1829
+ topLevelDefineCompiledEsmExpressions.length > 0 ||
1830
+ code.indexOf('__esModule') >= 0);
1722
1831
 
1723
1832
  if (
1724
1833
  !(
1725
1834
  shouldWrap ||
1726
1835
  isRequired ||
1836
+ needsRequireWrapper ||
1727
1837
  uses.module ||
1728
1838
  uses.exports ||
1729
1839
  uses.require ||
@@ -1741,7 +1851,9 @@ async function transformCommonjs(
1741
1851
  magicString.remove(0, commentEnd).trim();
1742
1852
  }
1743
1853
 
1744
- const exportMode = shouldWrap
1854
+ const exportMode = isEsModule
1855
+ ? 'none'
1856
+ : shouldWrap
1745
1857
  ? uses.module
1746
1858
  ? 'module'
1747
1859
  : 'exports'
@@ -1834,10 +1946,16 @@ function commonjs(options = {}) {
1834
1946
  ignoreGlobal,
1835
1947
  ignoreDynamicRequires,
1836
1948
  requireReturnsDefault: requireReturnsDefaultOption,
1949
+ defaultIsModuleExports: defaultIsModuleExportsOption,
1837
1950
  esmExternals
1838
1951
  } = options;
1839
1952
  const extensions = options.extensions || ['.js'];
1840
1953
  const filter = createFilter(options.include, options.exclude);
1954
+ const isPossibleCjsId = (id) => {
1955
+ const extName = extname(id);
1956
+ return extName === '.cjs' || (extensions.includes(extName) && filter(id));
1957
+ };
1958
+
1841
1959
  const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
1842
1960
 
1843
1961
  const getRequireReturnsDefault =
@@ -1853,8 +1971,11 @@ function commonjs(options = {}) {
1853
1971
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1854
1972
  : () => esmExternals;
1855
1973
 
1856
- const defaultIsModuleExports =
1857
- typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1974
+ const getDefaultIsModuleExports =
1975
+ typeof defaultIsModuleExportsOption === 'function'
1976
+ ? defaultIsModuleExportsOption
1977
+ : () =>
1978
+ typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto';
1858
1979
 
1859
1980
  const dynamicRequireRoot =
1860
1981
  typeof options.dynamicRequireRoot === 'string'
@@ -1889,7 +2010,7 @@ function commonjs(options = {}) {
1889
2010
  };
1890
2011
  };
1891
2012
 
1892
- const resolveId = getResolveId(extensions);
2013
+ const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId);
1893
2014
 
1894
2015
  const sourceMap = options.sourceMap !== false;
1895
2016
 
@@ -1954,7 +2075,7 @@ function commonjs(options = {}) {
1954
2075
  dynamicRequireModules,
1955
2076
  commonDir,
1956
2077
  ast,
1957
- defaultIsModuleExports,
2078
+ getDefaultIsModuleExports(id),
1958
2079
  needsRequireWrapper,
1959
2080
  requireResolver.resolveRequireSourcesAndUpdateMeta(this),
1960
2081
  requireResolver.isRequiredId(id),
@@ -1994,7 +2115,11 @@ function commonjs(options = {}) {
1994
2115
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1995
2116
  );
1996
2117
  }
1997
- requireResolver = getRequireResolver(extensions, detectCyclesAndConditional);
2118
+ requireResolver = getRequireResolver(
2119
+ extensions,
2120
+ detectCyclesAndConditional,
2121
+ currentlyResolving
2122
+ );
1998
2123
  },
1999
2124
 
2000
2125
  buildEnd() {
@@ -2050,11 +2175,13 @@ function commonjs(options = {}) {
2050
2175
 
2051
2176
  // entry suffix is just appended to not mess up relative external resolution
2052
2177
  if (id.endsWith(ENTRY_SUFFIX)) {
2053
- return getEntryProxy(id.slice(0, -ENTRY_SUFFIX.length), defaultIsModuleExports, this.load);
2178
+ const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
2179
+ return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo);
2054
2180
  }
2055
2181
 
2056
2182
  if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
2057
- return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
2183
+ const actualId = unwrapId(id, ES_IMPORT_SUFFIX);
2184
+ return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId));
2058
2185
  }
2059
2186
 
2060
2187
  if (id === DYNAMIC_MODULES_ID) {
@@ -2079,10 +2206,7 @@ function commonjs(options = {}) {
2079
2206
  },
2080
2207
 
2081
2208
  transform(code, id) {
2082
- const extName = extname(id);
2083
- if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {
2084
- return null;
2085
- }
2209
+ if (!isPossibleCjsId(id)) return null;
2086
2210
 
2087
2211
  try {
2088
2212
  return transformAndCheckExports.call(this, code, id);