@rollup/plugin-commonjs 22.0.0-9 → 22.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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-9";
10
+ var version = "22.0.2";
11
11
  var peerDependencies = {
12
- rollup: "^2.67.0"
12
+ rollup: "^2.68.0"
13
13
  };
14
14
 
15
15
  function tryParse(parse, code, id) {
@@ -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,85 +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
- const customOptions = resolveOptions.custom;
497
- if (customOptions && customOptions['node-resolve'] && customOptions['node-resolve'].isRequire) {
498
- return null;
499
- }
500
- if (isWrappedId(importee, WRAPPED_SUFFIX)) {
501
- return unwrapId(importee, WRAPPED_SUFFIX);
502
- }
492
+ function getResolveId(extensions, isPossibleCjsId) {
493
+ const currentlyResolving = new Map();
503
494
 
504
- if (
505
- importee.endsWith(ENTRY_SUFFIX) ||
506
- isWrappedId(importee, MODULE_SUFFIX) ||
507
- isWrappedId(importee, EXPORTS_SUFFIX) ||
508
- isWrappedId(importee, PROXY_SUFFIX) ||
509
- isWrappedId(importee, ES_IMPORT_SUFFIX) ||
510
- isWrappedId(importee, EXTERNAL_SUFFIX) ||
511
- importee.startsWith(HELPERS_ID) ||
512
- importee === DYNAMIC_MODULES_ID
513
- ) {
514
- return importee;
515
- }
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
+ }
516
527
 
517
- if (importer) {
518
528
  if (
519
- importer === DYNAMIC_MODULES_ID ||
520
- // Proxies are only importing resolved ids, no need to resolve again
521
- isWrappedId(importer, PROXY_SUFFIX) ||
522
- isWrappedId(importer, ES_IMPORT_SUFFIX) ||
523
- 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
524
537
  ) {
525
538
  return importee;
526
539
  }
527
- if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
528
- // We need to return null for unresolved imports so that the proper warning is shown
529
- if (!(await this.resolve(importee, importer, { skipSelf: true }))) {
530
- 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 };
531
564
  }
532
- // For other external imports, we need to make sure they are handled as external
533
- return { id: importee, external: true };
534
565
  }
535
- }
536
566
 
537
- if (importee.startsWith('\0')) {
538
- return null;
539
- }
567
+ if (importee.startsWith('\0')) {
568
+ return null;
569
+ }
540
570
 
541
- // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
542
- // if that is the case, we need to add a proxy.
543
- const resolved =
544
- (await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) ||
545
- resolveExtensions(importee, importer, extensions);
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
- ) {
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
+ }
553
606
  return resolved;
554
607
  }
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
- }
561
- const {
562
- meta: { commonjs: commonjsMeta }
563
- } = moduleInfo;
564
- if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) {
565
- return wrapId(resolved.id, ES_IMPORT_SUFFIX);
566
- }
567
- return resolved;
568
608
  };
569
609
  }
570
610
 
571
- function getRequireResolver(extensions, detectCyclesAndConditional) {
611
+ function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) {
572
612
  const knownCjsModuleTypes = Object.create(null);
573
613
  const requiredIds = Object.create(null);
574
614
  const unconditionallyRequiredIds = Object.create(null);
@@ -588,6 +628,9 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
588
628
  return false;
589
629
  };
590
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.
591
634
  const fullyAnalyzedModules = Object.create(null);
592
635
 
593
636
  const getTypeForFullyAnalyzedModule = (id) => {
@@ -595,7 +638,6 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
595
638
  if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
596
639
  return knownType;
597
640
  }
598
- fullyAnalyzedModules[id] = true;
599
641
  if (isCyclic(id)) {
600
642
  return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
601
643
  }
@@ -603,13 +645,11 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
603
645
  };
604
646
 
605
647
  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;
648
+ // Fully analyzed modules may never change type
649
+ if (fullyAnalyzedModules[id]) {
650
+ return;
651
+ }
652
+ knownCjsModuleTypes[id] = initialCommonJSType;
613
653
  if (
614
654
  detectCyclesAndConditional &&
615
655
  knownCjsModuleTypes[id] === true &&
@@ -620,7 +660,7 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
620
660
  }
621
661
  };
622
662
 
623
- const setTypesForRequiredModules = async (parentId, resolved, isConditional, loadModule) => {
663
+ const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
624
664
  const childId = resolved.id;
625
665
  requiredIds[childId] = true;
626
666
  if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
@@ -629,41 +669,85 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
629
669
 
630
670
  getDependencies(parentId).add(childId);
631
671
  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.
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.
635
676
  await loadModule(resolved);
636
677
  }
637
678
  };
638
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
+
639
691
  return {
640
692
  getWrappedIds: () =>
641
693
  Object.keys(knownCjsModuleTypes).filter(
642
694
  (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
643
695
  ),
644
696
  isRequiredId: (id) => requiredIds[id],
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]) {
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) {
663
714
  return true;
664
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
+ }
665
731
  }
666
- 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);
667
751
  },
668
752
  /* eslint-disable no-param-reassign */
669
753
  resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (
@@ -676,16 +760,20 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
676
760
  parentMeta.requires = [];
677
761
  parentMeta.isRequiredCommonJS = Object.create(null);
678
762
  setInitialParentType(parentId, isParentCommonJS);
763
+ const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set();
764
+ currentlyResolving.set(parentId, currentlyResolvingForParent);
679
765
  const requireTargets = await Promise.all(
680
766
  sources.map(async ({ source, isConditional }) => {
681
767
  // Never analyze or proxy internal modules
682
768
  if (source.startsWith('\0')) {
683
769
  return { id: source, allowProxy: false };
684
770
  }
771
+ currentlyResolvingForParent.add(source);
685
772
  const resolved =
686
773
  (await rollupContext.resolve(source, parentId, {
687
774
  custom: { 'node-resolve': { isRequire: true } }
688
775
  })) || resolveExtensions(source, parentId, extensions);
776
+ currentlyResolvingForParent.delete(source);
689
777
  if (!resolved) {
690
778
  return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
691
779
  }
@@ -694,16 +782,18 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
694
782
  return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
695
783
  }
696
784
  parentMeta.requires.push({ resolved, isConditional });
697
- await setTypesForRequiredModules(parentId, resolved, isConditional, rollupContext.load);
785
+ await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
698
786
  return { id: childId, allowProxy: true };
699
787
  })
700
788
  );
701
789
  parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
790
+ fullyAnalyzedModules[parentId] = true;
702
791
  return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
703
792
  // eslint-disable-next-line no-multi-assign
704
793
  const isCommonJS = (parentMeta.isRequiredCommonJS[
705
794
  dependencyId
706
795
  ] = getTypeForFullyAnalyzedModule(dependencyId));
796
+ fullyAnalyzedModules[dependencyId] = true;
707
797
  return {
708
798
  source: sources[index].source,
709
799
  id: allowProxy
@@ -714,6 +804,10 @@ function getRequireResolver(extensions, detectCyclesAndConditional) {
714
804
  isCommonJS
715
805
  };
716
806
  });
807
+ },
808
+ isCurrentlyResolving(source, parentId) {
809
+ const currentlyResolvingForParent = currentlyResolving.get(parentId);
810
+ return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
717
811
  }
718
812
  };
719
813
  }
@@ -871,7 +965,7 @@ function hasDefineEsmProperty(node) {
871
965
  });
872
966
  }
873
967
 
874
- function wrapCode(magicString, uses, moduleName, exportsName) {
968
+ function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
875
969
  const args = [];
876
970
  const passedArgs = [];
877
971
  if (uses.module) {
@@ -884,7 +978,7 @@ function wrapCode(magicString, uses, moduleName, exportsName) {
884
978
  }
885
979
  magicString
886
980
  .trim()
887
- .indent('\t')
981
+ .indent('\t', { exclude: indentExclusionRanges })
888
982
  .prepend(`(function (${args.join(', ')}) {\n`)
889
983
  .append(`\n} (${passedArgs.join(', ')}));`);
890
984
  }
@@ -1157,7 +1251,7 @@ function getRequireStringArg(node) {
1157
1251
  function getRequireHandlers() {
1158
1252
  const requireExpressions = [];
1159
1253
 
1160
- function addRequireStatement(
1254
+ function addRequireExpression(
1161
1255
  sourceId,
1162
1256
  node,
1163
1257
  scope,
@@ -1237,7 +1331,7 @@ function getRequireHandlers() {
1237
1331
  }
1238
1332
 
1239
1333
  return {
1240
- addRequireStatement,
1334
+ addRequireExpression,
1241
1335
  rewriteRequireExpressionsAndGetImportBlock
1242
1336
  };
1243
1337
  }
@@ -1356,6 +1450,7 @@ async function transformCommonjs(
1356
1450
  let programDepth = 0;
1357
1451
  let currentTryBlockEnd = null;
1358
1452
  let shouldWrap = false;
1453
+ let reexports = false;
1359
1454
 
1360
1455
  const globals = new Set();
1361
1456
  // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
@@ -1363,7 +1458,7 @@ async function transformCommonjs(
1363
1458
  // unconditional require elsewhere.
1364
1459
  let currentConditionalNodeEnd = null;
1365
1460
  const conditionalNodes = new Set();
1366
- const { addRequireStatement, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1461
+ const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
1367
1462
 
1368
1463
  // See which names are assigned to. This is necessary to prevent
1369
1464
  // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
@@ -1380,6 +1475,8 @@ async function transformCommonjs(
1380
1475
  const topLevelDefineCompiledEsmExpressions = [];
1381
1476
  const replacedGlobal = [];
1382
1477
  const replacedDynamicRequires = [];
1478
+ const importedVariables = new Set();
1479
+ const indentExclusionRanges = [];
1383
1480
 
1384
1481
  walk(ast, {
1385
1482
  enter(node, parent) {
@@ -1435,8 +1532,9 @@ async function transformCommonjs(
1435
1532
  if (hasDefineEsmProperty(node.right)) {
1436
1533
  shouldWrap = true;
1437
1534
  }
1438
- } else if (defaultIsModuleExports === false) {
1535
+ } else if (isRequireExpression(node.right, scope)) {
1439
1536
  shouldWrap = true;
1537
+ reexports = true;
1440
1538
  }
1441
1539
  }
1442
1540
  } else if (exportName === KEY_COMPILED_ESM) {
@@ -1493,6 +1591,11 @@ async function transformCommonjs(
1493
1591
  }
1494
1592
 
1495
1593
  if (!isRequireExpression(node, scope)) {
1594
+ const keypath = getKeypath(node.callee);
1595
+ if (keypath && importedVariables.has(keypath.name)) {
1596
+ // Heuristic to deoptimize requires after a required function has been called
1597
+ currentConditionalNodeEnd = Infinity;
1598
+ }
1496
1599
  return;
1497
1600
  }
1498
1601
 
@@ -1512,15 +1615,28 @@ async function transformCommonjs(
1512
1615
  const requireStringArg = getRequireStringArg(node);
1513
1616
  if (!ignoreRequire(requireStringArg)) {
1514
1617
  const usesReturnValue = parent.type !== 'ExpressionStatement';
1515
- addRequireStatement(
1618
+ const toBeRemoved =
1619
+ parent.type === 'ExpressionStatement' &&
1620
+ (!currentConditionalNodeEnd ||
1621
+ // We should completely remove requires directly in a try-catch
1622
+ // so that Rollup can remove up the try-catch
1623
+ (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd))
1624
+ ? parent
1625
+ : node;
1626
+ addRequireExpression(
1516
1627
  requireStringArg,
1517
1628
  node,
1518
1629
  scope,
1519
1630
  usesReturnValue,
1520
1631
  currentTryBlockEnd !== null,
1521
1632
  currentConditionalNodeEnd !== null,
1522
- parent.type === 'ExpressionStatement' ? parent : node
1633
+ toBeRemoved
1523
1634
  );
1635
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
1636
+ for (const name of extractAssignedNames(parent.id)) {
1637
+ importedVariables.add(name);
1638
+ }
1639
+ }
1524
1640
  }
1525
1641
  return;
1526
1642
  }
@@ -1659,6 +1775,11 @@ async function transformCommonjs(
1659
1775
  if (!scope.parent) {
1660
1776
  topLevelDeclarations.push(node);
1661
1777
  }
1778
+ return;
1779
+ case 'TemplateElement':
1780
+ if (node.value.raw.includes('\n')) {
1781
+ indentExclusionRanges.push([node.start, node.end]);
1782
+ }
1662
1783
  }
1663
1784
  },
1664
1785
 
@@ -1710,12 +1831,15 @@ async function transformCommonjs(
1710
1831
  shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
1711
1832
  const detectWrappedDefault =
1712
1833
  shouldWrap &&
1713
- (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
1834
+ (reexports ||
1835
+ topLevelDefineCompiledEsmExpressions.length > 0 ||
1836
+ code.indexOf('__esModule') >= 0);
1714
1837
 
1715
1838
  if (
1716
1839
  !(
1717
1840
  shouldWrap ||
1718
1841
  isRequired ||
1842
+ needsRequireWrapper ||
1719
1843
  uses.module ||
1720
1844
  uses.exports ||
1721
1845
  uses.require ||
@@ -1733,7 +1857,9 @@ async function transformCommonjs(
1733
1857
  magicString.remove(0, commentEnd).trim();
1734
1858
  }
1735
1859
 
1736
- const exportMode = shouldWrap
1860
+ const exportMode = isEsModule
1861
+ ? 'none'
1862
+ : shouldWrap
1737
1863
  ? uses.module
1738
1864
  ? 'module'
1739
1865
  : 'exports'
@@ -1786,11 +1912,13 @@ async function transformCommonjs(
1786
1912
  );
1787
1913
 
1788
1914
  if (shouldWrap) {
1789
- wrapCode(magicString, uses, moduleName, exportsName);
1915
+ wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
1790
1916
  }
1791
1917
 
1792
1918
  if (usesRequireWrapper) {
1793
- magicString.trim().indent('\t');
1919
+ magicString.trim().indent('\t', {
1920
+ exclude: indentExclusionRanges
1921
+ });
1794
1922
  magicString.prepend(
1795
1923
  `var ${isRequiredName};
1796
1924
 
@@ -1826,10 +1954,16 @@ function commonjs(options = {}) {
1826
1954
  ignoreGlobal,
1827
1955
  ignoreDynamicRequires,
1828
1956
  requireReturnsDefault: requireReturnsDefaultOption,
1957
+ defaultIsModuleExports: defaultIsModuleExportsOption,
1829
1958
  esmExternals
1830
1959
  } = options;
1831
1960
  const extensions = options.extensions || ['.js'];
1832
1961
  const filter = createFilter(options.include, options.exclude);
1962
+ const isPossibleCjsId = (id) => {
1963
+ const extName = extname(id);
1964
+ return extName === '.cjs' || (extensions.includes(extName) && filter(id));
1965
+ };
1966
+
1833
1967
  const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
1834
1968
 
1835
1969
  const getRequireReturnsDefault =
@@ -1845,8 +1979,11 @@ function commonjs(options = {}) {
1845
1979
  ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
1846
1980
  : () => esmExternals;
1847
1981
 
1848
- const defaultIsModuleExports =
1849
- typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
1982
+ const getDefaultIsModuleExports =
1983
+ typeof defaultIsModuleExportsOption === 'function'
1984
+ ? defaultIsModuleExportsOption
1985
+ : () =>
1986
+ typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto';
1850
1987
 
1851
1988
  const dynamicRequireRoot =
1852
1989
  typeof options.dynamicRequireRoot === 'string'
@@ -1881,7 +2018,7 @@ function commonjs(options = {}) {
1881
2018
  };
1882
2019
  };
1883
2020
 
1884
- const resolveId = getResolveId(extensions);
2021
+ const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId);
1885
2022
 
1886
2023
  const sourceMap = options.sourceMap !== false;
1887
2024
 
@@ -1946,7 +2083,7 @@ function commonjs(options = {}) {
1946
2083
  dynamicRequireModules,
1947
2084
  commonDir,
1948
2085
  ast,
1949
- defaultIsModuleExports,
2086
+ getDefaultIsModuleExports(id),
1950
2087
  needsRequireWrapper,
1951
2088
  requireResolver.resolveRequireSourcesAndUpdateMeta(this),
1952
2089
  requireResolver.isRequiredId(id),
@@ -1986,7 +2123,11 @@ function commonjs(options = {}) {
1986
2123
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
1987
2124
  );
1988
2125
  }
1989
- requireResolver = getRequireResolver(extensions, detectCyclesAndConditional);
2126
+ requireResolver = getRequireResolver(
2127
+ extensions,
2128
+ detectCyclesAndConditional,
2129
+ currentlyResolving
2130
+ );
1990
2131
  },
1991
2132
 
1992
2133
  buildEnd() {
@@ -2042,15 +2183,13 @@ function commonjs(options = {}) {
2042
2183
 
2043
2184
  // entry suffix is just appended to not mess up relative external resolution
2044
2185
  if (id.endsWith(ENTRY_SUFFIX)) {
2045
- return getEntryProxy(
2046
- id.slice(0, -ENTRY_SUFFIX.length),
2047
- defaultIsModuleExports,
2048
- this.getModuleInfo
2049
- );
2186
+ const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
2187
+ return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo);
2050
2188
  }
2051
2189
 
2052
2190
  if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
2053
- return getEsImportProxy(unwrapId(id, ES_IMPORT_SUFFIX), defaultIsModuleExports);
2191
+ const actualId = unwrapId(id, ES_IMPORT_SUFFIX);
2192
+ return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId));
2054
2193
  }
2055
2194
 
2056
2195
  if (id === DYNAMIC_MODULES_ID) {
@@ -2075,10 +2214,7 @@ function commonjs(options = {}) {
2075
2214
  },
2076
2215
 
2077
2216
  transform(code, id) {
2078
- const extName = extname(id);
2079
- if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) {
2080
- return null;
2081
- }
2217
+ if (!isPossibleCjsId(id)) return null;
2082
2218
 
2083
2219
  try {
2084
2220
  return transformAndCheckExports.call(this, code, id);