@rollup/plugin-commonjs 22.0.0-0 → 22.0.0-4

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/README.md CHANGED
@@ -51,9 +51,9 @@ When used together with the node-resolve plugin
51
51
  Type: `"auto" | boolean | "debug" | string[]`<br>
52
52
  Default: `"auto"`
53
53
 
54
- By default, this plugin will try to hoist `require` statements as imports to the top of each file. While this works well for many code bases and allows for very efficient ESM output, it does not perfectly capture CommonJS semantics as the order of side effects like log statements may change. But it is especially problematic when there are circular `require` calls between CommonJS modules as those often rely on the lazy execution of nested `require` calls.
54
+ By default, this plugin will try to hoist `require` statements as imports to the top of each file. While this works well for many code bases and allows for very efficient ESM output, it does not perfectly capture CommonJS semantics as the initialisation order of required modules will be different. The resultant side effects can include log statements being emitted in a different order, and some code that is dependent on the initialisation order of polyfills in require statements may not work. But it is especially problematic when there are circular `require` calls between CommonJS modules as those often rely on the lazy execution of nested `require` calls.
55
55
 
56
- Setting this option to `true` will wrap all CommonJS files in functions which are executed when they are required for the first time, preserving NodeJS semantics. Note that this can have an impact on the size and performance of the generated code.
56
+ Setting this option to `true` will wrap all CommonJS files in functions which are executed when they are required for the first time, preserving NodeJS semantics. This is the safest setting and should be used if the generated code does not work correctly with `"auto"`. Note that `strictRequires: true` can have a small impact on the size and performance of generated code, but less so if the code is minified.
57
57
 
58
58
  The default value of `"auto"` will only wrap CommonJS files when they are part of a CommonJS dependency cycle, e.g. an index file that is required by some of its dependencies, or if they are only required in a potentially "conditional" way like from within an if-statement or a function. All other CommonJS files are hoisted. This is the recommended setting for most code bases. Note that the detection of conditional requires can be subject to race conditions if there are both conditional and unconditional requires of the same file, which in edge cases may result in inconsistencies between builds. If you think this is a problem for you, you can avoid this by using any value other than `"auto"` or `"debug"`.
59
59
 
package/dist/index.es.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-0";
10
+ var version = "22.0.0-4";
11
11
  var peerDependencies = {
12
- rollup: "^2.60.0"
12
+ rollup: "^2.61.1"
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;
@@ -478,6 +481,14 @@ function resolveExtensions(importee, importer, extensions) {
478
481
 
479
482
  function getResolveId(extensions) {
480
483
  return async function resolveId(importee, importer, resolveOptions) {
484
+ // We assume that all requires are pre-resolved
485
+ if (
486
+ resolveOptions.custom &&
487
+ resolveOptions.custom['node-resolve'] &&
488
+ resolveOptions.custom['node-resolve'].isRequire
489
+ ) {
490
+ return null;
491
+ }
481
492
  if (isWrappedId(importee, WRAPPED_SUFFIX)) {
482
493
  return unwrapId(importee, WRAPPED_SUFFIX);
483
494
  }
@@ -497,7 +508,7 @@ function getResolveId(extensions) {
497
508
  if (importer) {
498
509
  if (
499
510
  importer === DYNAMIC_MODULES_ID ||
500
- // Except for exports, proxies are only importing resolved ids, no need to resolve again
511
+ // Proxies are only importing resolved ids, no need to resolve again
501
512
  isWrappedId(importer, PROXY_SUFFIX) ||
502
513
  isWrappedId(importer, ES_IMPORT_SUFFIX)
503
514
  ) {
@@ -546,9 +557,39 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
546
557
  const knownCjsModuleTypes = Object.create(null);
547
558
  const requiredIds = Object.create(null);
548
559
  const unconditionallyRequiredIds = Object.create(null);
549
- const dependentModules = Object.create(null);
550
- const getDependentModules = (id) =>
551
- dependentModules[id] || (dependentModules[id] = Object.create(null));
560
+ const dependencies = Object.create(null);
561
+ const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
562
+
563
+ const isCyclic = (id) => {
564
+ const dependenciesToCheck = new Set(getDependencies(id));
565
+ for (const dependency of dependenciesToCheck) {
566
+ if (dependency === id) {
567
+ return true;
568
+ }
569
+ for (const childDependency of getDependencies(dependency)) {
570
+ dependenciesToCheck.add(childDependency);
571
+ }
572
+ }
573
+ return false;
574
+ };
575
+
576
+ const fullyAnalyzedModules = Object.create(null);
577
+
578
+ const getTypeForFullyAnalyzedModule = (id) => {
579
+ const knownType = knownCjsModuleTypes[id];
580
+ if (
581
+ knownType === IS_WRAPPED_COMMONJS ||
582
+ !detectCyclesAndConditional ||
583
+ fullyAnalyzedModules[id]
584
+ ) {
585
+ return knownType;
586
+ }
587
+ fullyAnalyzedModules[id] = true;
588
+ if (isCyclic(id)) {
589
+ return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
590
+ }
591
+ return knownType;
592
+ };
552
593
 
553
594
  return {
554
595
  getWrappedIds: () =>
@@ -561,8 +602,9 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
561
602
  isParentCommonJS,
562
603
  sources
563
604
  ) => {
564
- knownCjsModuleTypes[parentId] = knownCjsModuleTypes[parentId] || isParentCommonJS;
605
+ knownCjsModuleTypes[parentId] = isParentCommonJS;
565
606
  if (
607
+ detectCyclesAndConditional &&
566
608
  knownCjsModuleTypes[parentId] &&
567
609
  requiredIds[parentId] &&
568
610
  !unconditionallyRequiredIds[parentId]
@@ -577,9 +619,7 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
577
619
  }
578
620
  const resolved =
579
621
  (await rollupContext.resolve(source, parentId, {
580
- custom: {
581
- 'node-resolve': { isRequire: true }
582
- }
622
+ custom: { 'node-resolve': { isRequire: true } }
583
623
  })) || resolveExtensions(source, parentId, extensions);
584
624
  if (!resolved) {
585
625
  return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
@@ -589,44 +629,25 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
589
629
  return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
590
630
  }
591
631
  requiredIds[childId] = true;
592
- if (
593
- !(
594
- detectCyclesAndConditional &&
595
- (isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)
596
- )
597
- ) {
632
+ if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
598
633
  unconditionallyRequiredIds[childId] = true;
599
634
  }
600
- const parentDependentModules = getDependentModules(parentId);
601
- const childDependentModules = getDependentModules(childId);
602
- childDependentModules[parentId] = true;
603
- for (const dependentId of Object.keys(parentDependentModules)) {
604
- childDependentModules[dependentId] = true;
605
- }
606
- if (parentDependentModules[childId]) {
607
- // If we depend on one of our dependencies, we have a cycle. Then all modules that
608
- // we depend on that also depend on the same module are part of a cycle as well.
609
- if (detectCyclesAndConditional && isParentCommonJS) {
610
- knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
611
- knownCjsModuleTypes[childId] = IS_WRAPPED_COMMONJS;
612
- for (const dependentId of Object.keys(parentDependentModules)) {
613
- if (getDependentModules(dependentId)[childId]) {
614
- knownCjsModuleTypes[dependentId] = IS_WRAPPED_COMMONJS;
615
- }
616
- }
617
- }
618
- } else {
635
+
636
+ getDependencies(parentId).add(childId);
637
+ if (!isCyclic(childId)) {
619
638
  // This makes sure the current transform handler waits for all direct dependencies to be
620
639
  // loaded and transformed and therefore for all transitive CommonJS dependencies to be
621
640
  // loaded as well so that all cycles have been found and knownCjsModuleTypes is reliable.
622
641
  await rollupContext.load(resolved);
642
+ } else if (detectCyclesAndConditional && knownCjsModuleTypes[parentId]) {
643
+ knownCjsModuleTypes[parentId] = IS_WRAPPED_COMMONJS;
623
644
  }
624
645
  return { id: childId, allowProxy: true };
625
646
  })
626
647
  );
627
648
  return {
628
649
  requireTargets: requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
629
- const isCommonJS = knownCjsModuleTypes[dependencyId];
650
+ const isCommonJS = getTypeForFullyAnalyzedModule(dependencyId);
630
651
  return {
631
652
  source: sources[index].source,
632
653
  id: allowProxy
@@ -637,29 +658,39 @@ function getResolveRequireSourcesAndGetMeta(extensions, detectCyclesAndCondition
637
658
  isCommonJS
638
659
  };
639
660
  }),
640
- usesRequireWrapper: knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS
661
+ usesRequireWrapper: getTypeForFullyAnalyzedModule(parentId) === IS_WRAPPED_COMMONJS
641
662
  };
642
663
  }
643
664
  };
644
665
  }
645
666
 
646
- function validateRollupVersion(rollupVersion, peerDependencyVersion) {
647
- const [major, minor] = rollupVersion.split('.').map(Number);
648
- const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
667
+ function validateVersion(actualVersion, peerDependencyVersion, name) {
668
+ const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
649
669
  let minMajor = Infinity;
650
670
  let minMinor = Infinity;
671
+ let minPatch = Infinity;
651
672
  let foundVersion;
652
673
  // eslint-disable-next-line no-cond-assign
653
674
  while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
654
- const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
675
+ const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
655
676
  if (foundMajor < minMajor) {
656
677
  minMajor = foundMajor;
657
678
  minMinor = foundMinor;
679
+ minPatch = foundPatch;
658
680
  }
659
681
  }
660
- if (major < minMajor || (major === minMajor && minor < minMinor)) {
682
+ if (!actualVersion) {
661
683
  throw new Error(
662
- `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
684
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
685
+ );
686
+ }
687
+ const [major, minor, patch] = actualVersion.split('.').map(Number);
688
+ if (
689
+ major < minMajor ||
690
+ (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
691
+ ) {
692
+ throw new Error(
693
+ `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
663
694
  );
664
695
  }
665
696
  }
@@ -1105,14 +1136,16 @@ function getRequireHandlers() {
1105
1136
  resolveRequireSourcesAndGetMeta,
1106
1137
  needsRequireWrapper,
1107
1138
  isEsModule,
1108
- usesRequire,
1139
+ isDynamicRequireModulesEnabled,
1109
1140
  getIgnoreTryCatchRequireStatementMode
1110
1141
  ) {
1111
1142
  const imports = [];
1112
1143
  imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
1113
- if (usesRequire) {
1144
+ if (dynamicRequireName) {
1114
1145
  imports.push(
1115
- `import { commonjsRequire as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1146
+ `import { ${
1147
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1148
+ } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";`
1116
1149
  );
1117
1150
  }
1118
1151
  if (exportMode === 'module') {
@@ -1398,15 +1431,9 @@ async function transformCommonjs(
1398
1431
  isRequire(node.callee.object, scope) &&
1399
1432
  node.callee.property.name === 'resolve'
1400
1433
  ) {
1401
- checkDynamicRequire();
1434
+ checkDynamicRequire(node.start);
1402
1435
  uses.require = true;
1403
1436
  const requireNode = node.callee.object;
1404
- magicString.appendLeft(
1405
- node.end - 1,
1406
- `,${JSON.stringify(
1407
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1408
- )}`
1409
- );
1410
1437
  replacedDynamicRequires.push(requireNode);
1411
1438
  return;
1412
1439
  }
@@ -1420,15 +1447,9 @@ async function transformCommonjs(
1420
1447
 
1421
1448
  if (hasDynamicArguments(node)) {
1422
1449
  if (isDynamicRequireModulesEnabled) {
1423
- magicString.appendLeft(
1424
- node.end - 1,
1425
- `, ${JSON.stringify(
1426
- dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
1427
- )}`
1428
- );
1450
+ checkDynamicRequire(node.start);
1429
1451
  }
1430
1452
  if (!ignoreDynamicRequires) {
1431
- checkDynamicRequire();
1432
1453
  replacedDynamicRequires.push(node.callee);
1433
1454
  }
1434
1455
  return;
@@ -1486,7 +1507,6 @@ async function transformCommonjs(
1486
1507
  return;
1487
1508
  }
1488
1509
  if (!ignoreDynamicRequires) {
1489
- checkDynamicRequire();
1490
1510
  if (isShorthandProperty(parent)) {
1491
1511
  magicString.prependRight(node.start, 'require: ');
1492
1512
  }
@@ -1570,9 +1590,10 @@ async function transformCommonjs(
1570
1590
  if (scope.contains(flattened.name)) return;
1571
1591
 
1572
1592
  if (
1573
- flattened.keypath === 'module.exports' ||
1574
- flattened.keypath === 'module' ||
1575
- flattened.keypath === 'exports'
1593
+ !isEsModule &&
1594
+ (flattened.keypath === 'module.exports' ||
1595
+ flattened.keypath === 'module' ||
1596
+ flattened.keypath === 'exports')
1576
1597
  ) {
1577
1598
  magicString.overwrite(node.start, node.end, `'object'`, {
1578
1599
  storeName: false
@@ -1600,7 +1621,13 @@ async function transformCommonjs(
1600
1621
  const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
1601
1622
  const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
1602
1623
  const helpersName = deconflict([scope], globals, 'commonjsHelpers');
1603
- const dynamicRequireName = deconflict([scope], globals, 'commonjsRequire');
1624
+ const dynamicRequireName =
1625
+ replacedDynamicRequires.length > 0 &&
1626
+ deconflict(
1627
+ [scope],
1628
+ globals,
1629
+ isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
1630
+ );
1604
1631
  const deconflictedExportNames = Object.create(null);
1605
1632
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
1606
1633
  deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
@@ -1612,10 +1639,17 @@ async function transformCommonjs(
1612
1639
  });
1613
1640
  }
1614
1641
  for (const node of replacedDynamicRequires) {
1615
- magicString.overwrite(node.start, node.end, dynamicRequireName, {
1616
- contentOnly: true,
1617
- storeName: true
1618
- });
1642
+ magicString.overwrite(
1643
+ node.start,
1644
+ node.end,
1645
+ isDynamicRequireModulesEnabled
1646
+ ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
1647
+ : dynamicRequireName,
1648
+ {
1649
+ contentOnly: true,
1650
+ storeName: true
1651
+ }
1652
+ );
1619
1653
  }
1620
1654
 
1621
1655
  // We cannot wrap ES/mixed modules
@@ -1670,7 +1704,7 @@ async function transformCommonjs(
1670
1704
  resolveRequireSourcesAndGetMeta,
1671
1705
  needsRequireWrapper,
1672
1706
  isEsModule,
1673
- uses.require,
1707
+ isDynamicRequireModulesEnabled,
1674
1708
  getIgnoreTryCatchRequireStatementMode
1675
1709
  );
1676
1710
  const exportBlock = isEsModule
@@ -1831,16 +1865,19 @@ function commonjs(options = {}) {
1831
1865
  !isEsModule &&
1832
1866
  (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id));
1833
1867
 
1834
- const checkDynamicRequire = () => {
1868
+ const checkDynamicRequire = (position) => {
1835
1869
  if (id.indexOf(dynamicRequireRoot) !== 0) {
1836
- this.error({
1837
- code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1838
- id,
1839
- dynamicRequireRoot,
1840
- message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(
1841
- id
1842
- )}" or one of its parent directories.`
1843
- });
1870
+ this.error(
1871
+ {
1872
+ code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
1873
+ id,
1874
+ dynamicRequireRoot,
1875
+ message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname(
1876
+ id
1877
+ )}" or one of its parent directories.`
1878
+ },
1879
+ position
1880
+ );
1844
1881
  }
1845
1882
  };
1846
1883
 
@@ -1886,8 +1923,12 @@ function commonjs(options = {}) {
1886
1923
  return { ...rawOptions, plugins };
1887
1924
  },
1888
1925
 
1889
- buildStart() {
1890
- validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
1926
+ buildStart({ plugins }) {
1927
+ validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
1928
+ const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
1929
+ if (nodeResolve) {
1930
+ validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
1931
+ }
1891
1932
  if (options.namedExports != null) {
1892
1933
  this.warn(
1893
1934
  'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'