@rollup/plugin-commonjs 15.1.0 → 16.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,28 +1,33 @@
1
1
  'use strict';
2
2
 
3
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
-
5
3
  var path = require('path');
6
4
  var pluginutils = require('@rollup/pluginutils');
7
- var getCommonDir = _interopDefault(require('commondir'));
5
+ var getCommonDir = require('commondir');
8
6
  var fs = require('fs');
9
7
  var estreeWalker = require('estree-walker');
10
- var MagicString = _interopDefault(require('magic-string'));
8
+ var MagicString = require('magic-string');
11
9
  var resolve = require('resolve');
12
- var isReference = _interopDefault(require('is-reference'));
13
- var glob = _interopDefault(require('glob'));
10
+ var isReference = require('is-reference');
11
+ var glob = require('glob');
12
+
13
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
+
15
+ var getCommonDir__default = /*#__PURE__*/_interopDefaultLegacy(getCommonDir);
16
+ var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
17
+ var isReference__default = /*#__PURE__*/_interopDefaultLegacy(isReference);
18
+ var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
14
19
 
15
20
  var peerDependencies = {
16
- rollup: "^2.22.0"
21
+ rollup: "^2.30.0"
17
22
  };
18
23
 
19
- const PROXY_SUFFIX = '?commonjs-proxy';
20
- const getProxyId = (id) => `\0${id}${PROXY_SUFFIX}`;
21
- const getIdFromProxyId = (proxyId) => proxyId.slice(1, -PROXY_SUFFIX.length);
24
+ const isWrappedId = (id, suffix) => id.endsWith(suffix);
25
+ const wrapId = (id, suffix) => `\0${id}${suffix}`;
26
+ const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
22
27
 
28
+ const PROXY_SUFFIX = '?commonjs-proxy';
29
+ const REQUIRE_SUFFIX = '?commonjs-require';
23
30
  const EXTERNAL_SUFFIX = '?commonjs-external';
24
- const getExternalProxyId = (id) => `\0${id}${EXTERNAL_SUFFIX}`;
25
- const getIdFromExternalProxyId = (proxyId) => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
26
31
 
27
32
  const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
28
33
  const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
@@ -418,17 +423,19 @@ function transformCommonjs(
418
423
  sourceMap,
419
424
  isDynamicRequireModulesEnabled,
420
425
  dynamicRequireModuleSet,
426
+ disableWrap,
421
427
  commonDir,
422
428
  astCache
423
429
  ) {
424
430
  const ast = astCache || tryParse(parse, code, id);
425
431
 
426
- const magicString = new MagicString(code);
432
+ const magicString = new MagicString__default['default'](code);
427
433
 
428
434
  const required = {};
429
435
  // Because objects have no guaranteed ordering, yet we need it,
430
436
  // we need to keep track of the order in a array
431
- const sources = [];
437
+ const requiredSources = [];
438
+ const dynamicRegisterSources = [];
432
439
 
433
440
  let uid = 0;
434
441
 
@@ -519,8 +526,7 @@ function transformCommonjs(
519
526
  }
520
527
 
521
528
  const existing = required[sourceId];
522
- // eslint-disable-next-line no-undefined
523
- if (existing === undefined) {
529
+ if (!existing) {
524
530
  const isDynamic = hasDynamicModuleForPath(sourceId);
525
531
 
526
532
  if (!name) {
@@ -530,12 +536,15 @@ function transformCommonjs(
530
536
  } while (scope.contains(name));
531
537
  }
532
538
 
533
- if (isDynamicRegister && sourceId.endsWith('.json')) {
534
- sourceId = DYNAMIC_JSON_PREFIX + sourceId;
539
+ if (isDynamicRegister) {
540
+ if (sourceId.endsWith('.json')) {
541
+ sourceId = DYNAMIC_JSON_PREFIX + sourceId;
542
+ }
543
+ dynamicRegisterSources.push(sourceId);
535
544
  }
536
545
 
537
- if (isDynamicRegister || !isDynamic || sourceId.endsWith('.json')) {
538
- sources.push([sourceId, !isDynamicRegister]);
546
+ if (!isDynamic || sourceId.endsWith('.json')) {
547
+ requiredSources.push(sourceId);
539
548
  }
540
549
 
541
550
  required[sourceId] = { source: sourceId, name, importsDefault: false, isDynamic };
@@ -545,7 +554,7 @@ function transformCommonjs(
545
554
  }
546
555
 
547
556
  function hasDynamicModuleForPath(source) {
548
- if (!/[/\\]/.test(source)) {
557
+ if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
549
558
  try {
550
559
  const resolvedPath = normalizePathSlashes(
551
560
  resolve.sync(source, { basedir: path.dirname(id) })
@@ -659,7 +668,7 @@ function transformCommonjs(
659
668
  // rewrite `require` (if not already handled) `global` and `define`, and handle free references to
660
669
  // `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
661
670
  if (node.type === 'Identifier') {
662
- if (isReference(node, parent) && !scope.contains(node.name)) {
671
+ if (isReference__default['default'](node, parent) && !scope.contains(node.name)) {
663
672
  if (node.name in uses) {
664
673
  if (isRequireIdentifier(node)) {
665
674
  if (isNodeRequireStatement(parent)) {
@@ -836,42 +845,45 @@ function transformCommonjs(
836
845
  }
837
846
  });
838
847
 
848
+ // If `isEsModule` is on, it means it has ES6 import/export statements,
849
+ // which just can't be wrapped in a function.
850
+ shouldWrap = shouldWrap && !disableWrap && !isEsModule;
851
+
852
+ usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
853
+
839
854
  if (
840
- !sources.length &&
855
+ !requiredSources.length &&
856
+ !dynamicRegisterSources.length &&
841
857
  !uses.module &&
842
858
  !uses.exports &&
843
859
  !uses.require &&
860
+ !usesCommonjsHelpers &&
844
861
  (ignoreGlobal || !uses.global)
845
862
  ) {
846
- // not a CommonJS module
847
- return null;
863
+ return { meta: { commonjs: { isCommonJS: false } } };
848
864
  }
849
865
 
850
- // If `isEsModule` is on, it means it has ES6 import/export statements,
851
- // which just can't be wrapped in a function.
852
- if (isEsModule) shouldWrap = false;
853
-
854
- usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
855
-
856
866
  const importBlock = `${(usesCommonjsHelpers
857
867
  ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`]
858
868
  : []
859
869
  )
860
870
  .concat(
861
- sources.map(
862
- ([source]) =>
863
- // import the actual module before the proxy, so that we know
864
- // what kind of proxy to build
865
- `import '${source}';`
866
- ),
867
- sources
868
- .filter(([, importProxy]) => importProxy)
869
- .map(([source]) => {
870
- const { name, importsDefault } = required[source];
871
- return `import ${importsDefault ? `${name} from ` : ``}'${
872
- source.startsWith('\0') ? source : getProxyId(source)
873
- }';`;
874
- })
871
+ // dynamic registers first, as the may be required in the other modules
872
+ dynamicRegisterSources.map((source) => `import '${source}';`),
873
+
874
+ // now the actual modules so that they are analyzed before creating the proxies;
875
+ // no need to do this for virtual modules as we never proxy them
876
+ requiredSources
877
+ .filter((source) => !source.startsWith('\0'))
878
+ .map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
879
+
880
+ // now the proxy modules
881
+ requiredSources.map((source) => {
882
+ const { name, importsDefault } = required[source];
883
+ return `import ${importsDefault ? `${name} from ` : ``}'${
884
+ source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
885
+ }';`;
886
+ })
875
887
  )
876
888
  .join('\n')}\n\n`;
877
889
 
@@ -982,7 +994,12 @@ function transformCommonjs(
982
994
  code = magicString.toString();
983
995
  const map = sourceMap ? magicString.generateMap() : null;
984
996
 
985
- return { code, map, syntheticNamedExports: isEsModule ? false : '__moduleExports' };
997
+ return {
998
+ code,
999
+ map,
1000
+ syntheticNamedExports: isEsModule ? false : '__moduleExports',
1001
+ meta: { commonjs: { isCommonJS: !isEsModule } }
1002
+ };
986
1003
  }
987
1004
 
988
1005
  function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
@@ -1010,28 +1027,24 @@ function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
1010
1027
  }
1011
1028
 
1012
1029
  function getDynamicPackagesEntryIntro(
1013
- id,
1014
1030
  dynamicRequireModuleDirPaths,
1015
1031
  dynamicRequireModuleSet
1016
1032
  ) {
1017
- try {
1018
- const code = fs.readFileSync(id, { encoding: 'utf8' });
1019
- let dynamicImports = Array.from(
1020
- dynamicRequireModuleSet,
1021
- (dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
1022
- ).join('\n');
1023
-
1024
- if (dynamicRequireModuleDirPaths.length) {
1025
- dynamicImports += `require(${JSON.stringify(
1026
- DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID
1027
- )});`;
1028
- }
1033
+ let dynamicImports = Array.from(
1034
+ dynamicRequireModuleSet,
1035
+ (dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
1036
+ ).join('\n');
1029
1037
 
1030
- return `${dynamicImports}\n${code}`;
1031
- } catch (ex) {
1032
- this.warn(`Failed to read file ${id}, dynamic modules might not work correctly`);
1033
- return null;
1038
+ if (dynamicRequireModuleDirPaths.length) {
1039
+ dynamicImports += `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID)});`;
1034
1040
  }
1041
+
1042
+ return dynamicImports;
1043
+ }
1044
+
1045
+ function isModuleRegistrationProxy(id, dynamicRequireModuleSet) {
1046
+ const normalizedPath = normalizePathSlashes(id);
1047
+ return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
1035
1048
  }
1036
1049
 
1037
1050
  function getDynamicRequirePaths(patterns) {
@@ -1039,7 +1052,7 @@ function getDynamicRequirePaths(patterns) {
1039
1052
  for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
1040
1053
  const isNegated = pattern.startsWith('!');
1041
1054
  const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
1042
- for (const path$1 of glob.sync(isNegated ? pattern.substr(1) : pattern)) {
1055
+ for (const path$1 of glob__default['default'].sync(isNegated ? pattern.substr(1) : pattern)) {
1043
1056
  modifySet(normalizePathSlashes(path.resolve(path$1)));
1044
1057
  }
1045
1058
  }
@@ -1056,7 +1069,6 @@ function getDynamicRequirePaths(patterns) {
1056
1069
  return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
1057
1070
  }
1058
1071
 
1059
- /* eslint-disable no-undefined */
1060
1072
  const isCjsPromises = new Map();
1061
1073
 
1062
1074
  function getIsCjsPromise(id) {
@@ -1066,7 +1078,7 @@ function getIsCjsPromise(id) {
1066
1078
  const promise = new Promise((resolve) => {
1067
1079
  isCjsPromise = {
1068
1080
  resolve,
1069
- promise: undefined
1081
+ promise: null
1070
1082
  };
1071
1083
  isCjsPromises.set(id, isCjsPromise);
1072
1084
  });
@@ -1080,10 +1092,10 @@ function setIsCjsPromise(id, resolution) {
1080
1092
  if (isCjsPromise) {
1081
1093
  if (isCjsPromise.resolve) {
1082
1094
  isCjsPromise.resolve(resolution);
1083
- isCjsPromise.resolve = undefined;
1095
+ isCjsPromise.resolve = null;
1084
1096
  }
1085
1097
  } else {
1086
- isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: undefined });
1098
+ isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: null });
1087
1099
  }
1088
1100
  }
1089
1101
 
@@ -1185,10 +1197,18 @@ function getResolveId(extensions) {
1185
1197
  return undefined;
1186
1198
  }
1187
1199
 
1188
- function resolveId(importee, importer) {
1189
- const isProxyModule = importee.endsWith(PROXY_SUFFIX);
1200
+ return function resolveId(importee, importer) {
1201
+ // Proxies are only importing resolved ids, no need to resolve again
1202
+ if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
1203
+ return importee;
1204
+ }
1205
+
1206
+ const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
1207
+ const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
1190
1208
  if (isProxyModule) {
1191
- importee = getIdFromProxyId(importee);
1209
+ importee = unwrapId(importee, PROXY_SUFFIX);
1210
+ } else if (isRequiredModule) {
1211
+ importee = unwrapId(importee, REQUIRE_SUFFIX);
1192
1212
  }
1193
1213
  if (importee.startsWith('\0')) {
1194
1214
  if (
@@ -1198,32 +1218,25 @@ function getResolveId(extensions) {
1198
1218
  ) {
1199
1219
  return importee;
1200
1220
  }
1201
- if (!isProxyModule) {
1202
- return null;
1203
- }
1204
- }
1205
-
1206
- if (importer && importer.endsWith(PROXY_SUFFIX)) {
1207
- importer = getIdFromProxyId(importer);
1221
+ return null;
1208
1222
  }
1209
1223
 
1210
- return this.resolve(importee, importer, { skipSelf: true }).then((resolved) => {
1224
+ return this.resolve(importee, importer, {
1225
+ skipSelf: true,
1226
+ custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
1227
+ }).then((resolved) => {
1211
1228
  if (!resolved) {
1212
1229
  resolved = resolveExtensions(importee, importer);
1213
1230
  }
1214
- if (isProxyModule) {
1215
- if (!resolved) {
1216
- return { id: getExternalProxyId(importee), external: false };
1217
- }
1218
- resolved.id = (resolved.external ? getExternalProxyId : getProxyId)(resolved.id);
1231
+ if (resolved && isProxyModule) {
1232
+ resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
1219
1233
  resolved.external = false;
1220
- return resolved;
1234
+ } else if (!resolved && (isProxyModule || isRequiredModule)) {
1235
+ return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
1221
1236
  }
1222
1237
  return resolved;
1223
1238
  });
1224
- }
1225
-
1226
- return resolveId;
1239
+ };
1227
1240
  }
1228
1241
 
1229
1242
  function commonjs(options = {}) {
@@ -1251,7 +1264,7 @@ function commonjs(options = {}) {
1251
1264
  );
1252
1265
  const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
1253
1266
  const commonDir = isDynamicRequireModulesEnabled
1254
- ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1267
+ ? getCommonDir__default['default'](null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
1255
1268
  : null;
1256
1269
 
1257
1270
  const esModulesWithDefaultExport = new Set();
@@ -1269,6 +1282,11 @@ function commonjs(options = {}) {
1269
1282
  const sourceMap = options.sourceMap !== false;
1270
1283
 
1271
1284
  function transformAndCheckExports(code, id) {
1285
+ if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1286
+ code =
1287
+ getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1288
+ }
1289
+
1272
1290
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = checkEsModule(
1273
1291
  this.parse,
1274
1292
  code,
@@ -1285,11 +1303,13 @@ function commonjs(options = {}) {
1285
1303
  !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1286
1304
  (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1287
1305
  ) {
1288
- setIsCjsPromise(id, false);
1289
- return null;
1306
+ return { meta: { commonjs: { isCommonJS: false } } };
1290
1307
  }
1291
1308
 
1292
- const transformed = transformCommonjs(
1309
+ // avoid wrapping in createCommonjsModule, as this is a commonjsRegister call
1310
+ const disableWrap = isModuleRegistrationProxy(id, dynamicRequireModuleSet);
1311
+
1312
+ return transformCommonjs(
1293
1313
  this.parse,
1294
1314
  code,
1295
1315
  id,
@@ -1299,12 +1319,10 @@ function commonjs(options = {}) {
1299
1319
  sourceMap,
1300
1320
  isDynamicRequireModulesEnabled,
1301
1321
  dynamicRequireModuleSet,
1322
+ disableWrap,
1302
1323
  commonDir,
1303
1324
  ast
1304
1325
  );
1305
-
1306
- setIsCjsPromise(id, isEsModule ? false : Boolean(transformed));
1307
- return transformed;
1308
1326
  }
1309
1327
 
1310
1328
  return {
@@ -1338,8 +1356,8 @@ function commonjs(options = {}) {
1338
1356
  return getSpecificHelperProxy(id);
1339
1357
  }
1340
1358
 
1341
- if (id.endsWith(EXTERNAL_SUFFIX)) {
1342
- const actualId = getIdFromExternalProxyId(id);
1359
+ if (isWrappedId(id, EXTERNAL_SUFFIX)) {
1360
+ const actualId = unwrapId(id, EXTERNAL_SUFFIX);
1343
1361
  return getUnknownRequireProxy(
1344
1362
  actualId,
1345
1363
  isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
@@ -1354,13 +1372,12 @@ function commonjs(options = {}) {
1354
1372
  return getDynamicJsonProxy(id, commonDir);
1355
1373
  }
1356
1374
 
1357
- const normalizedPath = normalizePathSlashes(id);
1358
- if (dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json')) {
1359
- return getDynamicRequireProxy(normalizedPath, commonDir);
1375
+ if (isModuleRegistrationProxy(id, dynamicRequireModuleSet)) {
1376
+ return getDynamicRequireProxy(normalizePathSlashes(id), commonDir);
1360
1377
  }
1361
1378
 
1362
- if (id.endsWith(PROXY_SUFFIX)) {
1363
- const actualId = getIdFromProxyId(id);
1379
+ if (isWrappedId(id, PROXY_SUFFIX)) {
1380
+ const actualId = unwrapId(id, PROXY_SUFFIX);
1364
1381
  return getStaticRequireProxy(
1365
1382
  actualId,
1366
1383
  getRequireReturnsDefault(actualId),
@@ -1369,14 +1386,6 @@ function commonjs(options = {}) {
1369
1386
  );
1370
1387
  }
1371
1388
 
1372
- if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1373
- return getDynamicPackagesEntryIntro(
1374
- id,
1375
- dynamicRequireModuleDirPaths,
1376
- dynamicRequireModuleSet
1377
- );
1378
- }
1379
-
1380
1389
  return null;
1381
1390
  },
1382
1391
 
@@ -1388,20 +1397,25 @@ function commonjs(options = {}) {
1388
1397
  !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1389
1398
  (!filter(id) || !extensions.includes(extName))
1390
1399
  ) {
1391
- setIsCjsPromise(id, null);
1392
1400
  return null;
1393
1401
  }
1394
1402
 
1395
- let transformed;
1396
1403
  try {
1397
- transformed = transformAndCheckExports.call(this, code, id);
1404
+ return transformAndCheckExports.call(this, code, id);
1398
1405
  } catch (err) {
1399
- transformed = null;
1400
- setIsCjsPromise(id, false);
1401
- this.error(err, err.loc);
1406
+ return this.error(err, err.loc);
1402
1407
  }
1408
+ },
1403
1409
 
1404
- return transformed;
1410
+ moduleParsed({ id, meta: { commonjs } }) {
1411
+ if (commonjs) {
1412
+ const isCjs = commonjs.isCommonJS;
1413
+ if (isCjs != null) {
1414
+ setIsCjsPromise(id, isCjs);
1415
+ return;
1416
+ }
1417
+ }
1418
+ setIsCjsPromise(id, null);
1405
1419
  }
1406
1420
  };
1407
1421
  }