Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@rollup/plugin-commonjs

Package Overview
Dependencies
Maintainers
4
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@rollup/plugin-commonjs - npm Package Compare versions

Comparing version 11.1.0 to 12.0.0

18

CHANGELOG.md
# @rollup/plugin-commonjs ChangeLog
## v12.0.0
_2020-05-20_
### Breaking Changes
- feat: add kill-switch for mixed es-cjs modules (#358)
- feat: set syntheticNamedExports for commonjs modules (#149)
### Bugfixes
- fix: expose the virtual `require` function on mock `module`. fixes #307 (#326)
- fix: improved shouldWrap logic. fixes #304 (#355)
### Features
- feat: support for explicit module.require calls. fixes #310 (#325)
## v11.1.0

@@ -4,0 +22,0 @@

397

dist/index.es.js

@@ -1,13 +0,13 @@

import { statSync, existsSync, realpathSync, readFileSync } from 'fs';
import { basename, extname, dirname, sep, resolve, join, normalize } from 'path';
import { sync, isCore } from 'resolve';
import { statSync, existsSync, readFileSync } from 'fs';
import { basename, extname, dirname, sep, resolve, join } from 'path';
import { makeLegalIdentifier, attachScopes, extractAssignedNames, createFilter } from '@rollup/pluginutils';
import getCommonDir from 'commondir';
import glob from 'glob';
import { walk } from 'estree-walker';
import MagicString from 'magic-string';
import { sync } from 'resolve';
import isReference from 'is-reference';
import getCommonDir from 'commondir';
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}

@@ -20,6 +20,3 @@

function _iterableToArrayLimit(arr, i) {
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
return;
}
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];

@@ -50,6 +47,82 @@ var _n = true;

function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _createForOfIteratorHelper(o) {
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var it,
normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = o[Symbol.iterator]();
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
var peerDependencies = {
rollup: "^2.3.4"
};
/* eslint-disable no-undefined */

@@ -130,4 +203,10 @@ const operators = {

export function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
export function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}

@@ -195,3 +274,3 @@

return '.';
return joined;

@@ -211,2 +290,23 @@ }

function dirname (path) {
if (path.length === 0)
return '.';
let i = path.length - 1;
while (i > 0) {
const c = path.charCodeAt(i);
if ((c === 47 || c === 92) && i !== path.length - 1)
break;
i--;
}
if (i > 0)
return path.substr(0, i);
if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
return path.charAt(0);
return '.';
}
export function commonjsRequire (path, originalModuleDir) {

@@ -233,2 +333,3 @@ const shouldTryNodeModules = isPossibleNodeModulesPath(path);

filename: resolvedPath,
path: dirname(resolvedPath),
exports: {},

@@ -238,3 +339,6 @@ parent: DEFAULT_PARENT_MODULE,

children: [],
paths: []
paths: [],
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
}
};

@@ -319,8 +423,8 @@ try {

let isEsModule = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
var _iterator = _createForOfIteratorHelper(ast.body),
_step;
try {
for (var _iterator = ast.body[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
const node = _step.value;

@@ -335,8 +439,8 @@ if (node.type === 'ExportDefaultDeclaration') return {

isEsModule = true;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
var _iterator2 = _createForOfIteratorHelper(node.specifiers),
_step2;
try {
for (var _iterator2 = node.specifiers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
const specifier = _step2.value;

@@ -353,14 +457,5 @@

} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
_iterator2.e(err);
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
_iterator2.f();
}

@@ -370,14 +465,5 @@ } else if (importExportDeclaration.test(node.type)) isEsModule = true;

} catch (err) {
_didIteratorError = true;
_iteratorError = err;
_iterator.e(err);
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
_iterator.f();
}

@@ -410,3 +496,3 @@

function transformCommonjs(parse, code, id, isEntry, isEsModule, ignoreGlobal, ignoreRequire, customNamedExports, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, astCache) {
function transformCommonjs(parse, code, id, isEntry, isEsModule, ignoreGlobal, ignoreRequire, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, astCache) {
const ast = astCache || tryParse(parse, code, id);

@@ -434,13 +520,36 @@ const magicString = new MagicString(code);

let shouldWrap = /__esModule/.test(code);
let usesDynamicHelpers = false;
let usesCommonjsHelpers = false;
function isRequireStatement(node) {
if (!node) return false;
if (node.type !== 'CallExpression') return false;
if (node.callee.name !== 'require' || scope.contains('require')) return false; // Weird case of require() without arguments
if (node.type !== 'CallExpression') return false; // Weird case of `require()` or `module.require()` without arguments
if (node.arguments.length === 0) return false;
return true;
return isRequireIdentifier(node.callee);
}
function isRequireIdentifier(node) {
if (!node) return false;
if (node.type === 'Identifier' && node.name === 'require'
/* `require` */
) {
// `require` is hidden by a variable in local scope
if (scope.contains('require')) return false;
return true;
} else if (node.type === 'MemberExpression'
/* `[something].[something]` */
) {
// `module.[something]`
if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false; // `module` is hidden by a variable in local scope
if (scope.contains('module')) return false; // `module.require(...)`
if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
return true;
}
return false;
}
function hasDynamicArguments(node) {

@@ -592,5 +701,10 @@ return node.arguments.length > 1 || node.arguments[0].type !== 'Literal' && (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0);

uses.global = true;
if (!ignoreGlobal) magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
if (!ignoreGlobal) {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
usesCommonjsHelpers = true;
}
return;

@@ -617,3 +731,3 @@ } // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)

if (node.name in uses) {
if (node.name === 'require') {
if (isRequireIdentifier(node)) {
if (!isDynamicRequireModulesEnabled && isStaticRequireStatement(parent)) {

@@ -624,5 +738,5 @@ return;

if (isDynamicRequireModulesEnabled && isRequireStatement(parent)) {
magicString.appendLeft(parent.end - 1, ',' + JSON.stringify(dirname(id) === '.' ? null
magicString.appendLeft(parent.end - 1, `,${JSON.stringify(dirname(id) === '.' ? null
/* default behavior */
: getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir)));
: getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir))}`);
}

@@ -633,3 +747,3 @@

});
usesDynamicHelpers = true;
usesCommonjsHelpers = true;
}

@@ -643,2 +757,3 @@

});
usesCommonjsHelpers = true;
} // if module or exports are used outside the context of an assignment

@@ -724,3 +839,3 @@ // expression, we need to wrap the module

: getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir))})`);
usesDynamicHelpers = true;
usesCommonjsHelpers = true;
} else {

@@ -773,6 +888,9 @@ magicString.overwrite(node.start, node.end, required.name);

return null;
}
} // If `isEsModule` is on, it means it has ES6 import/export statements,
// which just can't be wrapped in a function.
const includeHelpers = usesDynamicHelpers || shouldWrap || uses.global || uses.require;
const importBlock = `${(includeHelpers ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`] : []).concat(sources.map(([source]) => // import the actual module before the proxy, so that we know
if (isEsModule) shouldWrap = false;
usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
const importBlock = `${(usesCommonjsHelpers ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`] : []).concat(sources.map(([source]) => // import the actual module before the proxy, so that we know
// what kind of proxy to build

@@ -809,3 +927,2 @@ `import '${source}';`), sources.filter(([, importProxy]) => importProxy).map(([source]) => {

if (customNamedExports) customNamedExports.forEach(addExport);
const defaultExportPropertyAssignments = [];

@@ -817,11 +934,17 @@ let hasDefaultExport = false;

wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
wrapperEnd = `\n});`;
wrapperEnd = `\n}`;
if (isDynamicRequireModulesEnabled) {
wrapperEnd += `, ${JSON.stringify(getVirtualPathForDynamicRequirePath(normalizePathSlashes(dirname(id)), commonDir))}`;
}
wrapperEnd += `);`;
} else {
const names = [];
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
var _iterator3 = _createForOfIteratorHelper(ast.body),
_step3;
try {
for (var _iterator3 = ast.body[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
const node = _step3.value;

@@ -871,14 +994,5 @@

} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
_iterator3.e(err);
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
_iterator3.f();
}

@@ -899,4 +1013,5 @@

magicString.trim().prepend(importBlock + wrapperStart).trim().append(wrapperEnd);
const injectExportBlock = hasDefaultExport || named.length > 0 || shouldWrap || !isEntry;
if (hasDefaultExport || named.length > 0 || shouldWrap || !isEntry && !isEsModule) {
if (injectExportBlock) {
magicString.append(exportBlock);

@@ -909,3 +1024,4 @@ }

code,
map
map,
syntheticNamedExports: injectExportBlock
};

@@ -916,17 +1032,17 @@ }

const dynamicRequireModuleSet = new Set();
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
var _iterator = _createForOfIteratorHelper(!patterns || Array.isArray(patterns) ? patterns || [] : [patterns]),
_step;
try {
for (var _iterator = (!patterns || Array.isArray(patterns) ? patterns || [] : [patterns])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
const pattern = _step.value;
const isNegated = pattern.startsWith('!');
const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
var _iterator2 = _createForOfIteratorHelper(glob.sync(isNegated ? pattern.substr(1) : pattern)),
_step2;
try {
for (var _iterator2 = glob.sync(isNegated ? pattern.substr(1) : pattern)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
const path = _step2.value;

@@ -936,29 +1052,11 @@ modifySet(normalizePathSlashes(resolve(path)));

} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
_iterator2.e(err);
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
_iterator2.f();
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
_iterator.e(err);
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
_iterator.f();
}

@@ -980,6 +1078,2 @@

var peerDependencies = {
rollup: "^1.20.0||^2.0.0"
};
/* eslint-disable no-undefined */

@@ -1106,40 +1200,2 @@ const isCjsPromises = new Map();

const commonDir = isDynamicRequireModulesEnabled ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd())) : null;
const customNamedExports = {};
if (options.namedExports) {
Object.keys(options.namedExports).forEach(id => {
let resolveId = id;
let resolvedId;
if (isCore(id)) {
// resolve will not find npm modules with the same name as
// core modules without a trailing slash. Since core modules
// must be external, we can assume any core modules defined
// here are npm modules by that name.
resolveId += '/';
}
try {
resolvedId = sync(resolveId, {
basedir: process.cwd()
});
} catch (err) {
resolvedId = resolve(id);
} // Note: customNamedExport's keys must be normalized file paths.
// resolve and nodeResolveSync both return normalized file paths
// so no additional normalization is necessary.
customNamedExports[resolvedId] = options.namedExports[id];
if (existsSync(resolvedId)) {
const realpath = realpathSync(resolvedId);
if (realpath !== resolvedId) {
customNamedExports[realpath] = options.namedExports[id];
}
}
});
}
const esModulesWithoutDefaultExport = new Set();

@@ -1159,5 +1215,10 @@ const esModulesWithDefaultExport = new Set();

if (isEsModule && !isDynamicRequireModule) {
if (isEsModule && (!isDynamicRequireModule || !options.transformMixedEsModules)) {
(hasDefaultExport ? esModulesWithDefaultExport : esModulesWithoutDefaultExport).add(id);
} // it is not an ES module but it does not have CJS-specific elements.
if (!options.transformMixedEsModules) {
setIsCjsPromise(id, false);
return null;
}
} // it is not an ES module AND it does not have CJS-specific elements.
else if (!hasCjsKeywords(code, ignoreGlobal)) {

@@ -1169,4 +1230,3 @@ esModulesWithoutDefaultExport.add(id);

const normalizedId = normalize(id);
const transformed = transformCommonjs(this.parse, code, id, this.getModuleInfo(id).isEntry, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, customNamedExports[normalizedId], sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, ast);
const transformed = transformCommonjs(this.parse, code, id, this.getModuleInfo(id).isEntry, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, ast);
setIsCjsPromise(id, isEsModule ? false : Boolean(transformed));

@@ -1186,2 +1246,6 @@

buildStart() {
if (options.namedExports != null) {
this.warn('The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.');
}
const _this$meta$rollupVers = this.meta.rollupVersion.split('.').map(Number),

@@ -1225,8 +1289,8 @@ _this$meta$rollupVers2 = _slicedToArray(_this$meta$rollupVers, 2),

let code = `const { commonjsRegister } = require('${HELPERS_ID}');`;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
var _iterator = _createForOfIteratorHelper(dynamicRequireModuleDirPaths),
_step;
try {
for (var _iterator = dynamicRequireModuleDirPaths[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
const dir = _step.value;

@@ -1249,14 +1313,5 @@ let entryPoint = 'index.js';

} catch (err) {
_didIteratorError = true;
_iteratorError = err;
_iterator.e(err);
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
_iterator.f();
}

@@ -1321,3 +1376,3 @@

code = dynamicImports + '\n' + code;
code = `${dynamicImports}\n${code}`;
return code;

@@ -1324,0 +1379,0 @@ }

@@ -7,12 +7,12 @@ 'use strict';

var path = require('path');
var resolve = require('resolve');
var pluginutils = require('@rollup/pluginutils');
var getCommonDir = _interopDefault(require('commondir'));
var glob = _interopDefault(require('glob'));
var estreeWalker = require('estree-walker');
var MagicString = _interopDefault(require('magic-string'));
var resolve = require('resolve');
var isReference = _interopDefault(require('is-reference'));
var getCommonDir = _interopDefault(require('commondir'));
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}

@@ -25,6 +25,3 @@

function _iterableToArrayLimit(arr, i) {
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
return;
}
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];

@@ -55,6 +52,82 @@ var _n = true;

function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _createForOfIteratorHelper(o) {
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var it,
normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = o[Symbol.iterator]();
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
var peerDependencies = {
rollup: "^2.3.4"
};
/* eslint-disable no-undefined */

@@ -135,4 +208,10 @@ const operators = {

export function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
export function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}

@@ -200,3 +279,3 @@

return '.';
return joined;

@@ -216,2 +295,23 @@ }

function dirname (path) {
if (path.length === 0)
return '.';
let i = path.length - 1;
while (i > 0) {
const c = path.charCodeAt(i);
if ((c === 47 || c === 92) && i !== path.length - 1)
break;
i--;
}
if (i > 0)
return path.substr(0, i);
if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
return path.charAt(0);
return '.';
}
export function commonjsRequire (path, originalModuleDir) {

@@ -238,2 +338,3 @@ const shouldTryNodeModules = isPossibleNodeModulesPath(path);

filename: resolvedPath,
path: dirname(resolvedPath),
exports: {},

@@ -243,3 +344,6 @@ parent: DEFAULT_PARENT_MODULE,

children: [],
paths: []
paths: [],
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
}
};

@@ -324,8 +428,8 @@ try {

let isEsModule = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
var _iterator = _createForOfIteratorHelper(ast.body),
_step;
try {
for (var _iterator = ast.body[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
const node = _step.value;

@@ -340,8 +444,8 @@ if (node.type === 'ExportDefaultDeclaration') return {

isEsModule = true;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
var _iterator2 = _createForOfIteratorHelper(node.specifiers),
_step2;
try {
for (var _iterator2 = node.specifiers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
const specifier = _step2.value;

@@ -358,14 +462,5 @@

} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
_iterator2.e(err);
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
_iterator2.f();
}

@@ -375,14 +470,5 @@ } else if (importExportDeclaration.test(node.type)) isEsModule = true;

} catch (err) {
_didIteratorError = true;
_iteratorError = err;
_iterator.e(err);
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
_iterator.f();
}

@@ -415,3 +501,3 @@

function transformCommonjs(parse, code, id, isEntry, isEsModule, ignoreGlobal, ignoreRequire, customNamedExports, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, astCache) {
function transformCommonjs(parse, code, id, isEntry, isEsModule, ignoreGlobal, ignoreRequire, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, astCache) {
const ast = astCache || tryParse(parse, code, id);

@@ -439,13 +525,36 @@ const magicString = new MagicString(code);

let shouldWrap = /__esModule/.test(code);
let usesDynamicHelpers = false;
let usesCommonjsHelpers = false;
function isRequireStatement(node) {
if (!node) return false;
if (node.type !== 'CallExpression') return false;
if (node.callee.name !== 'require' || scope.contains('require')) return false; // Weird case of require() without arguments
if (node.type !== 'CallExpression') return false; // Weird case of `require()` or `module.require()` without arguments
if (node.arguments.length === 0) return false;
return true;
return isRequireIdentifier(node.callee);
}
function isRequireIdentifier(node) {
if (!node) return false;
if (node.type === 'Identifier' && node.name === 'require'
/* `require` */
) {
// `require` is hidden by a variable in local scope
if (scope.contains('require')) return false;
return true;
} else if (node.type === 'MemberExpression'
/* `[something].[something]` */
) {
// `module.[something]`
if (node.object.type !== 'Identifier' || node.object.name !== 'module') return false; // `module` is hidden by a variable in local scope
if (scope.contains('module')) return false; // `module.require(...)`
if (node.property.type !== 'Identifier' || node.property.name !== 'require') return false;
return true;
}
return false;
}
function hasDynamicArguments(node) {

@@ -597,5 +706,10 @@ return node.arguments.length > 1 || node.arguments[0].type !== 'Literal' && (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0);

uses.global = true;
if (!ignoreGlobal) magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
if (!ignoreGlobal) {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
usesCommonjsHelpers = true;
}
return;

@@ -622,3 +736,3 @@ } // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)

if (node.name in uses) {
if (node.name === 'require') {
if (isRequireIdentifier(node)) {
if (!isDynamicRequireModulesEnabled && isStaticRequireStatement(parent)) {

@@ -629,5 +743,5 @@ return;

if (isDynamicRequireModulesEnabled && isRequireStatement(parent)) {
magicString.appendLeft(parent.end - 1, ',' + JSON.stringify(path.dirname(id) === '.' ? null
magicString.appendLeft(parent.end - 1, `,${JSON.stringify(path.dirname(id) === '.' ? null
/* default behavior */
: getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir)));
: getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir))}`);
}

@@ -638,3 +752,3 @@

});
usesDynamicHelpers = true;
usesCommonjsHelpers = true;
}

@@ -648,2 +762,3 @@

});
usesCommonjsHelpers = true;
} // if module or exports are used outside the context of an assignment

@@ -729,3 +844,3 @@ // expression, we need to wrap the module

: getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir))})`);
usesDynamicHelpers = true;
usesCommonjsHelpers = true;
} else {

@@ -778,6 +893,9 @@ magicString.overwrite(node.start, node.end, required.name);

return null;
}
} // If `isEsModule` is on, it means it has ES6 import/export statements,
// which just can't be wrapped in a function.
const includeHelpers = usesDynamicHelpers || shouldWrap || uses.global || uses.require;
const importBlock = `${(includeHelpers ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`] : []).concat(sources.map(([source]) => // import the actual module before the proxy, so that we know
if (isEsModule) shouldWrap = false;
usesCommonjsHelpers = usesCommonjsHelpers || shouldWrap;
const importBlock = `${(usesCommonjsHelpers ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`] : []).concat(sources.map(([source]) => // import the actual module before the proxy, so that we know
// what kind of proxy to build

@@ -814,3 +932,2 @@ `import '${source}';`), sources.filter(([, importProxy]) => importProxy).map(([source]) => {

if (customNamedExports) customNamedExports.forEach(addExport);
const defaultExportPropertyAssignments = [];

@@ -822,11 +939,17 @@ let hasDefaultExport = false;

wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
wrapperEnd = `\n});`;
wrapperEnd = `\n}`;
if (isDynamicRequireModulesEnabled) {
wrapperEnd += `, ${JSON.stringify(getVirtualPathForDynamicRequirePath(normalizePathSlashes(path.dirname(id)), commonDir))}`;
}
wrapperEnd += `);`;
} else {
const names = [];
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
var _iterator3 = _createForOfIteratorHelper(ast.body),
_step3;
try {
for (var _iterator3 = ast.body[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
const node = _step3.value;

@@ -876,14 +999,5 @@

} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
_iterator3.e(err);
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
_iterator3.f();
}

@@ -904,4 +1018,5 @@

magicString.trim().prepend(importBlock + wrapperStart).trim().append(wrapperEnd);
const injectExportBlock = hasDefaultExport || named.length > 0 || shouldWrap || !isEntry;
if (hasDefaultExport || named.length > 0 || shouldWrap || !isEntry && !isEsModule) {
if (injectExportBlock) {
magicString.append(exportBlock);

@@ -914,3 +1029,4 @@ }

code,
map
map,
syntheticNamedExports: injectExportBlock
};

@@ -921,17 +1037,17 @@ }

const dynamicRequireModuleSet = new Set();
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
var _iterator = _createForOfIteratorHelper(!patterns || Array.isArray(patterns) ? patterns || [] : [patterns]),
_step;
try {
for (var _iterator = (!patterns || Array.isArray(patterns) ? patterns || [] : [patterns])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
const pattern = _step.value;
const isNegated = pattern.startsWith('!');
const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
var _iterator2 = _createForOfIteratorHelper(glob.sync(isNegated ? pattern.substr(1) : pattern)),
_step2;
try {
for (var _iterator2 = glob.sync(isNegated ? pattern.substr(1) : pattern)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
const path$1 = _step2.value;

@@ -941,29 +1057,11 @@ modifySet(normalizePathSlashes(path.resolve(path$1)));

} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
_iterator2.e(err);
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
_iterator2.f();
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
_iterator.e(err);
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
_iterator.f();
}

@@ -985,6 +1083,2 @@

var peerDependencies = {
rollup: "^1.20.0||^2.0.0"
};
/* eslint-disable no-undefined */

@@ -1111,40 +1205,2 @@ const isCjsPromises = new Map();

const commonDir = isDynamicRequireModulesEnabled ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd())) : null;
const customNamedExports = {};
if (options.namedExports) {
Object.keys(options.namedExports).forEach(id => {
let resolveId = id;
let resolvedId;
if (resolve.isCore(id)) {
// resolve will not find npm modules with the same name as
// core modules without a trailing slash. Since core modules
// must be external, we can assume any core modules defined
// here are npm modules by that name.
resolveId += '/';
}
try {
resolvedId = resolve.sync(resolveId, {
basedir: process.cwd()
});
} catch (err) {
resolvedId = path.resolve(id);
} // Note: customNamedExport's keys must be normalized file paths.
// resolve and nodeResolveSync both return normalized file paths
// so no additional normalization is necessary.
customNamedExports[resolvedId] = options.namedExports[id];
if (fs.existsSync(resolvedId)) {
const realpath = fs.realpathSync(resolvedId);
if (realpath !== resolvedId) {
customNamedExports[realpath] = options.namedExports[id];
}
}
});
}
const esModulesWithoutDefaultExport = new Set();

@@ -1164,5 +1220,10 @@ const esModulesWithDefaultExport = new Set();

if (isEsModule && !isDynamicRequireModule) {
if (isEsModule && (!isDynamicRequireModule || !options.transformMixedEsModules)) {
(hasDefaultExport ? esModulesWithDefaultExport : esModulesWithoutDefaultExport).add(id);
} // it is not an ES module but it does not have CJS-specific elements.
if (!options.transformMixedEsModules) {
setIsCjsPromise(id, false);
return null;
}
} // it is not an ES module AND it does not have CJS-specific elements.
else if (!hasCjsKeywords(code, ignoreGlobal)) {

@@ -1174,4 +1235,3 @@ esModulesWithoutDefaultExport.add(id);

const normalizedId = path.normalize(id);
const transformed = transformCommonjs(this.parse, code, id, this.getModuleInfo(id).isEntry, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, customNamedExports[normalizedId], sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, ast);
const transformed = transformCommonjs(this.parse, code, id, this.getModuleInfo(id).isEntry, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModuleSet, commonDir, ast);
setIsCjsPromise(id, isEsModule ? false : Boolean(transformed));

@@ -1191,2 +1251,6 @@

buildStart() {
if (options.namedExports != null) {
this.warn('The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.');
}
const _this$meta$rollupVers = this.meta.rollupVersion.split('.').map(Number),

@@ -1230,8 +1294,8 @@ _this$meta$rollupVers2 = _slicedToArray(_this$meta$rollupVers, 2),

let code = `const { commonjsRegister } = require('${HELPERS_ID}');`;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
var _iterator = _createForOfIteratorHelper(dynamicRequireModuleDirPaths),
_step;
try {
for (var _iterator = dynamicRequireModuleDirPaths[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
const dir = _step.value;

@@ -1254,14 +1318,5 @@ let entryPoint = 'index.js';

} catch (err) {
_didIteratorError = true;
_iteratorError = err;
_iterator.e(err);
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
_iterator.f();
}

@@ -1326,3 +1381,3 @@

code = dynamicImports + '\n' + code;
code = `${dynamicImports}\n${code}`;
return code;

@@ -1329,0 +1384,0 @@ }

{
"name": "@rollup/plugin-commonjs",
"version": "11.1.0",
"version": "12.0.0",
"publishConfig": {

@@ -49,3 +49,3 @@ "access": "public"

"peerDependencies": {
"rollup": "^1.20.0||^2.0.0"
"rollup": "^2.3.4"
},

@@ -62,12 +62,12 @@ "dependencies": {

"devDependencies": {
"@babel/core": "^7.7.7",
"@babel/preset-env": "^7.7.7",
"@babel/register": "^7.7.7",
"@babel/core": "^7.9.0",
"@babel/preset-env": "^7.9.0",
"@babel/register": "^7.9.0",
"@rollup/plugin-json": "^4.0.1",
"@rollup/plugin-node-resolve": "^7.0.0",
"acorn": "^7.1.0",
"acorn": "^7.1.1",
"locate-character": "^2.0.5",
"prettier": "^1.19.1",
"require-relative": "^0.8.7",
"rollup": "^2.0.0",
"rollup": "^2.3.4",
"rollup-plugin-babel": "^4.3.3",

@@ -74,0 +74,0 @@ "shx": "^0.3.2",

@@ -109,43 +109,9 @@ [npm]: https://img.shields.io/npm/v/@rollup/plugin-commonjs

### `namedExports`
### `transformMixedEsModules`
Type: `Object`<br>
Default: `null`
Type: `Boolean`<br>
Default: `false`
Explicitly specify unresolvable named exports.
Instructs the plugin whether or not to enable mixed module transformations. This is useful in scenarios with mixed ES and CommonJS modules. Set to `true` if it's known that `require` calls should be transformed, or `false` if the code contains env detection and the `require` should survive a transformation.
This plugin will attempt to create named exports, where appropriate, so you can do this...
```js
// importer.js
import { named } from './exporter.js';
// exporter.js
module.exports = { named: 42 }; // or `exports.named = 42;`
```
...but that's not always possible:
```js
// importer.js
import { named } from 'my-lib';
// my-lib.js
var myLib = exports;
myLib.named = "you can't see me";
```
In those cases, you can specify custom named exports:
```js
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
'my-lib': ['named']
}
});
```
### `ignore`

@@ -160,3 +126,3 @@

Since most CommonJS packages you are importing are probably depdenencies in `node_modules`, you may need to use [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve):
Since most CommonJS packages you are importing are probably dependencies in `node_modules`, you may need to use [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve):

@@ -163,0 +129,0 @@ ```js

@@ -34,2 +34,7 @@ import { FilterPattern } from '@rollup/pluginutils';

/**
* Instructs the plugin whether or not to enable mixed module transformations. This is useful in scenarios with mixed ES and CommonJS modules. Set to `true` if it's known that `require` calls should be transformed, or `false` if the code contains env detection and the `require` should survive a transformation.
* @default false
*/
transformMixedEsModules?: boolean;
/**
* explicitly specify unresolvable named exports

@@ -36,0 +41,0 @@ * ([see below for more details](https://github.com/rollup/plugins/tree/master/packages/commonjs#named-exports))

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc