UNPKG

rollup-plugin-peer-deps-external

Version:

Rollup plugin to automatically add a library's peerDependencies to its bundle's external config.

1,009 lines (935 loc) 29.4 kB
'use strict'; function _isPlaceholder(a) { return a != null && typeof a === 'object' && a['@@functional/placeholder'] === true; } /** * Optimized internal one-arity curry function. * * @private * @category Function * @param {Function} fn The function to curry. * @return {Function} The curried function. */ function _curry1(fn) { return function f1(a) { if (arguments.length === 0 || _isPlaceholder(a)) { return f1; } else { return fn.apply(this, arguments); } }; } /** * Optimized internal two-arity curry function. * * @private * @category Function * @param {Function} fn The function to curry. * @return {Function} The curried function. */ function _curry2(fn) { return function f2(a, b) { switch (arguments.length) { case 0: return f2; case 1: return _isPlaceholder(a) ? f2 : _curry1(function (_b) { return fn(a, _b); }); default: return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) { return fn(_a, b); }) : _isPlaceholder(b) ? _curry1(function (_b) { return fn(a, _b); }) : fn(a, b); } }; } /** * Private `concat` function to merge two array-like objects. * * @private * @param {Array|Arguments} [set1=[]] An array-like object. * @param {Array|Arguments} [set2=[]] An array-like object. * @return {Array} A new, merged array. * @example * * _concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] */ function _concat(set1, set2) { set1 = set1 || []; set2 = set2 || []; var idx; var len1 = set1.length; var len2 = set2.length; var result = []; idx = 0; while (idx < len1) { result[result.length] = set1[idx]; idx += 1; } idx = 0; while (idx < len2) { result[result.length] = set2[idx]; idx += 1; } return result; } function _arity(n, fn) { /* eslint-disable no-unused-vars */ switch (n) { case 0: return function () { return fn.apply(this, arguments); }; case 1: return function (a0) { return fn.apply(this, arguments); }; case 2: return function (a0, a1) { return fn.apply(this, arguments); }; case 3: return function (a0, a1, a2) { return fn.apply(this, arguments); }; case 4: return function (a0, a1, a2, a3) { return fn.apply(this, arguments); }; case 5: return function (a0, a1, a2, a3, a4) { return fn.apply(this, arguments); }; case 6: return function (a0, a1, a2, a3, a4, a5) { return fn.apply(this, arguments); }; case 7: return function (a0, a1, a2, a3, a4, a5, a6) { return fn.apply(this, arguments); }; case 8: return function (a0, a1, a2, a3, a4, a5, a6, a7) { return fn.apply(this, arguments); }; case 9: return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { return fn.apply(this, arguments); }; case 10: return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { return fn.apply(this, arguments); }; default: throw new Error('First argument to _arity must be a non-negative integer no greater than ten'); } } /** * Internal curryN function. * * @private * @category Function * @param {Number} length The arity of the curried function. * @param {Array} received An array of arguments received thus far. * @param {Function} fn The function to curry. * @return {Function} The curried function. */ function _curryN(length, received, fn) { return function () { var combined = []; var argsIdx = 0; var left = length; var combinedIdx = 0; while (combinedIdx < received.length || argsIdx < arguments.length) { var result; if (combinedIdx < received.length && (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length)) { result = received[combinedIdx]; } else { result = arguments[argsIdx]; argsIdx += 1; } combined[combinedIdx] = result; if (!_isPlaceholder(result)) { left -= 1; } combinedIdx += 1; } return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn)); }; } /** * Returns a curried equivalent of the provided function, with the specified * arity. The curried function has two unusual capabilities. First, its * arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the * following are equivalent: * * - `g(1)(2)(3)` * - `g(1)(2, 3)` * - `g(1, 2)(3)` * - `g(1, 2, 3)` * * Secondly, the special placeholder value [`R.__`](#__) may be used to specify * "gaps", allowing partial application of any combination of arguments, * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__), * the following are equivalent: * * - `g(1, 2, 3)` * - `g(_, 2, 3)(1)` * - `g(_, _, 3)(1)(2)` * - `g(_, _, 3)(1, 2)` * - `g(_, 2)(1)(3)` * - `g(_, 2)(1, 3)` * - `g(_, 2)(_, 3)(1)` * * @func * @memberOf R * @since v0.5.0 * @category Function * @sig Number -> (* -> a) -> (* -> a) * @param {Number} length The arity for the returned function. * @param {Function} fn The function to curry. * @return {Function} A new, curried function. * @see R.curry * @example * * const sumArgs = (...args) => R.sum(args); * * const curriedAddFourNumbers = R.curryN(4, sumArgs); * const f = curriedAddFourNumbers(1, 2); * const g = f(3); * g(4); //=> 10 */ var curryN = /*#__PURE__*/_curry2(function curryN(length, fn) { if (length === 1) { return _curry1(fn); } return _arity(length, _curryN(length, [], fn)); }); /** * Tests whether or not an object is an array. * * @private * @param {*} val The object to test. * @return {Boolean} `true` if `val` is an array, `false` otherwise. * @example * * _isArray([]); //=> true * _isArray(null); //=> false * _isArray({}); //=> false */ var _isArray = Array.isArray || function _isArray(val) { return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]'; }; function _isTransformer(obj) { return obj != null && typeof obj['@@transducer/step'] === 'function'; } /** * Returns a function that dispatches with different strategies based on the * object in list position (last argument). If it is an array, executes [fn]. * Otherwise, if it has a function with one of the given method names, it will * execute that function (functor case). Otherwise, if it is a transformer, * uses transducer [xf] to return a new transformer (transducer case). * Otherwise, it will default to executing [fn]. * * @private * @param {Array} methodNames properties to check for a custom implementation * @param {Function} xf transducer to initialize if object is transformer * @param {Function} fn default ramda implementation * @return {Function} A function that dispatches on object in list position */ function _dispatchable(methodNames, xf, fn) { return function () { if (arguments.length === 0) { return fn(); } var args = Array.prototype.slice.call(arguments, 0); var obj = args.pop(); if (!_isArray(obj)) { var idx = 0; while (idx < methodNames.length) { if (typeof obj[methodNames[idx]] === 'function') { return obj[methodNames[idx]].apply(obj, args); } idx += 1; } if (_isTransformer(obj)) { var transducer = xf.apply(null, args); return transducer(obj); } } return fn.apply(this, arguments); }; } var _xfBase = { init: function () { return this.xf['@@transducer/init'](); }, result: function (result) { return this.xf['@@transducer/result'](result); } }; function _map(fn, functor) { var idx = 0; var len = functor.length; var result = Array(len); while (idx < len) { result[idx] = fn(functor[idx]); idx += 1; } return result; } function _isString(x) { return Object.prototype.toString.call(x) === '[object String]'; } /** * Tests whether or not an object is similar to an array. * * @private * @category Type * @category List * @sig * -> Boolean * @param {*} x The object to test. * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise. * @example * * _isArrayLike([]); //=> true * _isArrayLike(true); //=> false * _isArrayLike({}); //=> false * _isArrayLike({length: 10}); //=> false * _isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true */ var _isArrayLike = /*#__PURE__*/_curry1(function isArrayLike(x) { if (_isArray(x)) { return true; } if (!x) { return false; } if (typeof x !== 'object') { return false; } if (_isString(x)) { return false; } if (x.nodeType === 1) { return !!x.length; } if (x.length === 0) { return true; } if (x.length > 0) { return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1); } return false; }); var XWrap = /*#__PURE__*/function () { function XWrap(fn) { this.f = fn; } XWrap.prototype['@@transducer/init'] = function () { throw new Error('init not implemented on XWrap'); }; XWrap.prototype['@@transducer/result'] = function (acc) { return acc; }; XWrap.prototype['@@transducer/step'] = function (acc, x) { return this.f(acc, x); }; return XWrap; }(); function _xwrap(fn) { return new XWrap(fn); } /** * Creates a function that is bound to a context. * Note: `R.bind` does not provide the additional argument-binding capabilities of * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). * * @func * @memberOf R * @since v0.6.0 * @category Function * @category Object * @sig (* -> *) -> {*} -> (* -> *) * @param {Function} fn The function to bind to context * @param {Object} thisObj The context to bind `fn` to * @return {Function} A function that will execute in the context of `thisObj`. * @see R.partial * @example * * const log = R.bind(console.log, console); * R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3} * // logs {a: 2} * @symb R.bind(f, o)(a, b) = f.call(o, a, b) */ var bind = /*#__PURE__*/_curry2(function bind(fn, thisObj) { return _arity(fn.length, function () { return fn.apply(thisObj, arguments); }); }); function _arrayReduce(xf, acc, list) { var idx = 0; var len = list.length; while (idx < len) { acc = xf['@@transducer/step'](acc, list[idx]); if (acc && acc['@@transducer/reduced']) { acc = acc['@@transducer/value']; break; } idx += 1; } return xf['@@transducer/result'](acc); } function _iterableReduce(xf, acc, iter) { var step = iter.next(); while (!step.done) { acc = xf['@@transducer/step'](acc, step.value); if (acc && acc['@@transducer/reduced']) { acc = acc['@@transducer/value']; break; } step = iter.next(); } return xf['@@transducer/result'](acc); } function _methodReduce(xf, acc, obj, methodName) { return xf['@@transducer/result'](obj[methodName](bind(xf['@@transducer/step'], xf), acc)); } var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator'; function _reduce(fn, acc, list) { if (typeof fn === 'function') { fn = _xwrap(fn); } if (_isArrayLike(list)) { return _arrayReduce(fn, acc, list); } if (typeof list['fantasy-land/reduce'] === 'function') { return _methodReduce(fn, acc, list, 'fantasy-land/reduce'); } if (list[symIterator] != null) { return _iterableReduce(fn, acc, list[symIterator]()); } if (typeof list.next === 'function') { return _iterableReduce(fn, acc, list); } if (typeof list.reduce === 'function') { return _methodReduce(fn, acc, list, 'reduce'); } throw new TypeError('reduce: list must be array or iterable'); } var XMap = /*#__PURE__*/function () { function XMap(f, xf) { this.xf = xf; this.f = f; } XMap.prototype['@@transducer/init'] = _xfBase.init; XMap.prototype['@@transducer/result'] = _xfBase.result; XMap.prototype['@@transducer/step'] = function (result, input) { return this.xf['@@transducer/step'](result, this.f(input)); }; return XMap; }(); var _xmap = /*#__PURE__*/_curry2(function _xmap(f, xf) { return new XMap(f, xf); }); function _has(prop, obj) { return Object.prototype.hasOwnProperty.call(obj, prop); } var toString = Object.prototype.toString; var _isArguments = /*#__PURE__*/function () { return toString.call(arguments) === '[object Arguments]' ? function _isArguments(x) { return toString.call(x) === '[object Arguments]'; } : function _isArguments(x) { return _has('callee', x); }; }(); // cover IE < 9 keys issues var hasEnumBug = ! /*#__PURE__*/{ toString: null }.propertyIsEnumerable('toString'); var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; // Safari bug var hasArgsEnumBug = /*#__PURE__*/function () { return arguments.propertyIsEnumerable('length'); }(); var contains = function contains(list, item) { var idx = 0; while (idx < list.length) { if (list[idx] === item) { return true; } idx += 1; } return false; }; /** * Returns a list containing the names of all the enumerable own properties of * the supplied object. * Note that the order of the output array is not guaranteed to be consistent * across different JS platforms. * * @func * @memberOf R * @since v0.1.0 * @category Object * @sig {k: v} -> [k] * @param {Object} obj The object to extract properties from * @return {Array} An array of the object's own properties. * @see R.keysIn, R.values * @example * * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] */ var keys = typeof Object.keys === 'function' && !hasArgsEnumBug ? /*#__PURE__*/_curry1(function keys(obj) { return Object(obj) !== obj ? [] : Object.keys(obj); }) : /*#__PURE__*/_curry1(function keys(obj) { if (Object(obj) !== obj) { return []; } var prop, nIdx; var ks = []; var checkArgsLength = hasArgsEnumBug && _isArguments(obj); for (prop in obj) { if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) { ks[ks.length] = prop; } } if (hasEnumBug) { nIdx = nonEnumerableProps.length - 1; while (nIdx >= 0) { prop = nonEnumerableProps[nIdx]; if (_has(prop, obj) && !contains(ks, prop)) { ks[ks.length] = prop; } nIdx -= 1; } } return ks; }); /** * Takes a function and * a [functor](https://github.com/fantasyland/fantasy-land#functor), * applies the function to each of the functor's values, and returns * a functor of the same shape. * * Ramda provides suitable `map` implementations for `Array` and `Object`, * so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`. * * Dispatches to the `map` method of the second argument, if present. * * Acts as a transducer if a transformer is given in list position. * * Also treats functions as functors and will compose them together. * * @func * @memberOf R * @since v0.1.0 * @category List * @sig Functor f => (a -> b) -> f a -> f b * @param {Function} fn The function to be called on every element of the input `list`. * @param {Array} list The list to be iterated over. * @return {Array} The new list. * @see R.transduce, R.addIndex * @example * * const double = x => x * 2; * * R.map(double, [1, 2, 3]); //=> [2, 4, 6] * * R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6} * @symb R.map(f, [a, b]) = [f(a), f(b)] * @symb R.map(f, { x: a, y: b }) = { x: f(a), y: f(b) } * @symb R.map(f, functor_o) = functor_o.map(f) */ var map = /*#__PURE__*/_curry2( /*#__PURE__*/_dispatchable(['fantasy-land/map', 'map'], _xmap, function map(fn, functor) { switch (Object.prototype.toString.call(functor)) { case '[object Function]': return curryN(functor.length, function () { return fn.call(this, functor.apply(this, arguments)); }); case '[object Object]': return _reduce(function (acc, key) { acc[key] = fn(functor[key]); return acc; }, {}, keys(functor)); default: return _map(fn, functor); } })); /** * ap applies a list of functions to a list of values. * * Dispatches to the `ap` method of the second argument, if present. Also * treats curried functions as applicatives. * * @func * @memberOf R * @since v0.3.0 * @category Function * @sig [a -> b] -> [a] -> [b] * @sig Apply f => f (a -> b) -> f a -> f b * @sig (r -> a -> b) -> (r -> a) -> (r -> b) * @param {*} applyF * @param {*} applyX * @return {*} * @example * * R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] * R.ap([R.concat('tasty '), R.toUpper], ['pizza', 'salad']); //=> ["tasty pizza", "tasty salad", "PIZZA", "SALAD"] * * // R.ap can also be used as S combinator * // when only two functions are passed * R.ap(R.concat, R.toUpper)('Ramda') //=> 'RamdaRAMDA' * @symb R.ap([f, g], [a, b]) = [f(a), f(b), g(a), g(b)] */ var ap = /*#__PURE__*/_curry2(function ap(applyF, applyX) { return typeof applyX['fantasy-land/ap'] === 'function' ? applyX['fantasy-land/ap'](applyF) : typeof applyF.ap === 'function' ? applyF.ap(applyX) : typeof applyF === 'function' ? function (x) { return applyF(x)(applyX(x)); } : _reduce(function (acc, f) { return _concat(acc, map(f, applyX)); }, [], applyF); }); function _isFunction(x) { return Object.prototype.toString.call(x) === '[object Function]'; } /** * "lifts" a function to be the specified arity, so that it may "map over" that * many lists, Functions or other objects that satisfy the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply). * * @func * @memberOf R * @since v0.7.0 * @category Function * @sig Number -> (*... -> *) -> ([*]... -> [*]) * @param {Function} fn The function to lift into higher context * @return {Function} The lifted function. * @see R.lift, R.ap * @example * * const madd3 = R.liftN(3, (...args) => R.sum(args)); * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] */ var liftN = /*#__PURE__*/_curry2(function liftN(arity, fn) { var lifted = curryN(arity, fn); return curryN(arity, function () { return _reduce(ap, map(lifted, arguments[0]), Array.prototype.slice.call(arguments, 1)); }); }); /** * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other * object that satisfies the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply). * * @func * @memberOf R * @since v0.7.0 * @category Function * @sig (*... -> *) -> ([*]... -> [*]) * @param {Function} fn The function to lift into higher context * @return {Function} The lifted function. * @see R.liftN * @example * * const madd3 = R.lift((a, b, c) => a + b + c); * * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] * * const madd5 = R.lift((a, b, c, d, e) => a + b + c + d + e); * * madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24] */ var lift = /*#__PURE__*/_curry1(function lift(fn) { return liftN(fn.length, fn); }); /** * Returns `true` if one or both of its arguments are `true`. Returns `false` * if both arguments are `false`. * * @func * @memberOf R * @since v0.1.0 * @category Logic * @sig a -> b -> a | b * @param {Any} a * @param {Any} b * @return {Any} the first argument if truthy, otherwise the second argument. * @see R.either * @example * * R.or(true, true); //=> true * R.or(true, false); //=> true * R.or(false, true); //=> true * R.or(false, false); //=> false */ var or = /*#__PURE__*/_curry2(function or(a, b) { return a || b; }); /** * A function wrapping calls to the two functions in an `||` operation, * returning the result of the first function if it is truth-y and the result * of the second function otherwise. Note that this is short-circuited, * meaning that the second function will not be invoked if the first returns a * truth-y value. * * In addition to functions, `R.either` also accepts any fantasy-land compatible * applicative functor. * * @func * @memberOf R * @since v0.12.0 * @category Logic * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean) * @param {Function} f a predicate * @param {Function} g another predicate * @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together. * @see R.or * @example * * const gt10 = x => x > 10; * const even = x => x % 2 === 0; * const f = R.either(gt10, even); * f(101); //=> true * f(8); //=> true * * R.either(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(55) * R.either([false, false, 'a'], [11]) // => [11, 11, "a"] */ var either = /*#__PURE__*/_curry2(function either(f, g) { return _isFunction(f) ? function _either() { return f.apply(this, arguments) || g.apply(this, arguments); } : lift(or)(f, g); }); /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Built-in value references. */ var Symbol$1 = root.Symbol; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? getRawTag(value) : objectToString(value); } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Utility function mapping a Rollup config's `external` option into a function. * In Rollup, the `external` config option can be provided as "either a function * that takes an id and returns true (external) or false (not external), or an * Array of module IDs, or regular expressions to match module IDs, that should * remain external to the bundle. Can also be just a single ID or regular * expression." (https://rollupjs.org/guide/en/#external) * * An `external` configuration in string/regexp/array format can be represented * in the function format, but not vice-versa. This utility accepts either format * and returns the function representation such that we can easily retain the user's * configuration while simultaneously appending peer dependencies to it. * * @param {String|RegExp|Array|Function} external The `external` property from Rollup's config. * @returns {Function} Function equivalent of the passed in `external`. */ function externalToFn(external) { if (isFunction(external)) { return external; } else if (typeof external === 'string') { return function (id) { return external === id; }; } else if (external instanceof RegExp) { return function (id) { return external.test(id); }; } else if (Array.isArray(external)) { return function (id) { return external.some(function (module) { return module instanceof RegExp ? module.test(id) : module === id; }); }; } // Per the rollup docs, `undefined` isn't a valid value for the `external` option, // but it has been reported to have been passed in configs starting with 2.11.0. // It's unclear why it's happening so we'll support it for now: // https://github.com/pmowrer/rollup-plugin-peer-deps-external/issues/29 else if (typeof external === 'undefined') { return function () { return false; }; } else { throw new Error("rollup-plugin-peer-deps-external: 'external' option must be a function or an array."); } } /** * Creates a test function from a list of module names. The resulting function * accepts a string id and returns whether it matches a module in the list. * * The string id can be a module name (e.g. `lodash`) or a * "module path" (e.g. `lodash/map`). * * @param {Array} modulesNames Array of module names to match against. * @returns {function(String): (boolean)} Predicate function accepting a string id. */ function getModulesMatcher(modulesNames) { var regexps = modulesNames.map(moduleRegExp); return function (id) { return regexps.some(function (regexp) { return regexp.test(id); }); }; } var moduleRegExp = function moduleRegExp(module) { return new RegExp("^".concat(module, "(\\/.+)*$")); }; var _require = require('path'), resolve = _require.resolve; function getDeps() { var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : resolve(process.cwd(), 'package.json'); var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'peerDependencies'; try { var pkg = require(path); return Object.keys(pkg[type]); } catch (err) { return []; } } function PeerDepsExternalPlugin() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, packageJsonPath = _ref.packageJsonPath, includeDependencies = _ref.includeDependencies; return { name: 'peer-deps-external', options: function options(opts) { opts.external = either( // Retain existing `external` config externalToFn(opts.external), // Add `peerDependencies` to `external` config getModulesMatcher(getDeps(packageJsonPath, 'peerDependencies').concat(includeDependencies ? getDeps(packageJsonPath, 'dependencies') : []))); return opts; } }; } module.exports = PeerDepsExternalPlugin;