@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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @rollup/plugin-commonjs ChangeLog
2
2
 
3
+ ## v16.0.0
4
+
5
+ _2020-10-27_
6
+
7
+ ### Breaking Changes
8
+
9
+ - feat!: Expose cjs detection and support offline caching (#604)
10
+
11
+ ### Bugfixes
12
+
13
+ - fix: avoid wrapping `commonjsRegister` call in `createCommonjsModule(...)` (#602)
14
+ - fix: register dynamic modules when a different loader (i.e typescript) loads the entry file (#599)
15
+ - fix: fixed access to node_modules dynamic module with subfolder (i.e 'logform/json') (#601)
16
+
17
+ ### Features
18
+
19
+ - feat: pass type of import to node-resolve (#611)
20
+
3
21
  ## v15.1.0
4
22
 
5
23
  _2020-09-21_
package/README.md CHANGED
@@ -143,7 +143,7 @@ You can also supply an array of ids to be treated as ES modules, or a function t
143
143
 
144
144
  ### `requireReturnsDefault`
145
145
 
146
- Type: `boolean | "auto" | "preferred" | ((id: string) => boolean | "auto" | "preferred")`<br>
146
+ Type: `boolean | "namespace" | "auto" | "preferred" | ((id: string) => boolean | "auto" | "preferred")`<br>
147
147
  Default: `false`
148
148
 
149
149
  Controls what is returned when requiring an ES module from a CommonJS file. When using the `esmExternals` option, this will also apply to external modules. By default, this plugin will render those imports as namespace imports, i.e.
@@ -311,6 +311,26 @@ ES modules are _always_ parsed in strict mode. That means that certain non-stric
311
311
 
312
312
  Luckily, there is absolutely no good reason _not_ to use strict mode for everything — so the solution to this problem is to lobby the authors of those modules to update them.
313
313
 
314
+ ## Inter-plugin-communication
315
+
316
+ This plugin exposes the result of its CommonJS file type detection for other plugins to use. You can access it via `this.getModuleInfo` or the `moduleParsed` hook:
317
+
318
+ ```js
319
+ function cjsDetectionPlugin() {
320
+ return {
321
+ name: 'cjs-detection',
322
+ moduleParsed({
323
+ id,
324
+ meta: {
325
+ commonjs: { isCommonJS }
326
+ }
327
+ }) {
328
+ console.log(`File ${id} is CommonJS: ${isCommonJS}`);
329
+ }
330
+ };
331
+ }
332
+ ```
333
+
314
334
  ## Meta
315
335
 
316
336
  [CONTRIBUTING](/.github/CONTRIBUTING.md)
package/dist/index.es.js CHANGED
@@ -9,16 +9,16 @@ import isReference from 'is-reference';
9
9
  import glob from 'glob';
10
10
 
11
11
  var peerDependencies = {
12
- rollup: "^2.22.0"
12
+ rollup: "^2.30.0"
13
13
  };
14
14
 
15
- const PROXY_SUFFIX = '?commonjs-proxy';
16
- const getProxyId = (id) => `\0${id}${PROXY_SUFFIX}`;
17
- const getIdFromProxyId = (proxyId) => proxyId.slice(1, -PROXY_SUFFIX.length);
15
+ const isWrappedId = (id, suffix) => id.endsWith(suffix);
16
+ const wrapId = (id, suffix) => `\0${id}${suffix}`;
17
+ const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
18
18
 
19
+ const PROXY_SUFFIX = '?commonjs-proxy';
20
+ const REQUIRE_SUFFIX = '?commonjs-require';
19
21
  const EXTERNAL_SUFFIX = '?commonjs-external';
20
- const getExternalProxyId = (id) => `\0${id}${EXTERNAL_SUFFIX}`;
21
- const getIdFromExternalProxyId = (proxyId) => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
22
22
 
23
23
  const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
24
24
  const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
@@ -414,6 +414,7 @@ function transformCommonjs(
414
414
  sourceMap,
415
415
  isDynamicRequireModulesEnabled,
416
416
  dynamicRequireModuleSet,
417
+ disableWrap,
417
418
  commonDir,
418
419
  astCache
419
420
  ) {
@@ -424,7 +425,8 @@ function transformCommonjs(
424
425
  const required = {};
425
426
  // Because objects have no guaranteed ordering, yet we need it,
426
427
  // we need to keep track of the order in a array
427
- const sources = [];
428
+ const requiredSources = [];
429
+ const dynamicRegisterSources = [];
428
430
 
429
431
  let uid = 0;
430
432
 
@@ -515,8 +517,7 @@ function transformCommonjs(
515
517
  }
516
518
 
517
519
  const existing = required[sourceId];
518
- // eslint-disable-next-line no-undefined
519
- if (existing === undefined) {
520
+ if (!existing) {
520
521
  const isDynamic = hasDynamicModuleForPath(sourceId);
521
522
 
522
523
  if (!name) {
@@ -526,12 +527,15 @@ function transformCommonjs(
526
527
  } while (scope.contains(name));
527
528
  }
528
529
 
529
- if (isDynamicRegister && sourceId.endsWith('.json')) {
530
- sourceId = DYNAMIC_JSON_PREFIX + sourceId;
530
+ if (isDynamicRegister) {
531
+ if (sourceId.endsWith('.json')) {
532
+ sourceId = DYNAMIC_JSON_PREFIX + sourceId;
533
+ }
534
+ dynamicRegisterSources.push(sourceId);
531
535
  }
532
536
 
533
- if (isDynamicRegister || !isDynamic || sourceId.endsWith('.json')) {
534
- sources.push([sourceId, !isDynamicRegister]);
537
+ if (!isDynamic || sourceId.endsWith('.json')) {
538
+ requiredSources.push(sourceId);
535
539
  }
536
540
 
537
541
  required[sourceId] = { source: sourceId, name, importsDefault: false, isDynamic };
@@ -541,7 +545,7 @@ function transformCommonjs(
541
545
  }
542
546
 
543
547
  function hasDynamicModuleForPath(source) {
544
- if (!/[/\\]/.test(source)) {
548
+ if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
545
549
  try {
546
550
  const resolvedPath = normalizePathSlashes(
547
551
  sync(source, { basedir: dirname(id) })
@@ -832,42 +836,45 @@ function transformCommonjs(
832
836
  }
833
837
  });
834
838
 
839
+ // If `isEsModule` is on, it means it has ES6 import/export statements,
840
+ // which just can't be wrapped in a function.
841
+ shouldWrap = shouldWrap && !disableWrap && !isEsModule;
842
+
843
+ usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
844
+
835
845
  if (
836
- !sources.length &&
846
+ !requiredSources.length &&
847
+ !dynamicRegisterSources.length &&
837
848
  !uses.module &&
838
849
  !uses.exports &&
839
850
  !uses.require &&
851
+ !usesCommonjsHelpers &&
840
852
  (ignoreGlobal || !uses.global)
841
853
  ) {
842
- // not a CommonJS module
843
- return null;
854
+ return { meta: { commonjs: { isCommonJS: false } } };
844
855
  }
845
856
 
846
- // If `isEsModule` is on, it means it has ES6 import/export statements,
847
- // which just can't be wrapped in a function.
848
- if (isEsModule) shouldWrap = false;
849
-
850
- usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
851
-
852
857
  const importBlock = `${(usesCommonjsHelpers
853
858
  ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`]
854
859
  : []
855
860
  )
856
861
  .concat(
857
- sources.map(
858
- ([source]) =>
859
- // import the actual module before the proxy, so that we know
860
- // what kind of proxy to build
861
- `import '${source}';`
862
- ),
863
- sources
864
- .filter(([, importProxy]) => importProxy)
865
- .map(([source]) => {
866
- const { name, importsDefault } = required[source];
867
- return `import ${importsDefault ? `${name} from ` : ``}'${
868
- source.startsWith('\0') ? source : getProxyId(source)
869
- }';`;
870
- })
862
+ // dynamic registers first, as the may be required in the other modules
863
+ dynamicRegisterSources.map((source) => `import '${source}';`),
864
+
865
+ // now the actual modules so that they are analyzed before creating the proxies;
866
+ // no need to do this for virtual modules as we never proxy them
867
+ requiredSources
868
+ .filter((source) => !source.startsWith('\0'))
869
+ .map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
870
+
871
+ // now the proxy modules
872
+ requiredSources.map((source) => {
873
+ const { name, importsDefault } = required[source];
874
+ return `import ${importsDefault ? `${name} from ` : ``}'${
875
+ source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
876
+ }';`;
877
+ })
871
878
  )
872
879
  .join('\n')}\n\n`;
873
880
 
@@ -978,7 +985,12 @@ function transformCommonjs(
978
985
  code = magicString.toString();
979
986
  const map = sourceMap ? magicString.generateMap() : null;
980
987
 
981
- return { code, map, syntheticNamedExports: isEsModule ? false : '__moduleExports' };
988
+ return {
989
+ code,
990
+ map,
991
+ syntheticNamedExports: isEsModule ? false : '__moduleExports',
992
+ meta: { commonjs: { isCommonJS: !isEsModule } }
993
+ };
982
994
  }
983
995
 
984
996
  function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
@@ -1006,28 +1018,24 @@ function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
1006
1018
  }
1007
1019
 
1008
1020
  function getDynamicPackagesEntryIntro(
1009
- id,
1010
1021
  dynamicRequireModuleDirPaths,
1011
1022
  dynamicRequireModuleSet
1012
1023
  ) {
1013
- try {
1014
- const code = readFileSync(id, { encoding: 'utf8' });
1015
- let dynamicImports = Array.from(
1016
- dynamicRequireModuleSet,
1017
- (dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
1018
- ).join('\n');
1024
+ let dynamicImports = Array.from(
1025
+ dynamicRequireModuleSet,
1026
+ (dynamicId) => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + dynamicId)});`
1027
+ ).join('\n');
1019
1028
 
1020
- if (dynamicRequireModuleDirPaths.length) {
1021
- dynamicImports += `require(${JSON.stringify(
1022
- DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID
1023
- )});`;
1024
- }
1025
-
1026
- return `${dynamicImports}\n${code}`;
1027
- } catch (ex) {
1028
- this.warn(`Failed to read file ${id}, dynamic modules might not work correctly`);
1029
- return null;
1029
+ if (dynamicRequireModuleDirPaths.length) {
1030
+ dynamicImports += `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID)});`;
1030
1031
  }
1032
+
1033
+ return dynamicImports;
1034
+ }
1035
+
1036
+ function isModuleRegistrationProxy(id, dynamicRequireModuleSet) {
1037
+ const normalizedPath = normalizePathSlashes(id);
1038
+ return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
1031
1039
  }
1032
1040
 
1033
1041
  function getDynamicRequirePaths(patterns) {
@@ -1052,7 +1060,6 @@ function getDynamicRequirePaths(patterns) {
1052
1060
  return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
1053
1061
  }
1054
1062
 
1055
- /* eslint-disable no-undefined */
1056
1063
  const isCjsPromises = new Map();
1057
1064
 
1058
1065
  function getIsCjsPromise(id) {
@@ -1062,7 +1069,7 @@ function getIsCjsPromise(id) {
1062
1069
  const promise = new Promise((resolve) => {
1063
1070
  isCjsPromise = {
1064
1071
  resolve,
1065
- promise: undefined
1072
+ promise: null
1066
1073
  };
1067
1074
  isCjsPromises.set(id, isCjsPromise);
1068
1075
  });
@@ -1076,10 +1083,10 @@ function setIsCjsPromise(id, resolution) {
1076
1083
  if (isCjsPromise) {
1077
1084
  if (isCjsPromise.resolve) {
1078
1085
  isCjsPromise.resolve(resolution);
1079
- isCjsPromise.resolve = undefined;
1086
+ isCjsPromise.resolve = null;
1080
1087
  }
1081
1088
  } else {
1082
- isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: undefined });
1089
+ isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: null });
1083
1090
  }
1084
1091
  }
1085
1092
 
@@ -1181,10 +1188,18 @@ function getResolveId(extensions) {
1181
1188
  return undefined;
1182
1189
  }
1183
1190
 
1184
- function resolveId(importee, importer) {
1185
- const isProxyModule = importee.endsWith(PROXY_SUFFIX);
1191
+ return function resolveId(importee, importer) {
1192
+ // Proxies are only importing resolved ids, no need to resolve again
1193
+ if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
1194
+ return importee;
1195
+ }
1196
+
1197
+ const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
1198
+ const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
1186
1199
  if (isProxyModule) {
1187
- importee = getIdFromProxyId(importee);
1200
+ importee = unwrapId(importee, PROXY_SUFFIX);
1201
+ } else if (isRequiredModule) {
1202
+ importee = unwrapId(importee, REQUIRE_SUFFIX);
1188
1203
  }
1189
1204
  if (importee.startsWith('\0')) {
1190
1205
  if (
@@ -1194,32 +1209,25 @@ function getResolveId(extensions) {
1194
1209
  ) {
1195
1210
  return importee;
1196
1211
  }
1197
- if (!isProxyModule) {
1198
- return null;
1199
- }
1200
- }
1201
-
1202
- if (importer && importer.endsWith(PROXY_SUFFIX)) {
1203
- importer = getIdFromProxyId(importer);
1212
+ return null;
1204
1213
  }
1205
1214
 
1206
- return this.resolve(importee, importer, { skipSelf: true }).then((resolved) => {
1215
+ return this.resolve(importee, importer, {
1216
+ skipSelf: true,
1217
+ custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
1218
+ }).then((resolved) => {
1207
1219
  if (!resolved) {
1208
1220
  resolved = resolveExtensions(importee, importer);
1209
1221
  }
1210
- if (isProxyModule) {
1211
- if (!resolved) {
1212
- return { id: getExternalProxyId(importee), external: false };
1213
- }
1214
- resolved.id = (resolved.external ? getExternalProxyId : getProxyId)(resolved.id);
1222
+ if (resolved && isProxyModule) {
1223
+ resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
1215
1224
  resolved.external = false;
1216
- return resolved;
1225
+ } else if (!resolved && (isProxyModule || isRequiredModule)) {
1226
+ return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
1217
1227
  }
1218
1228
  return resolved;
1219
1229
  });
1220
- }
1221
-
1222
- return resolveId;
1230
+ };
1223
1231
  }
1224
1232
 
1225
1233
  function commonjs(options = {}) {
@@ -1265,6 +1273,11 @@ function commonjs(options = {}) {
1265
1273
  const sourceMap = options.sourceMap !== false;
1266
1274
 
1267
1275
  function transformAndCheckExports(code, id) {
1276
+ if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1277
+ code =
1278
+ getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
1279
+ }
1280
+
1268
1281
  const { isEsModule, hasDefaultExport, hasNamedExports, ast } = checkEsModule(
1269
1282
  this.parse,
1270
1283
  code,
@@ -1281,11 +1294,13 @@ function commonjs(options = {}) {
1281
1294
  !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
1282
1295
  (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
1283
1296
  ) {
1284
- setIsCjsPromise(id, false);
1285
- return null;
1297
+ return { meta: { commonjs: { isCommonJS: false } } };
1286
1298
  }
1287
1299
 
1288
- const transformed = transformCommonjs(
1300
+ // avoid wrapping in createCommonjsModule, as this is a commonjsRegister call
1301
+ const disableWrap = isModuleRegistrationProxy(id, dynamicRequireModuleSet);
1302
+
1303
+ return transformCommonjs(
1289
1304
  this.parse,
1290
1305
  code,
1291
1306
  id,
@@ -1295,12 +1310,10 @@ function commonjs(options = {}) {
1295
1310
  sourceMap,
1296
1311
  isDynamicRequireModulesEnabled,
1297
1312
  dynamicRequireModuleSet,
1313
+ disableWrap,
1298
1314
  commonDir,
1299
1315
  ast
1300
1316
  );
1301
-
1302
- setIsCjsPromise(id, isEsModule ? false : Boolean(transformed));
1303
- return transformed;
1304
1317
  }
1305
1318
 
1306
1319
  return {
@@ -1334,8 +1347,8 @@ function commonjs(options = {}) {
1334
1347
  return getSpecificHelperProxy(id);
1335
1348
  }
1336
1349
 
1337
- if (id.endsWith(EXTERNAL_SUFFIX)) {
1338
- const actualId = getIdFromExternalProxyId(id);
1350
+ if (isWrappedId(id, EXTERNAL_SUFFIX)) {
1351
+ const actualId = unwrapId(id, EXTERNAL_SUFFIX);
1339
1352
  return getUnknownRequireProxy(
1340
1353
  actualId,
1341
1354
  isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
@@ -1350,13 +1363,12 @@ function commonjs(options = {}) {
1350
1363
  return getDynamicJsonProxy(id, commonDir);
1351
1364
  }
1352
1365
 
1353
- const normalizedPath = normalizePathSlashes(id);
1354
- if (dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json')) {
1355
- return getDynamicRequireProxy(normalizedPath, commonDir);
1366
+ if (isModuleRegistrationProxy(id, dynamicRequireModuleSet)) {
1367
+ return getDynamicRequireProxy(normalizePathSlashes(id), commonDir);
1356
1368
  }
1357
1369
 
1358
- if (id.endsWith(PROXY_SUFFIX)) {
1359
- const actualId = getIdFromProxyId(id);
1370
+ if (isWrappedId(id, PROXY_SUFFIX)) {
1371
+ const actualId = unwrapId(id, PROXY_SUFFIX);
1360
1372
  return getStaticRequireProxy(
1361
1373
  actualId,
1362
1374
  getRequireReturnsDefault(actualId),
@@ -1365,14 +1377,6 @@ function commonjs(options = {}) {
1365
1377
  );
1366
1378
  }
1367
1379
 
1368
- if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
1369
- return getDynamicPackagesEntryIntro(
1370
- id,
1371
- dynamicRequireModuleDirPaths,
1372
- dynamicRequireModuleSet
1373
- );
1374
- }
1375
-
1376
1380
  return null;
1377
1381
  },
1378
1382
 
@@ -1384,20 +1388,25 @@ function commonjs(options = {}) {
1384
1388
  !id.startsWith(DYNAMIC_JSON_PREFIX) &&
1385
1389
  (!filter(id) || !extensions.includes(extName))
1386
1390
  ) {
1387
- setIsCjsPromise(id, null);
1388
1391
  return null;
1389
1392
  }
1390
1393
 
1391
- let transformed;
1392
1394
  try {
1393
- transformed = transformAndCheckExports.call(this, code, id);
1395
+ return transformAndCheckExports.call(this, code, id);
1394
1396
  } catch (err) {
1395
- transformed = null;
1396
- setIsCjsPromise(id, false);
1397
- this.error(err, err.loc);
1397
+ return this.error(err, err.loc);
1398
1398
  }
1399
+ },
1399
1400
 
1400
- return transformed;
1401
+ moduleParsed({ id, meta: { commonjs } }) {
1402
+ if (commonjs) {
1403
+ const isCjs = commonjs.isCommonJS;
1404
+ if (isCjs != null) {
1405
+ setIsCjsPromise(id, isCjs);
1406
+ return;
1407
+ }
1408
+ }
1409
+ setIsCjsPromise(id, null);
1401
1410
  }
1402
1411
  };
1403
1412
  }