// Required for JavaScript engine shells. var global = this; if (typeof console === 'undefined') { console = {log: print}; } /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 681); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _Value = __webpack_require__(586); Object.defineProperty(exports, "Value", { enumerable: true, get: function () { return _interopRequireDefault(_Value).default; } }); var _ConcreteValue = __webpack_require__(1811); Object.defineProperty(exports, "ConcreteValue", { enumerable: true, get: function () { return _interopRequireDefault(_ConcreteValue).default; } }); var _PrimitiveValue = __webpack_require__(587); Object.defineProperty(exports, "PrimitiveValue", { enumerable: true, get: function () { return _interopRequireDefault(_PrimitiveValue).default; } }); var _ObjectValue = __webpack_require__(1812); Object.defineProperty(exports, "ObjectValue", { enumerable: true, get: function () { return _interopRequireDefault(_ObjectValue).default; } }); var _FunctionValue = __webpack_require__(1966); Object.defineProperty(exports, "FunctionValue", { enumerable: true, get: function () { return _interopRequireDefault(_FunctionValue).default; } }); var _ECMAScriptFunctionValue = __webpack_require__(1967); Object.defineProperty(exports, "ECMAScriptFunctionValue", { enumerable: true, get: function () { return _interopRequireDefault(_ECMAScriptFunctionValue).default; } }); var _ECMAScriptSourceFunctionValue = __webpack_require__(1968); Object.defineProperty(exports, "ECMAScriptSourceFunctionValue", { enumerable: true, get: function () { return _interopRequireDefault(_ECMAScriptSourceFunctionValue).default; } }); var _BoundFunctionValue = __webpack_require__(1969); Object.defineProperty(exports, "BoundFunctionValue", { enumerable: true, get: function () { return _interopRequireDefault(_BoundFunctionValue).default; } }); var _NativeFunctionValue = __webpack_require__(1970); Object.defineProperty(exports, "NativeFunctionValue", { enumerable: true, get: function () { return _interopRequireDefault(_NativeFunctionValue).default; } }); Object.defineProperty(exports, "NativeFunctionCallback", { enumerable: true, get: function () { return _NativeFunctionValue.NativeFunctionCallback; } }); var _ArrayValue = __webpack_require__(1971); Object.defineProperty(exports, "ArrayValue", { enumerable: true, get: function () { return _interopRequireDefault(_ArrayValue).default; } }); var _UndefinedValue = __webpack_require__(1972); Object.defineProperty(exports, "UndefinedValue", { enumerable: true, get: function () { return _interopRequireDefault(_UndefinedValue).default; } }); var _EmptyValue = __webpack_require__(1973); Object.defineProperty(exports, "EmptyValue", { enumerable: true, get: function () { return _interopRequireDefault(_EmptyValue).default; } }); var _NullValue = __webpack_require__(1974); Object.defineProperty(exports, "NullValue", { enumerable: true, get: function () { return _interopRequireDefault(_NullValue).default; } }); var _NumberValue = __webpack_require__(1975); Object.defineProperty(exports, "NumberValue", { enumerable: true, get: function () { return _NumberValue.NumberValue; } }); Object.defineProperty(exports, "IntegralValue", { enumerable: true, get: function () { return _NumberValue.IntegralValue; } }); var _ProxyValue = __webpack_require__(1976); Object.defineProperty(exports, "ProxyValue", { enumerable: true, get: function () { return _interopRequireDefault(_ProxyValue).default; } }); var _StringExotic = __webpack_require__(1977); Object.defineProperty(exports, "StringExotic", { enumerable: true, get: function () { return _interopRequireDefault(_StringExotic).default; } }); var _ArgumentsExotic = __webpack_require__(1978); Object.defineProperty(exports, "ArgumentsExotic", { enumerable: true, get: function () { return _interopRequireDefault(_ArgumentsExotic).default; } }); var _IntegerIndexedExotic = __webpack_require__(1979); Object.defineProperty(exports, "IntegerIndexedExotic", { enumerable: true, get: function () { return _interopRequireDefault(_IntegerIndexedExotic).default; } }); var _BooleanValue = __webpack_require__(1980); Object.defineProperty(exports, "BooleanValue", { enumerable: true, get: function () { return _interopRequireDefault(_BooleanValue).default; } }); var _StringValue = __webpack_require__(1981); Object.defineProperty(exports, "StringValue", { enumerable: true, get: function () { return _interopRequireDefault(_StringValue).default; } }); var _SymbolValue = __webpack_require__(1982); Object.defineProperty(exports, "SymbolValue", { enumerable: true, get: function () { return _interopRequireDefault(_SymbolValue).default; } }); var _AbstractValue = __webpack_require__(623); Object.defineProperty(exports, "AbstractValue", { enumerable: true, get: function () { return _interopRequireDefault(_AbstractValue).default; } }); Object.defineProperty(exports, "AbstractValueBuildNodeFunction", { enumerable: true, get: function () { return _AbstractValue.AbstractValueBuildNodeFunction; } }); var _AbstractObjectValue = __webpack_require__(625); Object.defineProperty(exports, "AbstractObjectValue", { enumerable: true, get: function () { return _interopRequireDefault(_AbstractObjectValue).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } //# sourceMappingURL=index.js.map /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = invariant; /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function invariant(condition, format) { if (condition) return; const message = `${format} This is likely a bug in Prepack, not your code. Feel free to open an issue on GitHub.`; let error = new Error(message); error.name = "Invariant Violation"; throw error; } //# sourceMappingURL=invariant.js.map /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setCreate = setCreate; exports.setEnvironment = setEnvironment; exports.setFunctions = setFunctions; exports.setHavoc = setHavoc; exports.setJoin = setJoin; exports.setPath = setPath; exports.setProperties = setProperties; exports.setTo = setTo; exports.setWiden = setWiden; exports.setConcretize = setConcretize; exports.setUtils = setUtils; let Create = exports.Create = null; /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ let Environment = exports.Environment = null; let Functions = exports.Functions = null; let Havoc = exports.Havoc = null; let Join = exports.Join = null; let Path = exports.Path = null; let Properties = exports.Properties = null; let To = exports.To = null; let Widen = exports.Widen = null; let concretize = exports.concretize = null; let Utils = exports.Utils = null; function setCreate(singleton) { exports.Create = Create = singleton; } function setEnvironment(singleton) { exports.Environment = Environment = singleton; } function setFunctions(singleton) { exports.Functions = Functions = singleton; } function setHavoc(singleton) { exports.Havoc = Havoc = singleton; } function setJoin(singleton) { exports.Join = Join = singleton; } function setPath(singleton) { exports.Path = Path = singleton; } function setProperties(singleton) { exports.Properties = Properties = singleton; } function setTo(singleton) { exports.To = To = singleton; } function setWiden(singleton) { exports.Widen = Widen = singleton; } function setConcretize(singleton) { exports.concretize = concretize = singleton; } function setUtils(singleton) { exports.Utils = Utils = singleton; } //# sourceMappingURL=singletons.js.map /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PossiblyNormalCompletion = exports.JoinedAbruptCompletions = exports.ReturnCompletion = exports.BreakCompletion = exports.ContinueCompletion = exports.ThrowCompletion = exports.AbruptCompletion = exports.NormalCompletion = exports.Completion = undefined; var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _index = __webpack_require__(0); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class Completion { constructor(value, location, target) { this.value = value; this.target = target; this.location = location; } } exports.Completion = Completion; // Normal completions are returned just like spec completions /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ class NormalCompletion extends Completion {} exports.NormalCompletion = NormalCompletion; // Abrupt completions are thrown as exeptions, to make it a easier // to quickly get to the matching high level construct. class AbruptCompletion extends Completion {} exports.AbruptCompletion = AbruptCompletion; class ThrowCompletion extends AbruptCompletion { constructor(value, location, nativeStack) { super(value, location); this.nativeStack = nativeStack || new Error().stack; } } exports.ThrowCompletion = ThrowCompletion; class ContinueCompletion extends AbruptCompletion { constructor(value, location, target) { super(value, location, target); } } exports.ContinueCompletion = ContinueCompletion; class BreakCompletion extends AbruptCompletion { constructor(value, location, target) { super(value, location, target); } } exports.BreakCompletion = BreakCompletion; class ReturnCompletion extends AbruptCompletion { constructor(value, location) { super(value, location); } } exports.ReturnCompletion = ReturnCompletion; class JoinedAbruptCompletions extends AbruptCompletion { constructor(realm, joinCondition, consequent, consequentEffects, alternate, alternateEffects) { super(realm.intrinsics.empty, consequent.location); this.joinCondition = joinCondition; this.consequent = consequent; this.consequentEffects = consequentEffects; this.alternate = alternate; this.alternateEffects = alternateEffects; } containsBreakOrContinue() { if (this.consequent instanceof BreakCompletion || this.consequent instanceof ContinueCompletion) return true; if (this.alternate instanceof BreakCompletion || this.alternate instanceof ContinueCompletion) return true; if (this.consequent instanceof JoinedAbruptCompletions) { if (this.consequent.containsBreakOrContinue()) return true; } if (this.alternate instanceof JoinedAbruptCompletions) { if (this.alternate.containsBreakOrContinue()) return true; } return false; } } exports.JoinedAbruptCompletions = JoinedAbruptCompletions; // Possibly normal completions have to be treated like normal completions // and are thus never thrown. At the end of a try block or loop body, however, // action must be taken to deal with the possibly abrupt case of the completion. class PossiblyNormalCompletion extends NormalCompletion { constructor(value, joinCondition, consequent, consequentEffects, alternate, alternateEffects, pathConditions, savedPathConditions, savedEffects = undefined) { (0, _invariant2.default)(consequent === consequentEffects[0]); (0, _invariant2.default)(alternate === alternateEffects[0]); (0, _invariant2.default)(consequent instanceof NormalCompletion || consequent instanceof _index.Value || alternate instanceof NormalCompletion || alternate instanceof _index.Value); (0, _invariant2.default)(consequent instanceof AbruptCompletion || alternate instanceof AbruptCompletion); (0, _invariant2.default)(value === consequent || consequent instanceof AbruptCompletion || consequent instanceof NormalCompletion && value === consequent.value); (0, _invariant2.default)(value === alternate || alternate instanceof AbruptCompletion || alternate instanceof NormalCompletion && value === alternate.value); let loc = consequent instanceof AbruptCompletion ? consequent.location : alternate instanceof Completion ? alternate.location : alternate.expressionLocation; super(value, loc); this.joinCondition = joinCondition; this.consequent = consequent; this.consequentEffects = consequentEffects; this.alternate = alternate; this.alternateEffects = alternateEffects; this.savedEffects = savedEffects; this.pathConditions = pathConditions; this.savedPathConditions = savedPathConditions; } containsBreakOrContinue() { if (this.consequent instanceof BreakCompletion || this.consequent instanceof ContinueCompletion) return true; if (this.alternate instanceof BreakCompletion || this.alternate instanceof ContinueCompletion) return true; if (this.consequent instanceof JoinedAbruptCompletions || this.consequent instanceof PossiblyNormalCompletion) { if (this.consequent.containsBreakOrContinue()) return true; } if (this.alternate instanceof JoinedAbruptCompletions || this.alternate instanceof PossiblyNormalCompletion) { if (this.alternate.containsBreakOrContinue()) return true; } return false; } } exports.PossiblyNormalCompletion = PossiblyNormalCompletion; //# sourceMappingURL=completions.js.map /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.createTypeAnnotationBasedOnTypeof = exports.removeTypeDuplicates = exports.createUnionTypeAnnotation = exports.valueToNode = exports.toBlock = exports.toExpression = exports.toStatement = exports.toBindingIdentifierName = exports.toIdentifier = exports.toKeyAlias = exports.toSequenceExpression = exports.toComputedKey = exports.isNodesEquivalent = exports.isImmutable = exports.isScope = exports.isSpecifierDefault = exports.isVar = exports.isBlockScoped = exports.isLet = exports.isValidIdentifier = exports.isReferenced = exports.isBinding = exports.getOuterBindingIdentifiers = exports.getBindingIdentifiers = exports.TYPES = exports.react = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; var _getOwnPropertySymbols = __webpack_require__(1875); var _getOwnPropertySymbols2 = _interopRequireDefault(_getOwnPropertySymbols); var _getIterator2 = __webpack_require__(21); var _getIterator3 = _interopRequireDefault(_getIterator2); var _keys = __webpack_require__(123); var _keys2 = _interopRequireDefault(_keys); var _stringify = __webpack_require__(158); var _stringify2 = _interopRequireDefault(_stringify); var _constants = __webpack_require__(319); Object.defineProperty(exports, "STATEMENT_OR_BLOCK_KEYS", { enumerable: true, get: function get() { return _constants.STATEMENT_OR_BLOCK_KEYS; } }); Object.defineProperty(exports, "FLATTENABLE_KEYS", { enumerable: true, get: function get() { return _constants.FLATTENABLE_KEYS; } }); Object.defineProperty(exports, "FOR_INIT_KEYS", { enumerable: true, get: function get() { return _constants.FOR_INIT_KEYS; } }); Object.defineProperty(exports, "COMMENT_KEYS", { enumerable: true, get: function get() { return _constants.COMMENT_KEYS; } }); Object.defineProperty(exports, "LOGICAL_OPERATORS", { enumerable: true, get: function get() { return _constants.LOGICAL_OPERATORS; } }); Object.defineProperty(exports, "UPDATE_OPERATORS", { enumerable: true, get: function get() { return _constants.UPDATE_OPERATORS; } }); Object.defineProperty(exports, "BOOLEAN_NUMBER_BINARY_OPERATORS", { enumerable: true, get: function get() { return _constants.BOOLEAN_NUMBER_BINARY_OPERATORS; } }); Object.defineProperty(exports, "EQUALITY_BINARY_OPERATORS", { enumerable: true, get: function get() { return _constants.EQUALITY_BINARY_OPERATORS; } }); Object.defineProperty(exports, "COMPARISON_BINARY_OPERATORS", { enumerable: true, get: function get() { return _constants.COMPARISON_BINARY_OPERATORS; } }); Object.defineProperty(exports, "BOOLEAN_BINARY_OPERATORS", { enumerable: true, get: function get() { return _constants.BOOLEAN_BINARY_OPERATORS; } }); Object.defineProperty(exports, "NUMBER_BINARY_OPERATORS", { enumerable: true, get: function get() { return _constants.NUMBER_BINARY_OPERATORS; } }); Object.defineProperty(exports, "BINARY_OPERATORS", { enumerable: true, get: function get() { return _constants.BINARY_OPERATORS; } }); Object.defineProperty(exports, "BOOLEAN_UNARY_OPERATORS", { enumerable: true, get: function get() { return _constants.BOOLEAN_UNARY_OPERATORS; } }); Object.defineProperty(exports, "NUMBER_UNARY_OPERATORS", { enumerable: true, get: function get() { return _constants.NUMBER_UNARY_OPERATORS; } }); Object.defineProperty(exports, "STRING_UNARY_OPERATORS", { enumerable: true, get: function get() { return _constants.STRING_UNARY_OPERATORS; } }); Object.defineProperty(exports, "UNARY_OPERATORS", { enumerable: true, get: function get() { return _constants.UNARY_OPERATORS; } }); Object.defineProperty(exports, "INHERIT_KEYS", { enumerable: true, get: function get() { return _constants.INHERIT_KEYS; } }); Object.defineProperty(exports, "BLOCK_SCOPED_SYMBOL", { enumerable: true, get: function get() { return _constants.BLOCK_SCOPED_SYMBOL; } }); Object.defineProperty(exports, "NOT_LOCAL_BINDING", { enumerable: true, get: function get() { return _constants.NOT_LOCAL_BINDING; } }); exports.is = is; exports.isType = isType; exports.validate = validate; exports.shallowEqual = shallowEqual; exports.appendToMemberExpression = appendToMemberExpression; exports.prependToMemberExpression = prependToMemberExpression; exports.ensureBlock = ensureBlock; exports.clone = clone; exports.cloneWithoutLoc = cloneWithoutLoc; exports.cloneDeep = cloneDeep; exports.buildMatchMemberExpression = buildMatchMemberExpression; exports.removeComments = removeComments; exports.inheritsComments = inheritsComments; exports.inheritTrailingComments = inheritTrailingComments; exports.inheritLeadingComments = inheritLeadingComments; exports.inheritInnerComments = inheritInnerComments; exports.inherits = inherits; exports.assertNode = assertNode; exports.isNode = isNode; exports.traverseFast = traverseFast; exports.removeProperties = removeProperties; exports.removePropertiesDeep = removePropertiesDeep; var _retrievers = __webpack_require__(608); Object.defineProperty(exports, "getBindingIdentifiers", { enumerable: true, get: function get() { return _retrievers.getBindingIdentifiers; } }); Object.defineProperty(exports, "getOuterBindingIdentifiers", { enumerable: true, get: function get() { return _retrievers.getOuterBindingIdentifiers; } }); var _validators = __webpack_require__(1879); Object.defineProperty(exports, "isBinding", { enumerable: true, get: function get() { return _validators.isBinding; } }); Object.defineProperty(exports, "isReferenced", { enumerable: true, get: function get() { return _validators.isReferenced; } }); Object.defineProperty(exports, "isValidIdentifier", { enumerable: true, get: function get() { return _validators.isValidIdentifier; } }); Object.defineProperty(exports, "isLet", { enumerable: true, get: function get() { return _validators.isLet; } }); Object.defineProperty(exports, "isBlockScoped", { enumerable: true, get: function get() { return _validators.isBlockScoped; } }); Object.defineProperty(exports, "isVar", { enumerable: true, get: function get() { return _validators.isVar; } }); Object.defineProperty(exports, "isSpecifierDefault", { enumerable: true, get: function get() { return _validators.isSpecifierDefault; } }); Object.defineProperty(exports, "isScope", { enumerable: true, get: function get() { return _validators.isScope; } }); Object.defineProperty(exports, "isImmutable", { enumerable: true, get: function get() { return _validators.isImmutable; } }); Object.defineProperty(exports, "isNodesEquivalent", { enumerable: true, get: function get() { return _validators.isNodesEquivalent; } }); var _converters = __webpack_require__(1880); Object.defineProperty(exports, "toComputedKey", { enumerable: true, get: function get() { return _converters.toComputedKey; } }); Object.defineProperty(exports, "toSequenceExpression", { enumerable: true, get: function get() { return _converters.toSequenceExpression; } }); Object.defineProperty(exports, "toKeyAlias", { enumerable: true, get: function get() { return _converters.toKeyAlias; } }); Object.defineProperty(exports, "toIdentifier", { enumerable: true, get: function get() { return _converters.toIdentifier; } }); Object.defineProperty(exports, "toBindingIdentifierName", { enumerable: true, get: function get() { return _converters.toBindingIdentifierName; } }); Object.defineProperty(exports, "toStatement", { enumerable: true, get: function get() { return _converters.toStatement; } }); Object.defineProperty(exports, "toExpression", { enumerable: true, get: function get() { return _converters.toExpression; } }); Object.defineProperty(exports, "toBlock", { enumerable: true, get: function get() { return _converters.toBlock; } }); Object.defineProperty(exports, "valueToNode", { enumerable: true, get: function get() { return _converters.valueToNode; } }); var _flow = __webpack_require__(1884); Object.defineProperty(exports, "createUnionTypeAnnotation", { enumerable: true, get: function get() { return _flow.createUnionTypeAnnotation; } }); Object.defineProperty(exports, "removeTypeDuplicates", { enumerable: true, get: function get() { return _flow.removeTypeDuplicates; } }); Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { enumerable: true, get: function get() { return _flow.createTypeAnnotationBasedOnTypeof; } }); var _toFastProperties = __webpack_require__(1885); var _toFastProperties2 = _interopRequireDefault(_toFastProperties); var _clone = __webpack_require__(176); var _clone2 = _interopRequireDefault(_clone); var _uniq = __webpack_require__(372); var _uniq2 = _interopRequireDefault(_uniq); __webpack_require__(1886); var _definitions = __webpack_require__(88); var _react2 = __webpack_require__(1893); var _react = _interopRequireWildcard(_react2); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var t = exports; function registerType(type) { var is = t["is" + type]; if (!is) { is = t["is" + type] = function (node, opts) { return t.is(type, node, opts); }; } t["assert" + type] = function (node, opts) { opts = opts || {}; if (!is(node, opts)) { throw new Error("Expected type " + (0, _stringify2.default)(type) + " with option " + (0, _stringify2.default)(opts)); } }; } exports.VISITOR_KEYS = _definitions.VISITOR_KEYS; exports.ALIAS_KEYS = _definitions.ALIAS_KEYS; exports.NODE_FIELDS = _definitions.NODE_FIELDS; exports.BUILDER_KEYS = _definitions.BUILDER_KEYS; exports.DEPRECATED_KEYS = _definitions.DEPRECATED_KEYS; exports.react = _react; for (var type in t.VISITOR_KEYS) { registerType(type); } t.FLIPPED_ALIAS_KEYS = {}; (0, _keys2.default)(t.ALIAS_KEYS).forEach(function (type) { t.ALIAS_KEYS[type].forEach(function (alias) { var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; types.push(type); }); }); (0, _keys2.default)(t.FLIPPED_ALIAS_KEYS).forEach(function (type) { t[type.toUpperCase() + "_TYPES"] = t.FLIPPED_ALIAS_KEYS[type]; registerType(type); }); var TYPES = exports.TYPES = (0, _keys2.default)(t.VISITOR_KEYS).concat((0, _keys2.default)(t.FLIPPED_ALIAS_KEYS)).concat((0, _keys2.default)(t.DEPRECATED_KEYS)); function is(type, node, opts) { if (!node) return false; var matches = isType(node.type, type); if (!matches) return false; if (typeof opts === "undefined") { return true; } else { return t.shallowEqual(node, opts); } } function isType(nodeType, targetType) { if (nodeType === targetType) return true; if (t.ALIAS_KEYS[targetType]) return false; var aliases = t.FLIPPED_ALIAS_KEYS[targetType]; if (aliases) { if (aliases[0] === nodeType) return true; for (var _iterator = aliases, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var alias = _ref; if (nodeType === alias) return true; } } return false; } (0, _keys2.default)(t.BUILDER_KEYS).forEach(function (type) { var keys = t.BUILDER_KEYS[type]; function builder() { if (arguments.length > keys.length) { throw new Error("t." + type + ": Too many arguments passed. Received " + arguments.length + " but can receive " + ("no more than " + keys.length)); } var node = {}; node.type = type; var i = 0; for (var _iterator2 = keys, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var _key = _ref2; var field = t.NODE_FIELDS[type][_key]; var arg = arguments[i++]; if (arg === undefined) arg = (0, _clone2.default)(field.default); node[_key] = arg; } for (var key in node) { validate(node, key, node[key]); } return node; } t[type] = builder; t[type[0].toLowerCase() + type.slice(1)] = builder; }); var _loop = function _loop(_type) { var newType = t.DEPRECATED_KEYS[_type]; function proxy(fn) { return function () { console.trace("The node type " + _type + " has been renamed to " + newType); return fn.apply(this, arguments); }; } t[_type] = t[_type[0].toLowerCase() + _type.slice(1)] = proxy(t[newType]); t["is" + _type] = proxy(t["is" + newType]); t["assert" + _type] = proxy(t["assert" + newType]); }; for (var _type in t.DEPRECATED_KEYS) { _loop(_type); } function validate(node, key, val) { if (!node) return; var fields = t.NODE_FIELDS[node.type]; if (!fields) return; var field = fields[key]; if (!field || !field.validate) return; if (field.optional && val == null) return; field.validate(node, key, val); } function shallowEqual(actual, expected) { var keys = (0, _keys2.default)(expected); for (var _iterator3 = keys, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { var _ref3; if (_isArray3) { if (_i3 >= _iterator3.length) break; _ref3 = _iterator3[_i3++]; } else { _i3 = _iterator3.next(); if (_i3.done) break; _ref3 = _i3.value; } var key = _ref3; if (actual[key] !== expected[key]) { return false; } } return true; } function appendToMemberExpression(member, append, computed) { member.object = t.memberExpression(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; } function prependToMemberExpression(member, prepend) { member.object = t.memberExpression(prepend, member.object); return member; } function ensureBlock(node) { var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "body"; return node[key] = t.toBlock(node[key], node); } function clone(node) { if (!node) return node; var newNode = {}; for (var key in node) { if (key[0] === "_") continue; newNode[key] = node[key]; } return newNode; } function cloneWithoutLoc(node) { var newNode = clone(node); delete newNode.loc; return newNode; } function cloneDeep(node) { if (!node) return node; var newNode = {}; for (var key in node) { if (key[0] === "_") continue; var val = node[key]; if (val) { if (val.type) { val = t.cloneDeep(val); } else if (Array.isArray(val)) { val = val.map(t.cloneDeep); } } newNode[key] = val; } return newNode; } function buildMatchMemberExpression(match, allowPartial) { var parts = match.split("."); return function (member) { if (!t.isMemberExpression(member)) return false; var search = [member]; var i = 0; while (search.length) { var node = search.shift(); if (allowPartial && i === parts.length) { return true; } if (t.isIdentifier(node)) { if (parts[i] !== node.name) return false; } else if (t.isStringLiteral(node)) { if (parts[i] !== node.value) return false; } else if (t.isMemberExpression(node)) { if (node.computed && !t.isStringLiteral(node.property)) { return false; } else { search.push(node.object); search.push(node.property); continue; } } else { return false; } if (++i > parts.length) { return false; } } return true; }; } function removeComments(node) { for (var _iterator4 = t.COMMENT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { var _ref4; if (_isArray4) { if (_i4 >= _iterator4.length) break; _ref4 = _iterator4[_i4++]; } else { _i4 = _iterator4.next(); if (_i4.done) break; _ref4 = _i4.value; } var key = _ref4; delete node[key]; } return node; } function inheritsComments(child, parent) { inheritTrailingComments(child, parent); inheritLeadingComments(child, parent); inheritInnerComments(child, parent); return child; } function inheritTrailingComments(child, parent) { _inheritComments("trailingComments", child, parent); } function inheritLeadingComments(child, parent) { _inheritComments("leadingComments", child, parent); } function inheritInnerComments(child, parent) { _inheritComments("innerComments", child, parent); } function _inheritComments(key, child, parent) { if (child && parent) { child[key] = (0, _uniq2.default)([].concat(child[key], parent[key]).filter(Boolean)); } } function inherits(child, parent) { if (!child || !parent) return child; for (var _iterator5 = t.INHERIT_KEYS.optional, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { var _ref5; if (_isArray5) { if (_i5 >= _iterator5.length) break; _ref5 = _iterator5[_i5++]; } else { _i5 = _iterator5.next(); if (_i5.done) break; _ref5 = _i5.value; } var _key2 = _ref5; if (child[_key2] == null) { child[_key2] = parent[_key2]; } } for (var key in parent) { if (key[0] === "_") child[key] = parent[key]; } for (var _iterator6 = t.INHERIT_KEYS.force, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { var _ref6; if (_isArray6) { if (_i6 >= _iterator6.length) break; _ref6 = _iterator6[_i6++]; } else { _i6 = _iterator6.next(); if (_i6.done) break; _ref6 = _i6.value; } var _key3 = _ref6; child[_key3] = parent[_key3]; } t.inheritsComments(child, parent); return child; } function assertNode(node) { if (!isNode(node)) { throw new TypeError("Not a valid node " + (node && node.type)); } } function isNode(node) { return !!(node && _definitions.VISITOR_KEYS[node.type]); } (0, _toFastProperties2.default)(t); (0, _toFastProperties2.default)(t.VISITOR_KEYS); function traverseFast(node, enter, opts) { if (!node) return; var keys = t.VISITOR_KEYS[node.type]; if (!keys) return; opts = opts || {}; enter(node, opts); for (var _iterator7 = keys, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { var _ref7; if (_isArray7) { if (_i7 >= _iterator7.length) break; _ref7 = _iterator7[_i7++]; } else { _i7 = _iterator7.next(); if (_i7.done) break; _ref7 = _i7.value; } var key = _ref7; var subNode = node[key]; if (Array.isArray(subNode)) { for (var _iterator8 = subNode, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { var _ref8; if (_isArray8) { if (_i8 >= _iterator8.length) break; _ref8 = _iterator8[_i8++]; } else { _i8 = _iterator8.next(); if (_i8.done) break; _ref8 = _i8.value; } var _node = _ref8; traverseFast(_node, enter, opts); } } else { traverseFast(subNode, enter, opts); } } } var CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; var CLEAR_KEYS_PLUS_COMMENTS = t.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS); function removeProperties(node, opts) { opts = opts || {}; var map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; for (var _iterator9 = map, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { var _ref9; if (_isArray9) { if (_i9 >= _iterator9.length) break; _ref9 = _iterator9[_i9++]; } else { _i9 = _iterator9.next(); if (_i9.done) break; _ref9 = _i9.value; } var _key4 = _ref9; if (node[_key4] != null) node[_key4] = undefined; } for (var key in node) { if (key[0] === "_" && node[key] != null) node[key] = undefined; } var syms = (0, _getOwnPropertySymbols2.default)(node); for (var _iterator10 = syms, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { var _ref10; if (_isArray10) { if (_i10 >= _iterator10.length) break; _ref10 = _iterator10[_i10++]; } else { _i10 = _iterator10.next(); if (_i10.done) break; _ref10 = _i10.value; } var sym = _ref10; node[sym] = null; } } function removePropertiesDeep(tree, opts) { traverseFast(tree, removeProperties, opts); return tree; } /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _abstract = __webpack_require__(29); Object.keys(_abstract).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _abstract[key]; } }); }); var _call = __webpack_require__(30); Object.keys(_call).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _call[key]; } }); }); var _construct = __webpack_require__(52); Object.keys(_construct).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _construct[key]; } }); }); var _date = __webpack_require__(611); Object.keys(_date).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _date[key]; } }); }); var _descriptor = __webpack_require__(1906); Object.keys(_descriptor).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _descriptor[key]; } }); }); var _get = __webpack_require__(19); Object.keys(_get).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _get[key]; } }); }); var _has = __webpack_require__(42); Object.keys(_has).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _has[key]; } }); }); var _hash = __webpack_require__(1907); Object.keys(_hash).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _hash[key]; } }); }); var _integrity = __webpack_require__(609); Object.keys(_integrity).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _integrity[key]; } }); }); var _is = __webpack_require__(16); Object.keys(_is).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _is[key]; } }); }); var _iterator = __webpack_require__(100); Object.keys(_iterator).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _iterator[key]; } }); }); var _own = __webpack_require__(612); Object.keys(_own).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _own[key]; } }); }); var _destructuring = __webpack_require__(1908); Object.keys(_destructuring).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _destructuring[key]; } }); }); var _regexp = __webpack_require__(225); Object.keys(_regexp).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _regexp[key]; } }); }); var _promise = __webpack_require__(321); Object.keys(_promise).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _promise[key]; } }); }); var _arraybuffer = __webpack_require__(124); Object.keys(_arraybuffer).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _arraybuffer[key]; } }); }); //# sourceMappingURL=index.js.map /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // This is the error format used to report errors to the caller-supplied // error-handler /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ class CompilerDiagnostic extends Error { constructor(message, location, errorCode, severity) { super(message); this.location = location; this.severity = severity; this.errorCode = errorCode; } } exports.CompilerDiagnostic = CompilerDiagnostic; // This error is thrown to exit Prepack when an ErrorHandler returns 'FatalError' // This should just be a class but Babel classes doesn't work with // built-in super classes. class FatalError extends Error { constructor(message) { super(message || "A fatal error occurred while prepacking."); } } exports.FatalError = FatalError; //# sourceMappingURL=errors.js.map /***/ }), /* 7 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /* 8 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { react: true, assertNode: true, createTypeAnnotationBasedOnTypeof: true, createUnionTypeAnnotation: true, cloneNode: true, clone: true, cloneDeep: true, cloneWithoutLoc: true, addComment: true, addComments: true, inheritInnerComments: true, inheritLeadingComments: true, inheritsComments: true, inheritTrailingComments: true, removeComments: true, ensureBlock: true, toBindingIdentifierName: true, toBlock: true, toComputedKey: true, toExpression: true, toIdentifier: true, toKeyAlias: true, toSequenceExpression: true, toStatement: true, valueToNode: true, appendToMemberExpression: true, inherits: true, prependToMemberExpression: true, removeProperties: true, removePropertiesDeep: true, removeTypeDuplicates: true, getBindingIdentifiers: true, getOuterBindingIdentifiers: true, traverse: true, traverseFast: true, shallowEqual: true, is: true, isBinding: true, isBlockScoped: true, isImmutable: true, isLet: true, isNode: true, isNodesEquivalent: true, isReferenced: true, isScope: true, isSpecifierDefault: true, isType: true, isValidES3Identifier: true, isValidIdentifier: true, isVar: true, matchesPattern: true, validate: true, buildMatchMemberExpression: true }; Object.defineProperty(exports, "assertNode", { enumerable: true, get: function () { return _assertNode.default; } }); Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { enumerable: true, get: function () { return _createTypeAnnotationBasedOnTypeof.default; } }); Object.defineProperty(exports, "createUnionTypeAnnotation", { enumerable: true, get: function () { return _createUnionTypeAnnotation.default; } }); Object.defineProperty(exports, "cloneNode", { enumerable: true, get: function () { return _cloneNode.default; } }); Object.defineProperty(exports, "clone", { enumerable: true, get: function () { return _clone.default; } }); Object.defineProperty(exports, "cloneDeep", { enumerable: true, get: function () { return _cloneDeep.default; } }); Object.defineProperty(exports, "cloneWithoutLoc", { enumerable: true, get: function () { return _cloneWithoutLoc.default; } }); Object.defineProperty(exports, "addComment", { enumerable: true, get: function () { return _addComment.default; } }); Object.defineProperty(exports, "addComments", { enumerable: true, get: function () { return _addComments.default; } }); Object.defineProperty(exports, "inheritInnerComments", { enumerable: true, get: function () { return _inheritInnerComments.default; } }); Object.defineProperty(exports, "inheritLeadingComments", { enumerable: true, get: function () { return _inheritLeadingComments.default; } }); Object.defineProperty(exports, "inheritsComments", { enumerable: true, get: function () { return _inheritsComments.default; } }); Object.defineProperty(exports, "inheritTrailingComments", { enumerable: true, get: function () { return _inheritTrailingComments.default; } }); Object.defineProperty(exports, "removeComments", { enumerable: true, get: function () { return _removeComments.default; } }); Object.defineProperty(exports, "ensureBlock", { enumerable: true, get: function () { return _ensureBlock.default; } }); Object.defineProperty(exports, "toBindingIdentifierName", { enumerable: true, get: function () { return _toBindingIdentifierName.default; } }); Object.defineProperty(exports, "toBlock", { enumerable: true, get: function () { return _toBlock.default; } }); Object.defineProperty(exports, "toComputedKey", { enumerable: true, get: function () { return _toComputedKey.default; } }); Object.defineProperty(exports, "toExpression", { enumerable: true, get: function () { return _toExpression.default; } }); Object.defineProperty(exports, "toIdentifier", { enumerable: true, get: function () { return _toIdentifier.default; } }); Object.defineProperty(exports, "toKeyAlias", { enumerable: true, get: function () { return _toKeyAlias.default; } }); Object.defineProperty(exports, "toSequenceExpression", { enumerable: true, get: function () { return _toSequenceExpression.default; } }); Object.defineProperty(exports, "toStatement", { enumerable: true, get: function () { return _toStatement.default; } }); Object.defineProperty(exports, "valueToNode", { enumerable: true, get: function () { return _valueToNode.default; } }); Object.defineProperty(exports, "appendToMemberExpression", { enumerable: true, get: function () { return _appendToMemberExpression.default; } }); Object.defineProperty(exports, "inherits", { enumerable: true, get: function () { return _inherits.default; } }); Object.defineProperty(exports, "prependToMemberExpression", { enumerable: true, get: function () { return _prependToMemberExpression.default; } }); Object.defineProperty(exports, "removeProperties", { enumerable: true, get: function () { return _removeProperties.default; } }); Object.defineProperty(exports, "removePropertiesDeep", { enumerable: true, get: function () { return _removePropertiesDeep.default; } }); Object.defineProperty(exports, "removeTypeDuplicates", { enumerable: true, get: function () { return _removeTypeDuplicates.default; } }); Object.defineProperty(exports, "getBindingIdentifiers", { enumerable: true, get: function () { return _getBindingIdentifiers.default; } }); Object.defineProperty(exports, "getOuterBindingIdentifiers", { enumerable: true, get: function () { return _getOuterBindingIdentifiers.default; } }); Object.defineProperty(exports, "traverse", { enumerable: true, get: function () { return _traverse.default; } }); Object.defineProperty(exports, "traverseFast", { enumerable: true, get: function () { return _traverseFast.default; } }); Object.defineProperty(exports, "shallowEqual", { enumerable: true, get: function () { return _shallowEqual.default; } }); Object.defineProperty(exports, "is", { enumerable: true, get: function () { return _is.default; } }); Object.defineProperty(exports, "isBinding", { enumerable: true, get: function () { return _isBinding.default; } }); Object.defineProperty(exports, "isBlockScoped", { enumerable: true, get: function () { return _isBlockScoped.default; } }); Object.defineProperty(exports, "isImmutable", { enumerable: true, get: function () { return _isImmutable.default; } }); Object.defineProperty(exports, "isLet", { enumerable: true, get: function () { return _isLet.default; } }); Object.defineProperty(exports, "isNode", { enumerable: true, get: function () { return _isNode.default; } }); Object.defineProperty(exports, "isNodesEquivalent", { enumerable: true, get: function () { return _isNodesEquivalent.default; } }); Object.defineProperty(exports, "isReferenced", { enumerable: true, get: function () { return _isReferenced.default; } }); Object.defineProperty(exports, "isScope", { enumerable: true, get: function () { return _isScope.default; } }); Object.defineProperty(exports, "isSpecifierDefault", { enumerable: true, get: function () { return _isSpecifierDefault.default; } }); Object.defineProperty(exports, "isType", { enumerable: true, get: function () { return _isType.default; } }); Object.defineProperty(exports, "isValidES3Identifier", { enumerable: true, get: function () { return _isValidES3Identifier.default; } }); Object.defineProperty(exports, "isValidIdentifier", { enumerable: true, get: function () { return _isValidIdentifier.default; } }); Object.defineProperty(exports, "isVar", { enumerable: true, get: function () { return _isVar.default; } }); Object.defineProperty(exports, "matchesPattern", { enumerable: true, get: function () { return _matchesPattern.default; } }); Object.defineProperty(exports, "validate", { enumerable: true, get: function () { return _validate.default; } }); Object.defineProperty(exports, "buildMatchMemberExpression", { enumerable: true, get: function () { return _buildMatchMemberExpression.default; } }); exports.react = void 0; var _isReactComponent = _interopRequireDefault(__webpack_require__(724)); var _isCompatTag = _interopRequireDefault(__webpack_require__(725)); var _buildChildren = _interopRequireDefault(__webpack_require__(726)); var _assertNode = _interopRequireDefault(__webpack_require__(797)); var _generated = __webpack_require__(798); Object.keys(_generated).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _generated[key]; } }); }); var _createTypeAnnotationBasedOnTypeof = _interopRequireDefault(__webpack_require__(799)); var _createUnionTypeAnnotation = _interopRequireDefault(__webpack_require__(800)); var _generated2 = __webpack_require__(44); Object.keys(_generated2).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _generated2[key]; } }); }); var _cloneNode = _interopRequireDefault(__webpack_require__(134)); var _clone = _interopRequireDefault(__webpack_require__(369)); var _cloneDeep = _interopRequireDefault(__webpack_require__(801)); var _cloneWithoutLoc = _interopRequireDefault(__webpack_require__(802)); var _addComment = _interopRequireDefault(__webpack_require__(803)); var _addComments = _interopRequireDefault(__webpack_require__(370)); var _inheritInnerComments = _interopRequireDefault(__webpack_require__(371)); var _inheritLeadingComments = _interopRequireDefault(__webpack_require__(376)); var _inheritsComments = _interopRequireDefault(__webpack_require__(377)); var _inheritTrailingComments = _interopRequireDefault(__webpack_require__(378)); var _removeComments = _interopRequireDefault(__webpack_require__(813)); var _generated3 = __webpack_require__(814); Object.keys(_generated3).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _generated3[key]; } }); }); var _constants = __webpack_require__(93); Object.keys(_constants).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _constants[key]; } }); }); var _ensureBlock = _interopRequireDefault(__webpack_require__(815)); var _toBindingIdentifierName = _interopRequireDefault(__webpack_require__(816)); var _toBlock = _interopRequireDefault(__webpack_require__(379)); var _toComputedKey = _interopRequireDefault(__webpack_require__(817)); var _toExpression = _interopRequireDefault(__webpack_require__(818)); var _toIdentifier = _interopRequireDefault(__webpack_require__(380)); var _toKeyAlias = _interopRequireDefault(__webpack_require__(819)); var _toSequenceExpression = _interopRequireDefault(__webpack_require__(820)); var _toStatement = _interopRequireDefault(__webpack_require__(822)); var _valueToNode = _interopRequireDefault(__webpack_require__(823)); var _definitions = __webpack_require__(57); Object.keys(_definitions).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _definitions[key]; } }); }); var _appendToMemberExpression = _interopRequireDefault(__webpack_require__(825)); var _inherits = _interopRequireDefault(__webpack_require__(826)); var _prependToMemberExpression = _interopRequireDefault(__webpack_require__(827)); var _removeProperties = _interopRequireDefault(__webpack_require__(383)); var _removePropertiesDeep = _interopRequireDefault(__webpack_require__(381)); var _removeTypeDuplicates = _interopRequireDefault(__webpack_require__(368)); var _getBindingIdentifiers = _interopRequireDefault(__webpack_require__(184)); var _getOuterBindingIdentifiers = _interopRequireDefault(__webpack_require__(828)); var _traverse = _interopRequireDefault(__webpack_require__(829)); var _traverseFast = _interopRequireDefault(__webpack_require__(382)); var _shallowEqual = _interopRequireDefault(__webpack_require__(235)); var _is = _interopRequireDefault(__webpack_require__(250)); var _isBinding = _interopRequireDefault(__webpack_require__(830)); var _isBlockScoped = _interopRequireDefault(__webpack_require__(831)); var _isImmutable = _interopRequireDefault(__webpack_require__(832)); var _isLet = _interopRequireDefault(__webpack_require__(386)); var _isNode = _interopRequireDefault(__webpack_require__(367)); var _isNodesEquivalent = _interopRequireDefault(__webpack_require__(833)); var _isReferenced = _interopRequireDefault(__webpack_require__(834)); var _isScope = _interopRequireDefault(__webpack_require__(835)); var _isSpecifierDefault = _interopRequireDefault(__webpack_require__(836)); var _isType = _interopRequireDefault(__webpack_require__(251)); var _isValidES3Identifier = _interopRequireDefault(__webpack_require__(837)); var _isValidIdentifier = _interopRequireDefault(__webpack_require__(132)); var _isVar = _interopRequireDefault(__webpack_require__(838)); var _matchesPattern = _interopRequireDefault(__webpack_require__(349)); var _validate = _interopRequireDefault(__webpack_require__(366)); var _buildMatchMemberExpression = _interopRequireDefault(__webpack_require__(348)); var _generated4 = __webpack_require__(26); Object.keys(_generated4).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _generated4[key]; } }); }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const react = { isReactComponent: _isReactComponent.default, isCompatTag: _isCompatTag.default, buildChildren: _buildChildren.default }; exports.react = react; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } var Prefixer = __webpack_require__(150); var Browsers = __webpack_require__(120); var utils = __webpack_require__(47); var Declaration = function (_Prefixer) { _inherits(Declaration, _Prefixer); function Declaration() { _classCallCheck(this, Declaration); return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments)); } /** * Always true, because we already get prefixer by property name */ Declaration.prototype.check = function check() /* decl */{ return true; }; /** * Return prefixed version of property */ Declaration.prototype.prefixed = function prefixed(prop, prefix) { return prefix + prop; }; /** * Return unprefixed version of property */ Declaration.prototype.normalize = function normalize(prop) { return prop; }; /** * Check `value`, that it contain other prefixes, rather than `prefix` */ Declaration.prototype.otherPrefixes = function otherPrefixes(value, prefix) { for (var _iterator = Browsers.prefixes(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var other = _ref; if (other === prefix) { continue; } if (value.indexOf(other) !== -1) { return true; } } return false; }; /** * Set prefix to declaration */ Declaration.prototype.set = function set(decl, prefix) { decl.prop = this.prefixed(decl.prop, prefix); return decl; }; /** * Should we use visual cascade for prefixes */ Declaration.prototype.needCascade = function needCascade(decl) { if (!decl._autoprefixerCascade) { decl._autoprefixerCascade = this.all.options.cascade !== false && decl.raw('before').indexOf('\n') !== -1; } return decl._autoprefixerCascade; }; /** * Return maximum length of possible prefixed property */ Declaration.prototype.maxPrefixed = function maxPrefixed(prefixes, decl) { if (decl._autoprefixerMax) { return decl._autoprefixerMax; } var max = 0; for (var _iterator2 = prefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var prefix = _ref2; prefix = utils.removeNote(prefix); if (prefix.length > max) { max = prefix.length; } } decl._autoprefixerMax = max; return decl._autoprefixerMax; }; /** * Calculate indentation to create visual cascade */ Declaration.prototype.calcBefore = function calcBefore(prefixes, decl) { var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; var max = this.maxPrefixed(prefixes, decl); var diff = max - utils.removeNote(prefix).length; var before = decl.raw('before'); if (diff > 0) { before += Array(diff).fill(' ').join(''); } return before; }; /** * Remove visual cascade */ Declaration.prototype.restoreBefore = function restoreBefore(decl) { var lines = decl.raw('before').split('\n'); var min = lines[lines.length - 1]; this.all.group(decl).up(function (prefixed) { var array = prefixed.raw('before').split('\n'); var last = array[array.length - 1]; if (last.length < min.length) { min = last; } }); lines[lines.length - 1] = min; decl.raws.before = lines.join('\n'); }; /** * Clone and insert new declaration */ Declaration.prototype.insert = function insert(decl, prefix, prefixes) { var cloned = this.set(this.clone(decl), prefix); if (!cloned) return undefined; var already = decl.parent.some(function (i) { return i.prop === cloned.prop && i.value === cloned.value; }); if (already) { return undefined; } if (this.needCascade(decl)) { cloned.raws.before = this.calcBefore(prefixes, decl, prefix); } return decl.parent.insertBefore(decl, cloned); }; /** * Did this declaration has this prefix above */ Declaration.prototype.isAlready = function isAlready(decl, prefixed) { var already = this.all.group(decl).up(function (i) { return i.prop === prefixed; }); if (!already) { already = this.all.group(decl).down(function (i) { return i.prop === prefixed; }); } return already; }; /** * Clone and add prefixes for declaration */ Declaration.prototype.add = function add(decl, prefix, prefixes, result) { var prefixed = this.prefixed(decl.prop, prefix); if (this.isAlready(decl, prefixed) || this.otherPrefixes(decl.value, prefix)) { return undefined; } return this.insert(decl, prefix, prefixes, result); }; /** * Add spaces for visual cascade */ Declaration.prototype.process = function process(decl, result) { if (!this.needCascade(decl)) { _Prefixer.prototype.process.call(this, decl, result); return; } var prefixes = _Prefixer.prototype.process.call(this, decl, result); if (!prefixes || !prefixes.length) { return; } this.restoreBefore(decl); decl.raws.before = this.calcBefore(prefixes, decl); }; /** * Return list of prefixed properties to clean old prefixes */ Declaration.prototype.old = function old(prop, prefix) { return [this.prefixed(prop, prefix)]; }; return Declaration; }(Prefixer); module.exports = Declaration; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Realm = exports.ExecutionContext = exports.Tracer = undefined; exports.construct_empty_effects = construct_empty_effects; var _errors = __webpack_require__(6); var _index = __webpack_require__(0); var _environment = __webpack_require__(12); var _index2 = __webpack_require__(5); var _completions = __webpack_require__(3); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _seedrandom = __webpack_require__(626); var _seedrandom2 = _interopRequireDefault(_seedrandom); var _generator = __webpack_require__(34); var _internalizer = __webpack_require__(125); var _singletons = __webpack_require__(2); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ class Tracer { beginEvaluateForEffects(state) {} endEvaluateForEffects(state, effects) {} detourCall(F, thisArgument, argumentsList, newTarget, performCall) {} beforeCall(F, thisArgument, argumentsList, newTarget) {} afterCall(F, thisArgument, argumentsList, newTarget, result) {} } exports.Tracer = Tracer; class ExecutionContext { setCaller(context) { this.caller = context; } setFunction(F) { if (F instanceof _index.ECMAScriptSourceFunctionValue) this.isStrict = F.$Strict; this.function = F; } setLocation(loc) { if (!loc) return; this.loc = loc; } setRealm(realm) { this.realm = realm; } /* Read-only envs disallow: - creating bindings in their scope - creating or modifying objects when they are current running context */ setReadOnly(value) { let oldReadOnly = this.isReadOnly; if (this.variableEnvironment) this.variableEnvironment.environmentRecord.isReadOnly = value; if (this.lexicalEnvironment) this.lexicalEnvironment.environmentRecord.isReadOnly = value; this.isReadOnly = value; return oldReadOnly; } suspend() { // TODO #712: suspend } resume() { // TODO #712: resume return this.realm.intrinsics.undefined; } } exports.ExecutionContext = ExecutionContext; function construct_empty_effects(realm) { return [realm.intrinsics.empty, new _generator.Generator(realm), new Map(), new Map(), new Set()]; } class Realm { constructor(opts) { this.contextStack = []; this.MOBILE_JSC_VERSION = "jsc-600-1-4-17"; this.objectCount = 0; this.symbolCount = 867501803871088; this.functionBodyUniqueTagSeed = 1; this.nextGeneratorId = 0; this.isReadOnly = false; this.useAbstractInterpretation = !!opts.serialize || !!opts.residual || !!opts.check; this.trackLeaks = !!opts.abstractEffectsInAdditionalFunctions; this.ignoreLeakLogic = false; this.isInPureTryStatement = false; if (opts.mathRandomSeed !== undefined) { this.mathRandomGenerator = (0, _seedrandom2.default)(opts.mathRandomSeed); } this.strictlyMonotonicDateNow = !!opts.strictlyMonotonicDateNow; this.timeout = opts.timeout; if (this.timeout) { // We'll call Date.now for every this.timeoutCounterThreshold'th AST node. // The threshold is there to reduce the cost of the surprisingly expensive Date.now call. this.timeoutCounter = this.timeoutCounterThreshold = 1024; } this.start = Date.now(); this.compatibility = opts.compatibility || "browser"; this.maxStackDepth = opts.maxStackDepth || 225; this.omitInvariants = !!opts.omitInvariants; this.emitConcreteModel = !!opts.emitConcreteModel; this.$TemplateMap = []; if (this.useAbstractInterpretation) { this.preludeGenerator = new _generator.PreludeGenerator(opts.debugNames, opts.uniqueSuffix); this.pathConditions = []; _index.ObjectValue.setupTrackedPropertyAccessors(_index.ObjectValue.trackedPropertyNames); _index.ObjectValue.setupTrackedPropertyAccessors(_index.NativeFunctionValue.trackedPropertyNames); _index.ObjectValue.setupTrackedPropertyAccessors(_index.ProxyValue.trackedPropertyNames); } this.tracers = []; // These get initialized in construct_realm to avoid the dependency this.intrinsics = {}; this.$GlobalObject = {}; this.evaluators = Object.create(null); this.partialEvaluators = Object.create(null); this.$GlobalEnv = undefined; this.react = { abstractHints: new WeakMap(), classComponentMetadata: new Map(), currentOwner: undefined, enabled: opts.reactEnabled || false, output: opts.reactOutput || "create-element", hoistableFunctions: new WeakMap(), hoistableReactElements: new WeakMap(), reactElements: new WeakSet(), symbols: new Map() }; this.stripFlow = opts.stripFlow || false; this.fbLibraries = { other: new Map(), react: undefined, reactRelay: undefined }; this.errorHandler = opts.errorHandler; this.globalSymbolRegistry = []; this.activeLexicalEnvironments = new Set(); this._abstractValuesDefined = new Set(); // A set of nameStrings to ensure abstract values have unique names this.debugNames = opts.debugNames; } // TODO(1264): Remove this once we implement proper exception handling in abstract calls. // A list of abstract conditions that are known to be true in the current execution path. // For example, the abstract condition of an if statement is known to be true inside its true branch. // Unique tag for identifying function body ast node. It is neeeded // instead of ast node itself because we may perform ast tree deep clone // during serialization which changes the ast identity. // to force flow to type the annotations isCompatibleWith(compatibility) { return compatibility === this.compatibility; } // Checks if there is a let binding at global scope with the given name // returning it if so getGlobalLetBinding(key) { let globrec = this.$GlobalEnv.environmentRecord; // GlobalEnv should have a GlobalEnvironmentRecord (0, _invariant2.default)(globrec instanceof _environment.GlobalEnvironmentRecord); let dclrec = globrec.$DeclarativeRecord; try { return dclrec.HasBinding(key) ? dclrec.GetBindingValue(key, false) : undefined; } catch (e) { if (e instanceof _errors.FatalError) return undefined; throw e; } } /* Read only realms disallow: - using console.log - creating bindings in any existing scopes - modifying object properties in any existing scopes Setting a realm read-only sets all contained environments to read-only, but all new environments (e.g. new ExecutionContexts) will be writeable. */ setReadOnly(readOnlyValue) { this.isReadOnly = readOnlyValue; this.$GlobalEnv.environmentRecord.isReadOnly = readOnlyValue; this.contextStack.forEach(ctx => { ctx.setReadOnly(readOnlyValue); }); } testTimeout() { let timeout = this.timeout; if (timeout && ! --this.timeoutCounter) { this.timeoutCounter = this.timeoutCounterThreshold; let total = Date.now() - this.start; if (total > timeout) { throw new _errors.FatalError("Timed out"); } } } hasRunningContext() { return this.contextStack.length !== 0; } getRunningContext() { let context = this.contextStack[this.contextStack.length - 1]; (0, _invariant2.default)(context, "There's no running execution context"); return context; } clearBlockBindings(modifiedBindings, environmentRecord) { if (modifiedBindings === undefined) return; for (let b of modifiedBindings.keys()) if (environmentRecord.bindings[b.name] && environmentRecord.bindings[b.name] === b) modifiedBindings.delete(b); } clearBlockBindingsFromCompletion(completion, environmentRecord) { if (completion instanceof _completions.PossiblyNormalCompletion) { this.clearBlockBindings(completion.alternateEffects[2], environmentRecord); this.clearBlockBindings(completion.consequentEffects[2], environmentRecord); if (completion.savedEffects !== undefined) this.clearBlockBindings(completion.savedEffects[2], environmentRecord); if (completion.alternate instanceof _completions.Completion) this.clearBlockBindingsFromCompletion(completion.alternate, environmentRecord); if (completion.consequent instanceof _completions.Completion) this.clearBlockBindingsFromCompletion(completion.consequent, environmentRecord); } else if (completion instanceof _completions.JoinedAbruptCompletions) { this.clearBlockBindings(completion.alternateEffects[2], environmentRecord); this.clearBlockBindings(completion.consequentEffects[2], environmentRecord); if (completion.alternate instanceof _completions.Completion) this.clearBlockBindingsFromCompletion(completion.alternate, environmentRecord); if (completion.consequent instanceof _completions.Completion) this.clearBlockBindingsFromCompletion(completion.consequent, environmentRecord); } } // Call when a scope falls out of scope and should be destroyed. // Clears the Bindings corresponding to the disappearing Scope from ModifiedBindings onDestroyScope(lexicalEnvironment) { (0, _invariant2.default)(this.activeLexicalEnvironments.has(lexicalEnvironment)); let modifiedBindings = this.modifiedBindings; if (modifiedBindings) { // Don't undo things to global scope because it's needed past its destruction point (for serialization) let environmentRecord = lexicalEnvironment.environmentRecord; if (environmentRecord instanceof _environment.DeclarativeEnvironmentRecord) { this.clearBlockBindings(modifiedBindings, environmentRecord); if (this.savedCompletion !== undefined) this.clearBlockBindingsFromCompletion(this.savedCompletion, environmentRecord); } } // Ensures if we call onDestroyScope too early, there will be a failure. this.activeLexicalEnvironments.delete(lexicalEnvironment); lexicalEnvironment.destroy(); } pushContext(context) { if (this.contextStack.length >= this.maxStackDepth) { throw new _errors.FatalError("Maximum stack depth exceeded"); } this.contextStack.push(context); } clearFunctionBindings(modifiedBindings, funcVal) { if (modifiedBindings === undefined) return; for (let b of modifiedBindings.keys()) { if (b.environment.$FunctionObject === funcVal) modifiedBindings.delete(b); } } clearFunctionBindingsFromCompletion(completion, funcVal) { if (completion instanceof _completions.PossiblyNormalCompletion) { this.clearFunctionBindings(completion.alternateEffects[2], funcVal); this.clearFunctionBindings(completion.consequentEffects[2], funcVal); if (completion.savedEffects !== undefined) this.clearFunctionBindings(completion.savedEffects[2], funcVal); if (completion.alternate instanceof _completions.Completion) this.clearFunctionBindingsFromCompletion(completion.alternate, funcVal); if (completion.consequent instanceof _completions.Completion) this.clearFunctionBindingsFromCompletion(completion.consequent, funcVal); } else if (completion instanceof _completions.JoinedAbruptCompletions) { this.clearFunctionBindings(completion.alternateEffects[2], funcVal); this.clearFunctionBindings(completion.consequentEffects[2], funcVal); if (completion.alternate instanceof _completions.Completion) this.clearFunctionBindingsFromCompletion(completion.alternate, funcVal); if (completion.consequent instanceof _completions.Completion) this.clearFunctionBindingsFromCompletion(completion.consequent, funcVal); } } popContext(context) { let funcVal = context.function; if (funcVal) { this.clearFunctionBindings(this.modifiedBindings, funcVal); if (this.savedCompletion !== undefined) this.clearFunctionBindingsFromCompletion(this.savedCompletion, funcVal); } let c = this.contextStack.pop(); (0, _invariant2.default)(c === context); } wrapInGlobalEnv(callback) { let context = new ExecutionContext(); context.isStrict = this.isStrict; context.lexicalEnvironment = this.$GlobalEnv; context.variableEnvironment = this.$GlobalEnv; context.realm = this; this.pushContext(context); try { return callback(); } finally { this.popContext(context); } } assignToGlobal(name, value) { this.wrapInGlobalEnv(() => this.$GlobalEnv.assignToGlobal(name, value)); } deleteGlobalBinding(name) { this.$GlobalEnv.environmentRecord.DeleteBinding(name); } // Evaluate a context as if it won't have any side-effects outside of any objects // that it created itself. This promises that any abstract functions inside of it // also won't have effects on any objects or bindings that weren't created in this // call. evaluatePure(f) { if (!this.trackLeaks) { return f(); } let saved_createdObjectsTrackedForLeaks = this.createdObjectsTrackedForLeaks; // Track all objects (including function closures) created during // this call. This will be used to make the assumption that every // *other* object is unchanged (pure). These objects are marked // as leaked if they're passed to abstract functions. this.createdObjectsTrackedForLeaks = new Set(); try { return f(); } finally { this.createdObjectsTrackedForLeaks = saved_createdObjectsTrackedForLeaks; } } isInPureScope() { return !!this.createdObjectsTrackedForLeaks; } evaluateWithoutLeakLogic(f) { (0, _invariant2.default)(!this.ignoreLeakLogic, "Nesting evaluateWithoutLeakLogic() calls is not supported."); this.ignoreLeakLogic = true; try { return f(); } finally { this.ignoreLeakLogic = false; } } // Evaluate some code that might generate temporal values knowing that it might end in an abrupt // completion. We only need to support ThrowCompletion for now but this can be expanded to support other // abrupt completions. evaluateWithPossibleThrowCompletion(f, thrownTypes, thrownValues) { // The cases when we need this are only when we might invoke unknown code such as abstract // funtions, getters, custom coercion etc. It is possible we can use this in other cases // where something might throw a built-in error but can never issue arbitrary code such as // calling something that might not be a function. For now we only use it in pure functions. (0, _invariant2.default)(this.isInPureScope(), "only abstract abrupt completion in pure functions"); // TODO(1264): We should create a new generator for this scope and wrap it in a try/catch. // We could use the outcome of that as the join condition for a PossiblyNormalCompletion. // We should then compose that with the saved completion and move on to the normal route. // Currently we just issue a recoverable error instead if this might matter. let value = f(); if (this.isInPureTryStatement) { let diag = new _errors.CompilerDiagnostic("Possible throw inside try/catch is not yet supported", this.currentLocation, "PP0021", "RecoverableError"); if (this.handleError(diag) !== "Recover") throw new _errors.FatalError(); } return value; } // Evaluate the given ast in a sandbox and return the evaluation results // in the form of a completion, a code generator, a map of changed variable // bindings and a map of changed property bindings. evaluateNodeForEffects(ast, strictCode, env, state, generatorName) { return this.evaluateForEffects(() => env.evaluateCompletionDeref(ast, strictCode), state, generatorName); } evaluateForEffectsInGlobalEnv(func, state, generatorName) { return this.wrapInGlobalEnv(() => this.evaluateForEffects(func, state, generatorName)); } // NB: does not apply generators because there's no way to cleanly revert them. // func should not return undefined withEffectsAppliedInGlobalEnv(func, effects) { let result; this.evaluateForEffectsInGlobalEnv(() => { try { this.applyEffects(effects); result = func(effects); return this.intrinsics.undefined; } finally { this.restoreBindings(effects[2]); this.restoreProperties(effects[3]); } }); (0, _invariant2.default)(result !== undefined, "If we get here, func must have returned undefined."); return result; } evaluateNodeForEffectsInGlobalEnv(node, state, generatorName) { return this.wrapInGlobalEnv(() => this.evaluateNodeForEffects(node, false, this.$GlobalEnv, state, generatorName)); } partiallyEvaluateNodeForEffects(ast, strictCode, env) { let nodeAst, nodeIO; function partialEval() { let result; [result, nodeAst, nodeIO] = env.partiallyEvaluateCompletionDeref(ast, strictCode); return result; } let effects = this.evaluateForEffects(partialEval); (0, _invariant2.default)(nodeAst !== undefined && nodeIO !== undefined); return [effects, nodeAst, nodeIO]; } evaluateForEffects(f, state, generatorName) { // Save old state and set up empty state for ast let [savedBindings, savedProperties] = this.getAndResetModifiedMaps(); let saved_generator = this.generator; let saved_createdObjects = this.createdObjects; let saved_completion = this.savedCompletion; this.generator = new _generator.Generator(this, generatorName); this.createdObjects = new Set(); this.savedCompletion = undefined; // while in this call, we only explore the normal path. let result; try { for (let t1 of this.tracers) t1.beginEvaluateForEffects(state); let c; try { try { c = f(); if (c instanceof _environment.Reference) c = _singletons.Environment.GetValue(this, c); } catch (e) { if (e instanceof _completions.AbruptCompletion) c = e;else throw e; } // This is a join point for the normal branch of a PossiblyNormalCompletion. if (c instanceof _index.Value || c instanceof _completions.AbruptCompletion) c = _singletons.Functions.incorporateSavedCompletion(this, c); (0, _invariant2.default)(c !== undefined); if (c instanceof _completions.PossiblyNormalCompletion) { // The current state may have advanced since the time control forked into the various paths recorded in c. // Update the normal path and restore the global state to what it was at the time of the fork. let subsequentEffects = this.getCapturedEffects(c, c.value); (0, _invariant2.default)(subsequentEffects !== undefined); this.stopEffectCaptureAndUndoEffects(c); _singletons.Join.updatePossiblyNormalCompletionWithSubsequentEffects(this, c, subsequentEffects); this.savedCompletion = undefined; } (0, _invariant2.default)(this.generator !== undefined); (0, _invariant2.default)(this.modifiedBindings !== undefined); (0, _invariant2.default)(this.modifiedProperties !== undefined); (0, _invariant2.default)(this.createdObjects !== undefined); let astGenerator = this.generator; let astBindings = this.modifiedBindings; let astProperties = this.modifiedProperties; let astCreatedObjects = this.createdObjects; // Return the captured state changes and evaluation result result = [c, astGenerator, astBindings, astProperties, astCreatedObjects]; return result; } finally { // Roll back the state changes if (this.savedCompletion !== undefined) this.stopEffectCaptureAndUndoEffects(this.savedCompletion); if (result !== undefined) { this.restoreBindings(result[2]); this.restoreProperties(result[3]); } else { this.restoreBindings(this.modifiedBindings); this.restoreProperties(this.modifiedProperties); } this.generator = saved_generator; this.modifiedBindings = savedBindings; this.modifiedProperties = savedProperties; this.createdObjects = saved_createdObjects; this.savedCompletion = saved_completion; } } finally { for (let t2 of this.tracers) t2.endEvaluateForEffects(state, result); } } evaluateWithUndo(f, defaultValue = this.intrinsics.undefined) { if (!this.useAbstractInterpretation) return f(); let oldErrorHandler = this.errorHandler; this.errorHandler = d => { if (d.severity === "Information" || d.severity === "Warning") return "Recover"; return "Fail"; }; try { let effects = this.evaluateForEffects(() => { try { return f(); } catch (e) { if (e instanceof _completions.Completion) { return defaultValue; } else if (e instanceof _errors.FatalError) { return defaultValue; } else { throw e; } } }); return effects[0] instanceof _index.Value ? effects[0] : defaultValue; } finally { this.errorHandler = oldErrorHandler; } } evaluateWithUndoForDiagnostic(f) { if (!this.useAbstractInterpretation) return f(); let savedHandler = this.errorHandler; let diagnostic; try { this.errorHandler = d => { diagnostic = d; return "Fail"; }; let effects = this.evaluateForEffects(f); this.applyEffects(effects); let resultVal = effects[0]; if (resultVal instanceof _completions.AbruptCompletion) throw resultVal; if (resultVal instanceof _completions.PossiblyNormalCompletion) { // in this case one of the branches may complete abruptly, which means that // not all control flow branches join into one flow at this point. // Consequently we have to continue tracking changes until the point where // all the branches come together into one. resultVal = this.composeWithSavedCompletion(resultVal); } (0, _invariant2.default)(resultVal instanceof _index.Value); return resultVal; } catch (e) { if (diagnostic !== undefined) return diagnostic; throw e; } finally { this.errorHandler = savedHandler; } } evaluateForFixpointEffects(loopContinueTest, loopBody) { try { let effects1 = this.evaluateForEffects(loopBody); while (true) { this.restoreBindings(effects1[2]); this.restoreProperties(effects1[3]); let effects2 = this.evaluateForEffects(() => { let test = loopContinueTest(); if (!(test instanceof _index.AbstractValue)) throw new _errors.FatalError("loop terminates before fixed point"); return loopBody(); }); this.restoreBindings(effects1[2]); this.restoreProperties(effects1[3]); if (_singletons.Widen.containsEffects(effects1, effects2)) { // effects1 includes every value present in effects2, so doing another iteration using effects2 will not // result in any more values being added to abstract domains and hence a fixpoint has been reached. let [, gen, bindings2, pbindings2] = effects2; this._emitPropertAssignments(gen, pbindings2); this._emitLocalAssignments(gen, bindings2); return [effects1, effects2]; } effects1 = _singletons.Widen.widenEffects(this, effects1, effects2); } } catch (e) { return undefined; } } // populate the loop body generator with assignments that will update the phiNodes _emitLocalAssignments(gen, bindings) { let tvalFor = new Map(); bindings.forEach((binding, key, map) => { let val = binding.value; if (val instanceof _index.AbstractValue) { (0, _invariant2.default)(val._buildNode !== undefined); let tval = gen.derive(val.types, val.values, [val], ([n]) => n, { skipInvariant: true }); tvalFor.set(key, tval); } }); bindings.forEach((binding, key, map) => { let val = binding.value; if (val instanceof _index.AbstractValue) { let phiNode = key.phiNode; let tval = tvalFor.get(key); (0, _invariant2.default)(tval !== undefined); gen.emitStatement([tval], ([v]) => { (0, _invariant2.default)(phiNode !== undefined); let id = phiNode.buildNode([]); return t.expressionStatement(t.assignmentExpression("=", id, v)); }); } }); } // populate the loop body generator with assignments that will update properties modified inside the loop _emitPropertAssignments(gen, pbindings) { function isSelfReferential(value, pathNode) { if (value === pathNode) return true; if (value instanceof _index.AbstractValue && pathNode !== undefined) { for (let v of value.args) { if (isSelfReferential(v, pathNode)) return true; } } return false; } let tvalFor = new Map(); pbindings.forEach((val, key, map) => { let value = val && val.value; if (value instanceof _index.AbstractValue) { (0, _invariant2.default)(value._buildNode !== undefined); let tval = gen.derive(value.types, value.values, [key.object, value], ([o, n]) => { (0, _invariant2.default)(value instanceof _index.Value); if (typeof key.key === "string" && value.mightHaveBeenDeleted() && isSelfReferential(value, key.pathNode)) { let inTest = t.binaryExpression("in", t.stringLiteral(key.key), o); let addEmpty = t.conditionalExpression(inTest, n, _internalizer.emptyExpression); n = t.logicalExpression("||", n, addEmpty); } return n; }, { skipInvariant: true }); tvalFor.set(key, tval); } }); pbindings.forEach((val, key, map) => { let path = key.pathNode; let tval = tvalFor.get(key); (0, _invariant2.default)(val !== undefined); let value = val.value; (0, _invariant2.default)(value instanceof _index.Value); let mightHaveBeenDeleted = value.mightHaveBeenDeleted(); let mightBeUndefined = value.mightBeUndefined(); if (typeof key.key === "string") { gen.emitStatement([key.object, tval || value, this.intrinsics.empty], ([o, v, e]) => { (0, _invariant2.default)(path !== undefined); let lh = path.buildNode([o, t.identifier(key.key)]); let r = t.expressionStatement(t.assignmentExpression("=", lh, v)); if (mightHaveBeenDeleted) { // If v === __empty || (v === undefined && !(key.key in o)) then delete it let emptyTest = t.binaryExpression("===", v, e); let undefinedTest = t.binaryExpression("===", v, _internalizer.voidExpression); let inTest = t.unaryExpression("!", t.binaryExpression("in", t.stringLiteral(key.key), o)); let guard = t.logicalExpression("||", emptyTest, t.logicalExpression("&&", undefinedTest, inTest)); let deleteIt = t.expressionStatement(t.unaryExpression("delete", lh)); return t.ifStatement(mightBeUndefined ? emptyTest : guard, deleteIt, r); } return r; }); } else { gen.emitStatement([key.object, key.key, tval || value, this.intrinsics.empty], ([o, p, v, e]) => { (0, _invariant2.default)(path !== undefined); let lh = path.buildNode([o, p]); return t.expressionStatement(t.assignmentExpression("=", lh, v)); }); } }); } composeEffects(priorEffects, subsequentEffects) { let [, pg, pb, pp, po] = priorEffects; let [sc, sg, sb, sp, so] = subsequentEffects; let result = construct_empty_effects(this); let [,, rb, rp, ro] = result; result[0] = sc; result[1] = _singletons.Join.composeGenerators(this, pg || result[1], sg); if (pb) { pb.forEach((val, key, m) => rb.set(key, val)); } sb.forEach((val, key, m) => rb.set(key, val)); if (pp) { pp.forEach((desc, propertyBinding, m) => rp.set(propertyBinding, desc)); } sp.forEach((val, key, m) => rp.set(key, val)); if (po) { po.forEach((ob, a) => ro.add(ob)); } so.forEach((ob, a) => ro.add(ob)); return result; } updateAbruptCompletions(priorEffects, c) { if (c.consequent instanceof _completions.AbruptCompletion) { c.consequentEffects = this.composeEffects(priorEffects, c.consequentEffects); let alternate = c.alternate; if (alternate instanceof _completions.PossiblyNormalCompletion) this.updateAbruptCompletions(priorEffects, alternate); } else { (0, _invariant2.default)(c.alternate instanceof _completions.AbruptCompletion); c.alternateEffects = this.composeEffects(priorEffects, c.alternateEffects); let consequent = c.consequent; if (consequent instanceof _completions.PossiblyNormalCompletion) this.updateAbruptCompletions(priorEffects, consequent); } } composeWithSavedCompletion(completion) { if (this.savedCompletion === undefined) { this.savedCompletion = completion; this.savedCompletion.savedPathConditions = this.pathConditions; this.captureEffects(completion); } else { this.savedCompletion = _singletons.Join.composePossiblyNormalCompletions(this, this.savedCompletion, completion); } if (completion.consequent instanceof _completions.AbruptCompletion) { _singletons.Path.pushInverseAndRefine(completion.joinCondition); if (completion.alternate instanceof _completions.PossiblyNormalCompletion) { completion.alternate.pathConditions.forEach(_singletons.Path.pushAndRefine); } } else if (completion.alternate instanceof _completions.AbruptCompletion) { _singletons.Path.pushAndRefine(completion.joinCondition); if (completion.consequent instanceof _completions.PossiblyNormalCompletion) { completion.consequent.pathConditions.forEach(_singletons.Path.pushAndRefine); } } return completion.value; } incorporatePriorSavedCompletion(priorCompletion) { if (priorCompletion === undefined) return; if (this.savedCompletion === undefined) { this.savedCompletion = priorCompletion; this.captureEffects(priorCompletion); } else { (0, _invariant2.default)(priorCompletion.savedEffects !== undefined); let savedEffects = this.savedCompletion.savedEffects; (0, _invariant2.default)(savedEffects !== undefined); this.restoreBindings(savedEffects[2]); this.restoreProperties(savedEffects[3]); _singletons.Join.updatePossiblyNormalCompletionWithSubsequentEffects(this, priorCompletion, savedEffects); this.restoreBindings(savedEffects[2]); this.restoreProperties(savedEffects[3]); (0, _invariant2.default)(this.savedCompletion !== undefined); this.savedCompletion.savedEffects = undefined; this.savedCompletion = _singletons.Join.composePossiblyNormalCompletions(this, priorCompletion, this.savedCompletion); } } captureEffects(completion) { if (completion.savedEffects !== undefined) { // Already called captureEffects, just carry on return; } completion.savedEffects = [this.intrinsics.undefined, this.generator, this.modifiedBindings, this.modifiedProperties, this.createdObjects]; this.generator = new _generator.Generator(this); this.modifiedBindings = new Map(); this.modifiedProperties = new Map(); this.createdObjects = new Set(); } getCapturedEffects(completion, v) { if (completion.savedEffects === undefined) return undefined; if (v === undefined) v = this.intrinsics.undefined; (0, _invariant2.default)(this.generator !== undefined); (0, _invariant2.default)(this.modifiedBindings !== undefined); (0, _invariant2.default)(this.modifiedProperties !== undefined); (0, _invariant2.default)(this.createdObjects !== undefined); return [v, this.generator, this.modifiedBindings, this.modifiedProperties, this.createdObjects]; } stopEffectCapture(completion) { let e = this.getCapturedEffects(completion); if (e !== undefined) { this.stopEffectCaptureAndUndoEffects(completion); this.applyEffects(e); } } stopEffectCaptureAndUndoEffects(completion) { // Roll back the state changes this.restoreBindings(this.modifiedBindings); this.restoreProperties(this.modifiedProperties); // Restore saved state if (completion.savedEffects !== undefined) { let [c, g, b, p, o] = completion.savedEffects; c; completion.savedEffects = undefined; this.generator = g; this.modifiedBindings = b; this.modifiedProperties = p; this.createdObjects = o; } else { (0, _invariant2.default)(false); } } // Apply the given effects to the global state applyEffects(effects, leadingComment = "") { let [, generator, bindings, properties, createdObjects] = effects; // Add generated code for property modifications this.appendGenerator(generator, leadingComment); // Restore bindings this.restoreBindings(bindings); this.restoreProperties(properties); // track bindings let realmModifiedBindings = this.modifiedBindings; if (realmModifiedBindings !== undefined) { bindings.forEach((val, key, m) => { (0, _invariant2.default)(realmModifiedBindings !== undefined); if (!realmModifiedBindings.has(key)) { realmModifiedBindings.set(key, val); } }); } let realmModifiedProperties = this.modifiedProperties; if (realmModifiedProperties !== undefined) { properties.forEach((desc, propertyBinding, m) => { (0, _invariant2.default)(realmModifiedProperties !== undefined); if (!realmModifiedProperties.has(propertyBinding)) { realmModifiedProperties.set(propertyBinding, desc); } }); } // add created objects if (createdObjects.size > 0) { let realmCreatedObjects = this.createdObjects; if (realmCreatedObjects === undefined) this.createdObjects = new Set(createdObjects);else { createdObjects.forEach((ob, a) => { (0, _invariant2.default)(realmCreatedObjects !== undefined); realmCreatedObjects.add(ob); }); } } } outputToConsole(method, args) { if (this.isReadOnly) { // This only happens during speculative execution and is reported elsewhere throw new _errors.FatalError("Trying to create console output in read-only realm"); } if (this.useAbstractInterpretation) { (0, _invariant2.default)(this.generator !== undefined); this.generator.emitConsoleLog(method, args); } else { console[method](getString(this, args)); } function getString(realm, values) { let res = ""; while (values.length) { let next = values.shift(); let nextString = _singletons.To.ToString(realm, next); res += nextString; } return res; } } // Record the current value of binding in this.modifiedBindings unless // there is already an entry for binding. recordModifiedBinding(binding) { if (binding.environment.isReadOnly) { // This only happens during speculative execution and is reported elsewhere throw new _errors.FatalError("Trying to modify a binding in read-only realm"); } if (this.modifiedBindings !== undefined && !this.modifiedBindings.has(binding)) this.modifiedBindings.set(binding, { hasLeaked: binding.hasLeaked, value: binding.value }); return binding; } callReportObjectGetOwnProperties(ob) { if (this.reportObjectGetOwnProperties !== undefined) { this.reportObjectGetOwnProperties(ob); } } callReportPropertyAccess(binding) { if (this.reportPropertyAccess !== undefined) { this.reportPropertyAccess(binding); } } // Record the current value of binding in this.modifiedProperties unless // there is already an entry for binding. recordModifiedProperty(binding) { if (binding === undefined) return; if (this.isReadOnly && (this.getRunningContext().isReadOnly || !this.isNewObject(binding.object))) { // This only happens during speculative execution and is reported elsewhere throw new _errors.FatalError("Trying to modify a property in read-only realm"); } this.callReportPropertyAccess(binding); if (this.modifiedProperties !== undefined && !this.modifiedProperties.has(binding)) { this.modifiedProperties.set(binding, (0, _index2.cloneDescriptor)(binding.descriptor)); } } isNewObject(object) { if (object instanceof _index.AbstractObjectValue) return false; return this.createdObjects === undefined || this.createdObjects.has(object); } recordNewObject(object) { if (this.createdObjects !== undefined) { this.createdObjects.add(object); } if (this.createdObjectsTrackedForLeaks !== undefined) { this.createdObjectsTrackedForLeaks.add(object); } } // Returns the current values of modifiedBindings and modifiedProperties // and then assigns new empty maps to them. getAndResetModifiedMaps() { let result = [this.modifiedBindings, this.modifiedProperties]; this.modifiedBindings = new Map(); this.modifiedProperties = new Map(); return result; } // Restores each Binding in the given map to the value it // had when it was entered into the map and updates the map to record // the value the Binding had just before the call to this method. restoreBindings(modifiedBindings) { if (modifiedBindings === undefined) return; modifiedBindings.forEach(({ hasLeaked, value }, binding, m) => { let l = binding.hasLeaked; let v = binding.value; binding.hasLeaked = hasLeaked; binding.value = value; m.set(binding, { hasLeaked: l, value: v }); }); } // Restores each PropertyBinding in the given map to the value it // had when it was entered into the map and updates the map to record // the value the Binding had just before the call to this method. restoreProperties(modifiedProperties) { if (modifiedProperties === undefined) return; modifiedProperties.forEach((desc, propertyBinding, m) => { let d = propertyBinding.descriptor; propertyBinding.descriptor = desc; m.set(propertyBinding, d); }); } // Provide the realm with maps in which to track modifications. // A map can be set to undefined if no tracking is required. setModifiedMaps(modifiedBindings, modifiedProperties) { this.modifiedBindings = modifiedBindings; this.modifiedProperties = modifiedProperties; } rebuildObjectProperty(object, key, propertyValue, path) { if (!(propertyValue instanceof _index.AbstractValue)) return; if (propertyValue.kind === "abstractConcreteUnion") { let absVal = propertyValue.args.find(e => e instanceof _index.AbstractValue); (0, _invariant2.default)(absVal instanceof _index.AbstractValue); propertyValue = absVal; } if (!propertyValue.isIntrinsic()) { propertyValue.intrinsicName = `${path}.${key}`; propertyValue.kind = "rebuiltProperty"; propertyValue.args = [object]; propertyValue._buildNode = ([node]) => t.memberExpression(node, t.identifier(key)); this.rebuildNestedProperties(propertyValue, propertyValue.intrinsicName); } } rebuildNestedProperties(abstractValue, path) { if (!(abstractValue instanceof _index.AbstractObjectValue)) return; if (abstractValue.values.isTop()) return; let template = abstractValue.getTemplate(); (0, _invariant2.default)(!template.intrinsicName || template.intrinsicName === path); template.intrinsicName = path; template.intrinsicNameGenerated = true; for (let [key, binding] of template.properties) { if (binding === undefined || binding.descriptor === undefined) continue; // deleted (0, _invariant2.default)(binding.descriptor !== undefined); let value = binding.descriptor.value; _singletons.Properties.ThrowIfMightHaveBeenDeleted(value); if (value === undefined) { _index.AbstractValue.reportIntrospectionError(abstractValue, key); throw new _errors.FatalError(); } (0, _invariant2.default)(value instanceof _index.Value); this.rebuildObjectProperty(abstractValue, key, value, path); } } createExecutionContext() { let context = new ExecutionContext(); let loc = this.nextContextLocation; if (loc) { context.setLocation(loc); this.nextContextLocation = null; } return context; } setNextExecutionContextLocation(loc) { if (!loc) return; //if (this.nextContextLocation) { // throw new ThrowCompletion( // Construct(this, this.intrinsics.TypeError, [new StringValue(this, "Already have a context location that we haven't used yet")]) // ); //} else { this.nextContextLocation = loc; //} } reportIntrospectionError(message) { if (message === undefined) message = ""; if (typeof message === "string") message = new _index.StringValue(this, message); (0, _invariant2.default)(message instanceof _index.StringValue); this.nextContextLocation = this.currentLocation; let error = new _errors.CompilerDiagnostic(message.value, this.currentLocation, "PP0001", "FatalError"); this.handleError(error); } createErrorThrowCompletion(type, message) { (0, _invariant2.default)(type !== this.intrinsics.__IntrospectionError); if (message === undefined) message = ""; if (typeof message === "string") message = new _index.StringValue(this, message); (0, _invariant2.default)(message instanceof _index.StringValue); this.nextContextLocation = this.currentLocation; return new _completions.ThrowCompletion((0, _index2.Construct)(this, type, [message]), this.currentLocation); } appendGenerator(generator, leadingComment = "") { let realmGenerator = this.generator; if (realmGenerator === undefined) { (0, _invariant2.default)(generator.empty()); return; } realmGenerator.appendGenerator(generator, leadingComment); } // Pass the error to the realm's error-handler // Return value indicates whether the caller should try to recover from the error or not. handleError(diagnostic) { if (!diagnostic.callStack && this.contextStack.length > 0) { let error = (0, _index2.Construct)(this, this.intrinsics.Error); let stack = error.$Get("stack", error); if (stack instanceof _index.StringValue) diagnostic.callStack = stack.value; } // Default behaviour is to bail on the first error let errorHandler = this.errorHandler; if (!errorHandler) { let msg = `${diagnostic.errorCode}: ${diagnostic.message}`; if (diagnostic.location) { let loc_start = diagnostic.location.start; let loc_end = diagnostic.location.end; msg += ` at ${loc_start.line}:${loc_start.column} to ${loc_end.line}:${loc_end.column}`; } try { switch (diagnostic.severity) { case "Information": console.log(`Info: ${msg}`); return "Recover"; case "Warning": console.warn(`Warn: ${msg}`); return "Recover"; case "RecoverableError": console.error(`Error: ${msg}`); return "Fail"; case "FatalError": console.error(`Fatal Error: ${msg}`); return "Fail"; default: (0, _invariant2.default)(false, "Unexpected error type"); } } finally { console.log(diagnostic.callStack); } } return errorHandler(diagnostic); } saveNameString(nameString) { this._abstractValuesDefined.add(nameString); } isNameStringUnique(nameString) { return !this._abstractValuesDefined.has(nameString); } } exports.Realm = Realm; //# sourceMappingURL=realm.js.map /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Reference = exports.LexicalEnvironment = exports.GlobalEnvironmentRecord = exports.FunctionEnvironmentRecord = exports.ObjectEnvironmentRecord = exports.DeclarativeEnvironmentRecord = exports.EnvironmentRecord = undefined; exports.havocBinding = havocBinding; exports.mightBecomeAnObject = mightBecomeAnObject; var _completions = __webpack_require__(3); var _errors = __webpack_require__(6); var _options = __webpack_require__(588); var _realm = __webpack_require__(11); var _index = __webpack_require__(0); var _babelGenerator = __webpack_require__(589); var _babelGenerator2 = _interopRequireDefault(_babelGenerator); var _parse = __webpack_require__(224); var _parse2 = _interopRequireDefault(_parse); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _traverseFast = __webpack_require__(101); var _traverseFast2 = _interopRequireDefault(_traverseFast); var _index2 = __webpack_require__(5); var _singletons = __webpack_require__(2); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); var _index3 = __webpack_require__(35); var _PrimitiveValue = __webpack_require__(587); var _PrimitiveValue2 = _interopRequireDefault(_PrimitiveValue); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const sourceMap = __webpack_require__(1911); /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function deriveGetBinding(realm, binding) { let types = _index3.TypesDomain.topVal; let values = _index3.ValuesDomain.topVal; (0, _invariant2.default)(realm.generator !== undefined); return realm.generator.derive(types, values, [], (_, context) => context.serializeBinding(binding)); } function havocBinding(binding) { let realm = binding.environment.realm; if (!binding.hasLeaked) { realm.recordModifiedBinding(binding).hasLeaked = true; } } // ECMA262 8.1.1 class EnvironmentRecord { constructor(realm) { (0, _invariant2.default)(realm, "expected realm"); this.realm = realm; this.isReadOnly = false; } } exports.EnvironmentRecord = EnvironmentRecord; // ECMA262 8.1.1.1 class DeclarativeEnvironmentRecord extends EnvironmentRecord { constructor(realm) { super(realm); this.bindings = Object.create(null); this.frozen = false; } // Frozen Records cannot have bindings created or deleted but can have bindings updated // ECMA262 8.1.1.1.1 HasBinding(N) { // 1. Let envRec be the declarative Environment Record for which the method was invoked. let envRec = this; // 2. If envRec has a binding for the name that is the value of N, return true. if (envRec.bindings[N]) return true; // 3. Return false. return false; } // ECMA262 8.1.1.1.2 CreateMutableBinding(N, D, isGlobal = false) { (0, _invariant2.default)(!this.frozen); let realm = this.realm; // 1. Let envRec be the declarative Environment Record for which the method was invoked. let envRec = this; // 2. Assert: envRec does not already have a binding for N. (0, _invariant2.default)(!envRec.bindings[N], `shouldn't have the binding ${N}`); // 3. Create a mutable binding in envRec for N and record that it is uninitialized. If D is true, record that the newly created binding may be deleted by a subsequent DeleteBinding call. this.bindings[N] = realm.recordModifiedBinding({ initialized: false, mutable: true, deletable: D, environment: envRec, name: N, isGlobal: isGlobal, hasLeaked: false }); // 4. Return NormalCompletion(empty). return realm.intrinsics.undefined; } // ECMA262 8.1.1.1.3 CreateImmutableBinding(N, S, isGlobal = false) { (0, _invariant2.default)(!this.frozen); let realm = this.realm; // 1. Let envRec be the declarative Environment Record for which the method was invoked. let envRec = this; // 2. Assert: envRec does not already have a binding for N. (0, _invariant2.default)(!envRec.bindings[N], `shouldn't have the binding ${N}`); // 3. Create an immutable binding in envRec for N and record that it is uninitialized. If S is true, record that the newly created binding is a strict binding. this.bindings[N] = realm.recordModifiedBinding({ initialized: false, strict: S, deletable: false, environment: envRec, name: N, isGlobal: isGlobal, hasLeaked: false }); // 4. Return NormalCompletion(empty). return realm.intrinsics.undefined; } // ECMA262 8.1.1.1.4 InitializeBinding(N, V) { // 1. Let envRec be the declarative Environment Record for which the method was invoked. let envRec = this; let binding = envRec.bindings[N]; // 2. Assert: envRec must have an uninitialized binding for N. (0, _invariant2.default)(binding && !binding.initialized, `shouldn't have the binding ${N}`); // 3. Set the bound value for N in envRec to V. this.realm.recordModifiedBinding(binding).value = V; // 4. Record that the binding for N in envRec has been initialized. binding.initialized = true; // 5. Return NormalCompletion(empty). return this.realm.intrinsics.empty; } // ECMA262 8.1.1.1.5 SetMutableBinding(N, V, S) { // We can mutate frozen bindings because of captured bindings. let realm = this.realm; // 1. Let envRec be the declarative Environment Record for which the method was invoked. let envRec = this; let binding = envRec.bindings[N]; // 2. If envRec does not have a binding for N, then if (!binding) { // a. If S is true, throw a ReferenceError exception. if (S) { throw realm.createErrorThrowCompletion(realm.intrinsics.ReferenceError, `${N} not found`); } // b. Perform envRec.CreateMutableBinding(N, true). envRec.CreateMutableBinding(N, true); // c. Perform envRec.InitializeBinding(N, V). envRec.InitializeBinding(N, V); // d. Return NormalCompletion(empty). return this.realm.intrinsics.empty; } // 3. If the binding for N in envRec is a strict binding, let S be true. if (binding.strict) S = true; // 4. If the binding for N in envRec has not yet been initialized, throw a ReferenceError exception. if (!binding.initialized) { throw realm.createErrorThrowCompletion(realm.intrinsics.ReferenceError, `${N} has not yet been initialized`); } else if (binding.mutable) { // 5. Else if the binding for N in envRec is a mutable binding, change its bound value to V. if (binding.hasLeaked) { _singletons.Havoc.value(realm, V); (0, _invariant2.default)(realm.generator); realm.generator.emitBindingAssignment(binding, V); } else { realm.recordModifiedBinding(binding).value = V; } } else { // 6. Else, // a. Assert: This is an attempt to change the value of an immutable binding. // b. If S is true, throw a TypeError exception. if (S) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "attempt to change immutable binding"); } } // 7. Return NormalCompletion(empty). return this.realm.intrinsics.empty; } // ECMA262 8.1.1.1.6 GetBindingValue(N, S) { let realm = this.realm; // 1. Let envRec be the declarative Environment Record for which the method was invoked. let envRec = this; let binding = envRec.bindings[N]; // 2. Assert: envRec has a binding for N. (0, _invariant2.default)(binding, "expected binding"); // 3. If the binding for N in envRec is an uninitialized binding, throw a ReferenceError exception. if (!binding.initialized) { throw realm.createErrorThrowCompletion(realm.intrinsics.ReferenceError); } // 4. Return the value currently bound to N in envRec. if (binding.hasLeaked) { return deriveGetBinding(realm, binding); } (0, _invariant2.default)(binding.value); return binding.value; } // ECMA262 8.1.1.1.7 DeleteBinding(N) { (0, _invariant2.default)(!this.frozen); // 1. Let envRec be the declarative Environment Record for which the method was invoked. let envRec = this; // 2. Assert: envRec has a binding for the name that is the value of N. (0, _invariant2.default)(envRec.bindings[N], "expected binding to exist"); // 3. If the binding for N in envRec cannot be deleted, return false. if (!envRec.bindings[N].deletable) return false; // 4. Remove the binding for N from envRec. this.realm.recordModifiedBinding(envRec.bindings[N]).value = undefined; delete envRec.bindings[N]; // 5. Return true. return true; } // ECMA262 8.1.1.1.8 HasThisBinding() { // 1. Return false. return false; } // ECMA262 8.1.1.1.9 HasSuperBinding() { // 1. Return false. return false; } // ECMA262 8.1.1.1.10 WithBaseObject() { // 1. Return undefined. return this.realm.intrinsics.undefined; } } exports.DeclarativeEnvironmentRecord = DeclarativeEnvironmentRecord; // ECMA262 8.1.1.2 class ObjectEnvironmentRecord extends EnvironmentRecord { constructor(realm, obj) { super(realm); this.object = obj; } // ECMA262 8.1.1.2.1 HasBinding(N) { let realm = this.realm; // 1. Let envRec be the object Environment Record for which the method was invoked. let envRec = this; // 2. Let bindings be the binding object for envRec. let bindings = this.object; // 3. Let foundBinding be ? HasProperty(bindings, N). let foundBinding = (0, _index2.HasProperty)(realm, bindings, N); // 4. If foundBinding is false, return false. if (!foundBinding) return false; // 5. If the withEnvironment flag of envRec is false, return true. if (!envRec.withEnvironment) return true; // 6. Let unscopables be ? Get(bindings, @@unscopables). let unscopables = (0, _index2.Get)(realm, bindings, realm.intrinsics.SymbolUnscopables); // 7. If Type(unscopables) is Object, then if (unscopables instanceof _index.ObjectValue || unscopables instanceof _index.AbstractObjectValue) { // a. Let blocked be ToBoolean(? Get(unscopables, N)). let blocked = _singletons.To.ToBooleanPartial(realm, (0, _index2.Get)(realm, unscopables, N)); // b. If blocked is true, return false. if (blocked) return false; } unscopables.throwIfNotConcrete(); // 8. Return true. return true; } // ECMA262 8.1.1.2.2 CreateMutableBinding(N, D) { let realm = this.realm; // 1. Let envRec be the object Environment Record for which the method was invoked. let envRec = this; // 2. Let bindings be the binding object for envRec. let bindings = envRec.object; // 3. If D is true, let configValue be true; otherwise let configValue be false. let configValue = D ? true : false; // 4. Return ? DefinePropertyOrThrow(bindings, N, PropertyDescriptor{[[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: configValue}). return new _index.BooleanValue(realm, _singletons.Properties.DefinePropertyOrThrow(realm, bindings, N, { value: realm.intrinsics.undefined, writable: true, enumerable: true, configurable: configValue })); } // ECMA262 8.1.1.2.3 CreateImmutableBinding(N, S) { // The concrete Environment Record method CreateImmutableBinding is never used within this specification in association with object Environment Records. (0, _invariant2.default)(false); } // ECMA262 8.1.1.2.4 InitializeBinding(N, V) { // 1. Let envRec be the object Environment Record for which the method was invoked. let envRec = this; // 2. Assert: envRec must have an uninitialized binding for N. // 3. Record that the binding for N in envRec has been initialized. // 4. Return ? envRec.SetMutableBinding(N, V, false). return envRec.SetMutableBinding(N, V, false); } // ECMA262 8.1.1.2.5 SetMutableBinding(N, V, S) { let realm = this.realm; // 1. Let envRec be the object Environment Record for which the method was invoked. let envRec = this; // 2. Let bindings be the binding object for envRec. let bindings = envRec.object; // 3. Return ? Set(bindings, N, V, S). return new _index.BooleanValue(realm, _singletons.Properties.Set(realm, bindings, N, V, S)); } // ECMA262 8.1.1.2.6 GetBindingValue(N, S) { let realm = this.realm; // 1. Let envRec be the object Environment Record for which the method was invoked. let envRec = this; // 2. Let bindings be the binding object for envRec. let bindings = envRec.object; // 3. Let value be ? HasProperty(bindings, N). let value = (0, _index2.HasProperty)(realm, bindings, N); // 4. If value is false, then if (!value) { // a. If S is false, return the value undefined; otherwise throw a ReferenceError exception. if (!S) { return realm.intrinsics.undefined; } else { throw realm.createErrorThrowCompletion(realm.intrinsics.ReferenceError); } } // 5. Return ? Get(bindings, N). return (0, _index2.Get)(realm, bindings, N); } // ECMA262 8.1.1.2.7 DeleteBinding(N) { // 1. Let envRec be the object Environment Record for which the method was invoked. let envRec = this; // 2. Let bindings be the binding object for envRec. let bindings = envRec.object; // 3. Return ? bindings.[[Delete]](N). return bindings.$Delete(N); } // ECMA262 8.1.1.2.8 HasThisBinding() { // 1. Return false. return false; } // ECMA262 8.1.1.2.9 HasSuperBinding() { // 1. Return false. return false; } // ECMA262 8.1.1.2.10 WithBaseObject() { // 1. Let envRec be the object Environment Record for which the method was invoked. let envRec = this; // 2. If the withEnvironment flag of envRec is true, return the binding object for envRec. if (envRec.withEnvironment) return envRec.object; // 3. Otherwise, return undefined. return this.realm.intrinsics.undefined; } } exports.ObjectEnvironmentRecord = ObjectEnvironmentRecord; // ECMA262 8.1.1.3 class FunctionEnvironmentRecord extends DeclarativeEnvironmentRecord { // ECMA262 8.1.1.3.1 BindThisValue(V) { let realm = this.realm; // 1. Let envRec be the function Environment Record for which the method was invoked. let envRec = this; // 2. Assert: envRec.[[ThisBindingStatus]] is not "lexical". (0, _invariant2.default)(envRec.$ThisBindingStatus !== "lexical", "this binding status shouldn't be lexical"); // 3. If envRec.[[ThisBindingStatus]] is "initialized", throw a ReferenceError exception. if (envRec.$ThisBindingStatus === "initialized") { throw realm.createErrorThrowCompletion(realm.intrinsics.ReferenceError); } // 4. Set envRec.[[ThisValue]] to V. envRec.$ThisValue = V; // 5. Set envRec.[[ThisBindingStatus]] to "initialized". envRec.$ThisBindingStatus = "initialized"; // 6. Return V. return V; } // ECMA262 8.1.1.3.2 HasThisBinding() { // 1. Let envRec be the function Environment Record for which the method was invoked. let envRec = this; // 2. If envRec.[[ThisBindingStatus]] is "lexical", return false; otherwise, return true. return envRec.$ThisBindingStatus === "lexical" ? false : true; } // ECMA262 8.1.1.3.3 HasSuperBinding() { // 1. Let envRec be the function Environment Record for which the method was invoked. let envRec = this; // 2. If envRec.[[ThisBindingStatus]] is "lexical", return false. if (envRec.$ThisBindingStatus === "lexical") return false; // 3. If envRec.[[HomeObject]] has the value undefined, return false; otherwise, return true. if (envRec.$HomeObject === undefined) { return false; } else { return true; } } // ECMA262 8.1.1.3.4 GetThisBinding() { let realm = this.realm; // 1. Let envRec be the function Environment Record for which the method was invoked. let envRec = this; // 2. Assert: envRec.[[ThisBindingStatus]] is not "lexical". (0, _invariant2.default)(envRec.$ThisBindingStatus !== "lexical", "this binding status shouldn't be lexical"); // 3. If envRec.[[ThisBindingStatus]] is "uninitialized", throw a ReferenceError exception. if (envRec.$ThisBindingStatus === "uninitialized") { throw realm.createErrorThrowCompletion(realm.intrinsics.ReferenceError); } // 4. Return envRec.[[ThisValue]]. return envRec.$ThisValue; } // ECMA262 8.1.1.3.5 GetSuperBase() { // 1. Let envRec be the function Environment Record for which the method was invoked. let envRec = this; // 2. Let home be the value of envRec.[[HomeObject]]. let home = envRec.$HomeObject; // 3. If home has the value undefined, return undefined. if (home === undefined) return this.realm.intrinsics.undefined; // 4. Assert: Type(home) is Object. (0, _invariant2.default)(home instanceof _index.ObjectValue, "expected object value"); // 5. Return ? home.[[GetPrototypeOf]](). return home.$GetPrototypeOf(); } } exports.FunctionEnvironmentRecord = FunctionEnvironmentRecord; // ECMA262 8.1.1.4 class GlobalEnvironmentRecord extends EnvironmentRecord { // ECMA262 8.1.1.4.1 HasBinding(N) { // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let DclRec be envRec.[[DeclarativeRecord]]. let DclRec = envRec.$DeclarativeRecord; // 3. If DclRec.HasBinding(N) is true, return true. if (DclRec.HasBinding(N)) return true; // 4. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 5. Return ? ObjRec.HasBinding(N). return ObjRec.HasBinding(N); } // ECMA262 8.1.1.4.2 CreateMutableBinding(N, D) { let realm = this.realm; // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let DclRec be envRec.[[DeclarativeRecord]]. let DclRec = envRec.$DeclarativeRecord; // 3. If DclRec.HasBinding(N) is true, throw a TypeError exception. if (DclRec.HasBinding(N)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 4. Return DclRec.CreateMutableBinding(N, D). return DclRec.CreateMutableBinding(N, D, true); } // ECMA262 8.1.1.4.3 CreateImmutableBinding(N, S) { let realm = this.realm; // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let DclRec be envRec.[[DeclarativeRecord]]. let DclRec = envRec.$DeclarativeRecord; // 3. If DclRec.HasBinding(N) is true, throw a TypeError exception. if (DclRec.HasBinding(N)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 4. Return DclRec.CreateImmutableBinding(N, S). return DclRec.CreateImmutableBinding(N, S, true); } // ECMA262 8.1.1.4.4 InitializeBinding(N, V) { // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let DclRec be envRec.[[DeclarativeRecord]]. let DclRec = envRec.$DeclarativeRecord; // 3. If DclRec.HasBinding(N) is true, then if (DclRec.HasBinding(N)) { // a. Return DclRec.InitializeBinding(N, V). return DclRec.InitializeBinding(N, V); } // 4. Assert: If the binding exists, it must be in the object Environment Record. // 5. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 6. Return ? ObjRec.InitializeBinding(N, V). return ObjRec.InitializeBinding(N, V); } // ECMA262 8.1.1.4.5 SetMutableBinding(N, V, S) { // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let DclRec be envRec.[[DeclarativeRecord]]. let DclRec = envRec.$DeclarativeRecord; // 3. If DclRec.HasBinding(N) is true, then if (DclRec.HasBinding(N)) { // a. Return DclRec.SetMutableBinding(N, V, S). return DclRec.SetMutableBinding(N, V, S); } // 4. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 5. Return ? ObjRec.SetMutableBinding(N, V, S). return ObjRec.SetMutableBinding(N, V, S); } // ECMA262 8.1.1.4.6 GetBindingValue(N, S) { // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let DclRec be envRec.[[DeclarativeRecord]]. let DclRec = envRec.$DeclarativeRecord; // 3. If DclRec.HasBinding(N) is true, then if (DclRec.HasBinding(N)) { // a. Return DclRec.GetBindingValue(N, S). return DclRec.GetBindingValue(N, S); } // 4. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 5. Return ? ObjRec.GetBindingValue(N, S). return ObjRec.GetBindingValue(N, S); } // ECMA262 8.1.1.4.7 DeleteBinding(N) { let realm = this.realm; // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let DclRec be envRec.[[DeclarativeRecord]]. let DclRec = envRec.$DeclarativeRecord; // 3. If DclRec.HasBinding(N) is true, then if (DclRec.HasBinding(N)) { // a. Return DclRec.DeleteBinding(N). return DclRec.DeleteBinding(N); } // 4. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 5. Let globalObject be the binding object for ObjRec. let globalObject = ObjRec.object; // 6. Let existingProp be ? HasOwnProperty(globalObject, N). let existingProp = (0, _index2.HasOwnProperty)(realm, globalObject, N); // 7. If existingProp is true, then if (existingProp) { // a. Let status be ? ObjRec.DeleteBinding(N). let status = ObjRec.DeleteBinding(N); // b. If status is true, then if (status) { // i. Let varNames be envRec.[[VarNames]]. let varNames = envRec.$VarNames; // ii. If N is an element of varNames, remove that element from the varNames. if (varNames.indexOf(N) >= 0) { varNames.splice(varNames.indexOf(N), 1); } } // c. Return status. return status; } // 8. Return true. return true; } // ECMA262 8.1.1.4.8 HasThisBinding() { // 1. Return true. return true; } // ECMA262 8.1.1.4.9 HasSuperBinding() { // 1. Return true. return true; } // ECMA262 8.1.1.4.10 WithBaseObject() { // 1. Return undefined. return this.realm.intrinsics.undefined; } // ECMA262 8.1.1.4.11 GetThisBinding() { // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; (0, _invariant2.default)(envRec.$GlobalThisValue); // 2. Return envRec.[[GlobalThisValue]]. return envRec.$GlobalThisValue; } // ECMA262 8.1.1.4.12 HasVarDeclaration(N) { // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let varDeclaredNames be envRec.[[VarNames]]. let varDeclaredNames = envRec.$VarNames; // 3. If varDeclaredNames contains the value of N, return true. if (varDeclaredNames.indexOf(N) >= 0) return true; // 4. Return false. return false; } // ECMA262 8.1.1.4.13 HasLexicalDeclaration(N) { // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let DclRec be envRec.[[DeclarativeRecord]]. let DclRec = envRec.$DeclarativeRecord; // 3. Return DclRec.HasBinding(N). return DclRec.HasBinding(N); } // ECMA262 8.1.1.4.14 HasRestrictedGlobalProperty(N) { // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 3. Let globalObject be the binding object for ObjRec. let globalObject = ObjRec.object; // 4. Let existingProp be ? globalObject.[[GetOwnProperty]](N). let existingProp = globalObject.$GetOwnProperty(N); // 5. If existingProp is undefined, return false. if (!existingProp) return false; _singletons.Properties.ThrowIfMightHaveBeenDeleted(existingProp.value); // 6. If existingProp.[[Configurable]] is true, return false. if (existingProp.configurable) return false; // 7. Return true. return true; } // ECMA262 8.1.1.4.15 CanDeclareGlobalVar(N) { let realm = this.realm; // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 3. Let globalObject be the binding object for ObjRec. let globalObject = ObjRec.object; // 4. Let hasProperty be ? HasOwnProperty(globalObject, N). let hasProperty = (0, _index2.HasOwnProperty)(realm, globalObject, N); // 5. If hasProperty is true, return true. if (hasProperty) return true; // 6. Return ? IsExtensible(globalObject). return (0, _index2.IsExtensible)(realm, globalObject); } // ECMA262 8.1.1.4.16 CanDeclareGlobalFunction(N) { let realm = this.realm; // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 3. Let globalObject be the binding object for ObjRec. let globalObject = ObjRec.object; // 4. Let existingProp be ? globalObject.[[GetOwnProperty]](N). let existingProp = globalObject.$GetOwnProperty(N); // 5. If existingProp is undefined, return ? IsExtensible(globalObject). if (!existingProp) return (0, _index2.IsExtensible)(realm, globalObject); _singletons.Properties.ThrowIfMightHaveBeenDeleted(existingProp.value); // 6. If existingProp.[[Configurable]] is true, return true. if (existingProp.configurable) return true; // 7. If IsDataDescriptor(existingProp) is true and existingProp has attribute values {[[Writable]]: true, [[Enumerable]]: true}, return true. if ((0, _index2.IsDataDescriptor)(realm, existingProp) && existingProp.writable && existingProp.enumerable) { return true; } // 8. Return false. return false; } // ECMA262 8.1.1.4.17 CreateGlobalVarBinding(N, D) { let realm = this.realm; // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 3. Let globalObject be the binding object for ObjRec. let globalObject = ObjRec.object; // 4. Let hasProperty be ? HasOwnProperty(globalObject, N). let hasProperty = (0, _index2.HasOwnProperty)(realm, globalObject, N); // 5. Let extensible be ? IsExtensible(globalObject). let extensible = (0, _index2.IsExtensible)(realm, globalObject); // 6. If hasProperty is false and extensible is true, then if (!hasProperty && extensible) { // a. Perform ? ObjRec.CreateMutableBinding(N, D). ObjRec.CreateMutableBinding(N, D); // b. Perform ? ObjRec.InitializeBinding(N, undefined). ObjRec.InitializeBinding(N, this.realm.intrinsics.undefined); } // 7. Let varDeclaredNames be envRec.[[VarNames]]. let varDeclaredNames = envRec.$VarNames; // 8. If varDeclaredNames does not contain the value of N, then if (varDeclaredNames.indexOf(N) < 0) { // a. Append N to varDeclaredNames. varDeclaredNames.push(N); } // 9. Return NormalCompletion(empty). } // ECMA262 8.1.1.4.18 CreateGlobalFunctionBinding(N, V, D) { // 1. Let envRec be the global Environment Record for which the method was invoked. let envRec = this; // 2. Let ObjRec be envRec.[[ObjectRecord]]. let ObjRec = envRec.$ObjectRecord; // 3. Let globalObject be the binding object for ObjRec. let globalObject = ObjRec.object; // 4. Let existingProp be ? globalObject.[[GetOwnProperty]](N). let existingProp = globalObject.$GetOwnProperty(N); // 5. If existingProp is undefined or existingProp.[[Configurable]] is true, then let desc; if (!existingProp || existingProp.configurable) { // a. Let desc be the PropertyDescriptor{[[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D}. desc = { value: V, writable: true, enumerable: true, configurable: D }; } else { // 6. Else, _singletons.Properties.ThrowIfMightHaveBeenDeleted(existingProp.value); // a. Let desc be the PropertyDescriptor{[[Value]]: V }. desc = { value: V }; } // 7. Perform ? DefinePropertyOrThrow(globalObject, N, desc). _singletons.Properties.DefinePropertyOrThrow(this.realm, globalObject, N, desc); // 8. Record that the binding for N in ObjRec has been initialized. // 9. Perform ? Set(globalObject, N, V, false). _singletons.Properties.Set(this.realm, globalObject, N, V, false); // 10. Let varDeclaredNames be envRec.[[VarNames]]. let varDeclaredNames = envRec.$VarNames; // 11. If varDeclaredNames does not contain the value of N, then if (varDeclaredNames.indexOf(N) < 0) { // a. Append N to varDeclaredNames. varDeclaredNames.push(N); } // 12. Return NormalCompletion(empty). } } exports.GlobalEnvironmentRecord = GlobalEnvironmentRecord; // ECMA262 8.1 let uid = 0; class LexicalEnvironment { constructor(realm) { (0, _invariant2.default)(realm, "expected realm"); this.realm = realm; this.destroyed = false; this._uid = uid++; } // For debugging it is convenient to have an ID for each of these. destroy() { this.destroyed = true; // Once the containing environment is destroyed, we can no longer add or remove entries from the environmentRecord // (but we can update existing values). if (this.environmentRecord instanceof DeclarativeEnvironmentRecord) { this.environmentRecord.frozen = true; } } assignToGlobal(globalAst, rvalue) { let globalValue = this.evaluate(globalAst, false); _singletons.Properties.PutValue(this.realm, globalValue, rvalue); } partiallyEvaluateCompletionDeref(ast, strictCode, metadata) { let [result, partial_ast, partial_io] = this.partiallyEvaluateCompletion(ast, strictCode, metadata); if (result instanceof Reference) { result = _singletons.Environment.GetValue(this.realm, result); } return [result, partial_ast, partial_io]; } partiallyEvaluateCompletion(ast, strictCode, metadata) { try { return this.partiallyEvaluate(ast, strictCode, metadata); } catch (err) { if (err instanceof _completions.Completion) return [err, ast, []]; if (err instanceof Error) // rethrowing Error should preserve stack trace throw err; // let's wrap into a proper Error to create stack trace throw new _errors.FatalError(err); } } evaluateCompletionDeref(ast, strictCode, metadata) { let result = this.evaluateCompletion(ast, strictCode, metadata); if (result instanceof Reference) result = _singletons.Environment.GetValue(this.realm, result); return result; } evaluateCompletion(ast, strictCode, metadata) { try { return this.evaluate(ast, strictCode, metadata); } catch (err) { if ((err instanceof _completions.JoinedAbruptCompletions || err instanceof _completions.PossiblyNormalCompletion) && err.containsBreakOrContinue()) { _index.AbstractValue.reportIntrospectionError(err.joinCondition); throw new _errors.FatalError(); } if (err instanceof _completions.AbruptCompletion) return err; if (err instanceof Error) // rethrowing Error should preserve stack trace throw err; // let's wrap into a proper Error to create stack trace throw new _errors.FatalError(err); } } evaluateAbstractCompletion(ast, strictCode, metadata) { try { return this.evaluateAbstract(ast, strictCode, metadata); } catch (err) { if (err instanceof _completions.Completion) return err; if (err instanceof Error) // rethrowing Error should preserve stack trace throw err; // let's wrap into a proper Error to create stack trace if (err instanceof Object) throw new _errors.FatalError(err.constructor.name + ": " + err); throw new _errors.FatalError(err); } } concatenateAndParse(sources, sourceType = "script") { let asts = []; let code = {}; let directives = []; for (let source of sources) { try { let node = (0, _parse2.default)(this.realm, source.fileContents, source.filePath, sourceType); if (source.sourceMapContents && source.sourceMapContents.length > 0) this.fixup_source_locations(node, source.sourceMapContents); this.fixup_filenames(node); asts = asts.concat(node.program.body); code[source.filePath] = source.fileContents; directives = directives.concat(node.program.directives); } catch (e) { if (e instanceof _completions.ThrowCompletion) { let error = e.value; if (error instanceof _index.ObjectValue) { let message = error.$Get("message", error); message.value = `Syntax error: ${message.value}`; e.location.source = source.filePath; // the position was not located properly on the // syntax errors happen on one given position, so start position = end position e.location.start = { line: e.location.line, column: e.location.column }; e.location.end = { line: e.location.line, column: e.location.column }; let diagnostic = new _errors.CompilerDiagnostic(message.value, e.location, "PP1004", "FatalError"); this.realm.handleError(diagnostic); throw new _errors.FatalError(message.value); } } throw e; } } return [t.file(t.program(asts, directives)), code]; } executeSources(sources, sourceType = "script", onParse = undefined) { let context = new _realm.ExecutionContext(); context.lexicalEnvironment = this; context.variableEnvironment = this; context.realm = this.realm; this.realm.pushContext(context); let res, code; try { let ast; [ast, code] = this.concatenateAndParse(sources, sourceType); if (onParse) onParse(ast); res = this.evaluateCompletion(ast, false); } finally { this.realm.popContext(context); this.realm.onDestroyScope(context.lexicalEnvironment); if (!this.destroyed) this.realm.onDestroyScope(this); (0, _invariant2.default)(this.realm.activeLexicalEnvironments.size === 0); } if (res instanceof _completions.AbruptCompletion) return [res, code]; return [_singletons.Environment.GetValue(this.realm, res), code]; } executePartialEvaluator(sources, options = _options.defaultOptions, sourceType = "script") { let [ast, code] = this.concatenateAndParse(sources, sourceType); let context = new _realm.ExecutionContext(); context.lexicalEnvironment = this; context.variableEnvironment = this; context.realm = this.realm; this.realm.pushContext(context); let partialAST; try { [, partialAST] = this.partiallyEvaluateCompletionDeref(ast, false); } finally { this.realm.popContext(context); this.realm.onDestroyScope(context.lexicalEnvironment); if (!this.destroyed) this.realm.onDestroyScope(this); (0, _invariant2.default)(this.realm.activeLexicalEnvironments.size === 0); } (0, _invariant2.default)(partialAST.type === "File"); let fileAst = partialAST; let prog = t.program(fileAst.program.body, ast.program.directives); this.fixup_filenames(prog); // The type signature for generate is not complete, hence the any return (0, _babelGenerator2.default)(prog, { sourceMaps: options.sourceMaps }, code); } execute(code, filename, map = "", sourceType = "script", onParse = undefined) { let context = new _realm.ExecutionContext(); context.lexicalEnvironment = this; context.variableEnvironment = this; context.realm = this.realm; this.realm.pushContext(context); let ast, res; try { try { ast = (0, _parse2.default)(this.realm, code, filename, sourceType); } catch (e) { if (e instanceof _completions.ThrowCompletion) return e; throw e; } if (onParse) onParse(ast); if (map.length > 0) this.fixup_source_locations(ast, map); this.fixup_filenames(ast); res = this.evaluateCompletion(ast, false); } finally { this.realm.popContext(context); // Avoid destroying "this" scope as execute may be called many times. if (context.lexicalEnvironment !== this) this.realm.onDestroyScope(context.lexicalEnvironment); (0, _invariant2.default)(this.realm.activeLexicalEnvironments.size === 1); } if (res instanceof _completions.AbruptCompletion) return res; return _singletons.Environment.GetValue(this.realm, res); } fixup_source_locations(ast, map) { const smc = new sourceMap.SourceMapConsumer(map); (0, _traverseFast2.default)(ast, node => { let loc = node.loc; if (!loc) return false; fixup(loc, loc.start); fixup(loc, loc.end); fixup_comments(node.leadingComments); fixup_comments(node.innerComments); fixup_comments(node.trailingComments); return false; function fixup(new_loc, new_pos) { let old_pos = smc.originalPositionFor({ line: new_pos.line, column: new_pos.column }); if (old_pos.source === null) return; new_pos.line = old_pos.line; new_pos.column = old_pos.column; new_loc.source = old_pos.source; } function fixup_comments(comments) { if (!comments) return; for (let c of comments) { let cloc = c.loc; if (!cloc) continue; fixup(cloc, cloc.start); fixup(cloc, cloc.end); } } }); } fixup_filenames(ast) { (0, _traverseFast2.default)(ast, node => { let loc = node.loc; if (!loc || !loc.source) { node.leadingComments = null; node.innerComments = null; node.trailingComments = null; node.loc = null; } else { let filename = loc.source; loc.filename = filename; fixup_comments(node.leadingComments, filename); fixup_comments(node.innerComments, filename); fixup_comments(node.trailingComments, filename); } return false; function fixup_comments(comments, filename) { if (!comments) return; for (let c of comments) { if (c.loc) { c.loc.filename = filename; c.loc.source = filename; } } } }); } evaluate(ast, strictCode, metadata) { if (this.realm.debuggerInstance) { this.realm.debuggerInstance.checkForActions(ast); } let res = this.evaluateAbstract(ast, strictCode, metadata); (0, _invariant2.default)(res instanceof _index.Value || res instanceof Reference, ast.type); return res; } evaluateAbstract(ast, strictCode, metadata) { this.realm.currentLocation = ast.loc; this.realm.testTimeout(); let evaluator = this.realm.evaluators[ast.type]; if (evaluator) { let result = evaluator(ast, strictCode, this, this.realm, metadata); return result; } throw new TypeError(`Unsupported node type ${ast.type}`); } partiallyEvaluate(ast, strictCode, metadata) { let partialEvaluator = this.realm.partialEvaluators[ast.type]; if (partialEvaluator) { return partialEvaluator(ast, strictCode, this, this.realm, metadata); } let err = new TypeError(`Unsupported node type ${ast.type}`); throw err; } } exports.LexicalEnvironment = LexicalEnvironment; // ECMA262 6.2.3 // A Reference is a resolved name or property binding. A Reference consists of three components, the base value, // the referenced name and the Boolean valued strict reference flag. The base value is either undefined, an Object, // a Boolean, a String, a Symbol, a Number, or an Environment Record. A base value of undefined indicates that the // Reference could not be resolved to a binding. The referenced name is a String or Symbol value. function mightBecomeAnObject(base) { let type = base.getType(); // The top Value type might be able to become an object. We let it // pass and error later if it can't. return type === _index.Value || type === _PrimitiveValue2.default || type === _index.BooleanValue || type === _index.StringValue || type === _index.SymbolValue || type === _index.NumberValue || type === _index.IntegralValue; } class Reference { constructor(base, refName, strict, thisValue) { (0, _invariant2.default)(base instanceof _index.AbstractObjectValue || base === undefined || base instanceof _index.ObjectValue || base instanceof EnvironmentRecord || mightBecomeAnObject(base)); this.base = base; this.referencedName = refName; (0, _invariant2.default)(!(refName instanceof _index.AbstractValue) || !(refName.mightNotBeString() && refName.mightNotBeNumber() && !refName.isSimpleObject() && // if the base is a simple abstract object but // the refName is not simple, this is also okay base instanceof _index.AbstractValue && !base.isSimpleObject())); this.strict = strict; this.thisValue = thisValue; (0, _invariant2.default)(thisValue === undefined || !(base instanceof EnvironmentRecord)); } } exports.Reference = Reference; //# sourceMappingURL=environment.js.map /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ var base64 = __webpack_require__(877) var ieee754 = __webpack_require__(878) var isArray = __webpack_require__(879) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() /* * Export kMaxLength after typed array support is determined. */ exports.kMaxLength = kMaxLength() function typedArraySupport () { try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length) } that.length = length } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual) } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that } function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end) newBuf.__proto__ = Buffer.prototype } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start] } } return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(14))) /***/ }), /* 14 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { /* eslint-disable node/no-deprecated-api */ var buffer = __webpack_require__(13) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IsConcatSpreadable = IsConcatSpreadable; exports.IsGenericDescriptor = IsGenericDescriptor; exports.IsAccessorDescriptor = IsAccessorDescriptor; exports.IsDataDescriptor = IsDataDescriptor; exports.OrdinaryIsExtensible = OrdinaryIsExtensible; exports.IsExtensible = IsExtensible; exports.IsCallable = IsCallable; exports.IsConstructor = IsConstructor; exports.IsInteger = IsInteger; exports.IsPropertyKey = IsPropertyKey; exports.IsArray = IsArray; exports.IsInTailPosition = IsInTailPosition; exports.IsRegExp = IsRegExp; exports.IsIdentifierRef = IsIdentifierRef; exports.IsFunctionDefinition = IsFunctionDefinition; exports.IsAnonymousFunctionDefinition = IsAnonymousFunctionDefinition; exports.IsArrayIndex = IsArrayIndex; exports.IsPromise = IsPromise; exports.IsDetachedBuffer = IsDetachedBuffer; exports.IsIntrospectionError = IsIntrospectionError; exports.IsStatic = IsStatic; exports.IsStatement = IsStatement; var _errors = __webpack_require__(6); var _get = __webpack_require__(19); var _index = __webpack_require__(0); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _has = __webpack_require__(42); var _babelTypes = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // ECMA262 22.1.3.1.1 /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function IsConcatSpreadable(realm, O) { // 1. If Type(O) is not Object, return false. if (!O.mightBeObject()) return false; O = O.throwIfNotObject(); // 2. Let spreadable be ? Get(O, @@isConcatSpreadable). let spreadable = (0, _get.Get)(realm, O, realm.intrinsics.SymbolIsConcatSpreadable); // 3. If spreadable is not undefined, return ToBoolean(spreadable). if (!spreadable.mightBeUndefined()) return _singletons.To.ToBooleanPartial(realm, spreadable); spreadable.throwIfNotConcrete(); // 4. Return ? IsArray(O). return IsArray(realm, O); } // ECMA262 6.2.4.3 function IsGenericDescriptor(realm, Desc) { // 1. If Desc is undefined, return false. if (!Desc) return false; // 2. If IsAccessorDescriptor(Desc) and IsDataDescriptor(Desc) are both false, return true. if (!IsAccessorDescriptor(realm, Desc) && !IsDataDescriptor(realm, Desc)) return true; // 3. Return false. return false; } // ECMA262 6.2.4.1 function IsAccessorDescriptor(realm, Desc) { // 1. If Desc is undefined, return false. if (!Desc) return false; // 2. If both Desc.[[Get]] and Desc.[[Set]] are absent, return false. if (!("get" in Desc) && !("set" in Desc)) return false; // 3. Return true. return true; } // ECMA262 6.2.4.2 function IsDataDescriptor(realm, Desc) { // If Desc is undefined, return false. if (!Desc) return false; // If both Desc.[[Value]] and Desc.[[Writable]] are absent, return false. if (!("value" in Desc) && !("writable" in Desc)) return false; // Return true. return true; } // ECMA262 9.1.3.1 function OrdinaryIsExtensible(realm, O) { // 1. Return the value of the [[Extensible]] internal slot of O. return O.getExtensible(); } // ECMA262 7.2.5 function IsExtensible(realm, O) { // 1. Assert: Type(O) is Object. // 2. Return ? O.[[IsExtensible]](). return O.$IsExtensible(); } // ECMA262 7.2.3 function IsCallable(realm, func) { // 1. If Type(argument) is not Object, return false. if (!func.mightBeObject()) return false; if ((0, _has.HasCompatibleType)(func, _index.FunctionValue)) return true; if (func.isSimpleObject()) return false; // 2. If argument has a [[Call]] internal method, return true. func = func.throwIfNotConcreteObject(); if (func.$Call) return true; // 3. Return false. return false; } // ECMA262 7.2.4 function IsConstructor(realm, argument) { // 1. If Type(argument) is not Object, return false. if (!argument.mightBeObject()) return false; // 2. If argument has a [[Construct]] internal method, return true. argument = argument.throwIfNotConcreteObject(); if (argument.$Construct) return true; // 3. Return false. return false; } // ECMA262 7.2.6 function IsInteger(realm, argument) { // 1. If Type(argument) is not Number, return false. (0, _invariant2.default)(typeof argument === "number", "Type(argument) is not number"); // 2. If argument is NaN, +∞, or -∞, return false. if (isNaN(argument) || argument === +Infinity || argument === -Infinity) return false; // 3. If floor(abs(argument)) ≠ abs(argument), return false. if (Math.floor(Math.abs(argument)) !== Math.abs(argument)) return false; // 4. Return true. return true; } // ECMA262 7.2.7 function IsPropertyKey(realm, arg) { // We allow native strings to be passed around to avoid constructing a StringValue if (typeof arg === "string") return true; // 1. If Type(argument) is String, return true. if (arg instanceof _index.StringValue) return true; // 2. If Type(argument) is Symbol, return true. if (arg instanceof _index.SymbolValue) return true; if (arg instanceof _index.AbstractValue) { _index.AbstractValue.reportIntrospectionError(arg); throw new _errors.FatalError(); } // 3. Return false. return false; } // ECMA262 7.2.2 function IsArray(realm, argument) { // 1. If Type(argument) is not Object, return false. if (!argument.mightBeObject()) return false; // 2. If argument is an Array exotic object, return true. if (argument instanceof _index.ArrayValue || argument === realm.intrinsics.ArrayPrototype) return true; // 3. If argument is a Proxy exotic object, then if (argument instanceof _index.ProxyValue) { // a. If the value of the [[ProxyHandler]] internal slot of argument is null, throw a TypeError exception. if (!argument.$ProxyHandler || argument.$ProxyHandler instanceof _index.NullValue) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // b. Let target be the value of the [[ProxyTarget]] internal slot of argument. let target = argument.$ProxyTarget; // c. Return ? IsArray(target). return IsArray(realm, target); } // 4. Return false. if (!argument.isSimpleObject()) argument.throwIfNotConcrete(); return false; } // ECMA262 14.6.1 function IsInTailPosition(realm, node) { // TODO #1008: implement tail calls return false; } // ECMA262 7.2.8 function IsRegExp(realm, argument) { // 1. If Type(argument) is not Object, return false. if (!argument.mightBeObject()) return false; argument = argument.throwIfNotObject(); // 2. Let isRegExp be ? Get(argument, @@match). let isRegExp = (0, _get.Get)(realm, argument, realm.intrinsics.SymbolMatch); // 3. If isRegExp is not undefined, return ToBoolean(isRegExp). if (isRegExp !== undefined) return _singletons.To.ToBooleanPartial(realm, isRegExp) === true; // 4. If argument has a [[RegExpMatcher]] internal slot, return true. if (argument.$RegExpMatcher) return true; // 5. Return false. return false; } // ECMA262 12.2.1.4 Static Semantics: IsIdentifierRef // ECMA262 12.3.1.4 Static Semantics: IsIdentifierRef function IsIdentifierRef(realm, node) { switch (node.type) { // ECMA262 12.2.1.4 Static Semantics: IsIdentifierRef case "Identifier": return true; // ECMA262 12.3.1.4 Static Semantics: IsIdentifierRef case "MemberExpression": return false; default: throw Error("Unexpected AST form : " + node.type); } } // 12.2.1.3 Static Semantics: IsFunctionDefinition // 12.2.1.3 Static Semantics: IsFunctionDefinition // 12.13 Binary Logical Operators // 12.3.1.2 Static Semantics: IsFunctionDefinition // 12.15.2 Static Semantics: IsFunctionDefinition function IsFunctionDefinition(realm, node) { switch (node.type) { // 12.2.1.3 Static Semantics: IsFunctionDefinition case "ThisExpression": case "Identifier": case "StringLiteral": case "NumericLiteral": case "BooleanLiteral": case "NullLiteral": case "RegExpLiteral": case "ArrayExpression": case "ObjectExpression": case "TemplateLiteral": case "ConditionalExpression": return false; // 12.2.1.3 Static Semantics: IsFunctionDefinition case "UpdateExpression": return false; // 12.13 Binary Logical Operators case "BinaryExpression": case "LogicalExpression": return false; // 12.3.1.2 Static Semantics: IsFunctionDefinition case "MemberExpression": case "CallExpression": case "NewExpression": case "MetaProperty": case "TaggedTemplateExpression": return false; //12.5.1 Static Semantics: IsFunctionDefinition case "UnaryExpression": return false; //12.15.2 Static Semantics: IsFunctionDefinition case "AssignmentExpression": return false; //12.16.1 Static Semantics: IsFunctionDefinition case "SequenceExpression": return false; case "ArrowFunctionExpression": case "FunctionExpression": return true; // 14.5.8 Static Semantics: IsFunctionDefinition case "ClassExpression": return true; // JSX Extensions: http://facebook.github.io/jsx/ case "JSXElement": return false; default: throw Error("Unexpected AST form : " + node.type); } } // ECMA262 14.1.10 function IsAnonymousFunctionDefinition(realm, node) { // 1. If IsFunctionDefinition of production is false, return false. if (!IsFunctionDefinition(realm, node)) return false; // 2. Let hasName be the result of HasName of production. let hasName = (0, _has.HasName)(realm, node); // 3. If hasName is true, return false. if (hasName === true) return false; // 4. Return true. return true; } // ECMA262 9.4.2 function IsArrayIndex(realm, P) { let key; if (typeof P === "string") { key = P; } else if (P instanceof _index.StringValue) { key = P.value; } else { return false; } let i = _singletons.To.ToUint32(realm, new _index.StringValue(realm, key)); return i !== Math.pow(2, 32) - 1 && _singletons.To.ToString(realm, new _index.NumberValue(realm, i)) === key; } // ECMA262 25.4.1.6 function IsPromise(realm, x) { // 1. If Type(x) is not Object, return false. if (!x.mightBeObject()) return false; // 2. If x does not have a [[PromiseState]] internal slot, return false. x = x.throwIfNotConcreteObject(); if (!x.$PromiseState) return false; // 3. Return true. return true; } // ECMA262 24.1.1.2 function IsDetachedBuffer(realm, arrayBuffer) { // 1. Assert: Type(arrayBuffer) is Object and it has an [[ArrayBufferData]] internal slot. (0, _invariant2.default)(arrayBuffer instanceof _index.ObjectValue && "$ArrayBufferData" in arrayBuffer); // 2. If arrayBuffer's [[ArrayBufferData]] internal slot is null, return true. if (arrayBuffer.$ArrayBufferData === null) return true; // 3. Return false. return false; } function IsIntrospectionError(realm, value) { if (!value.mightBeObject()) return false; value = value.throwIfNotConcreteObject(); return value.$GetPrototypeOf() === realm.intrinsics.__IntrospectionErrorPrototype; } function IsStatic(classElement) { // $FlowFixMe need to backport static property to BabelNodeClassMethod return classElement.static; } function IsStatement(node) { switch (node.type) { case "BlockStatement": case "BreakStatement": case "ContinueStatement": case "DebuggerStatement": case "DoWhileStatement": case "EmptyStatement": case "ExpressionStatement": case "ForInStatement": case "ForStatement": case "FunctionDeclaration": case "IfStatement": case "LabeledStatement": case "ReturnStatement": case "SwitchStatement": case "ThrowStatement": case "TryStatement": case "VariableDeclaration": case "WhileStatement": case "WithStatement": case "ClassDeclaration": case "ExportAllDeclaration": case "ExportDefaultDeclaration": case "ExportNamedDeclaration": case "ForOfStatement": case "ImportDeclaration": case "DeclareClass": case "DeclareFunction": case "DeclareInterface": case "DeclareModule": case "DeclareModuleExports": case "DeclareTypeAlias": case "DeclareVariable": case "InterfaceDeclaration": case "TypeAlias": case "ForAwaitStatement": return true; default: return false; } } //# sourceMappingURL=is.js.map /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const virtualfs = __webpack_require__(696); // Setup the virtual file system. const fs = new virtualfs.VirtualFS(); fs.mkdirpSync("third_party/todomvc/react"); fs.writeFileSync( "third_party/angular-material-1.1.8.css", __webpack_require__(697) ); fs.writeFileSync( "third_party/backbone-1.1.0.js", __webpack_require__(698) ); fs.writeFileSync( "third_party/bootstrap-4.0.0.css", __webpack_require__(699) ); fs.writeFileSync( "third_party/foundation-6.4.2.css", __webpack_require__(700) ); fs.writeFileSync( "third_party/jquery-3.2.1.js", __webpack_require__(701) ); fs.writeFileSync( "third_party/coffeescript-lexer-2.0.1.coffee", __webpack_require__(702) ); fs.writeFileSync( "third_party/lodash.core-4.17.4.js", __webpack_require__(703) ); fs.writeFileSync( "third_party/lodash.min-4.17.4.js.map", __webpack_require__(704) ); fs.writeFileSync( "third_party/mootools-core-1.6.0.js", __webpack_require__(705) ); fs.writeFileSync( "third_party/preact-8.2.5.js", __webpack_require__(706) ); fs.writeFileSync( "third_party/preact-8.2.5.js.map", __webpack_require__(707) ); fs.writeFileSync( "third_party/redux.min-3.7.2.js", __webpack_require__(708) ); fs.writeFileSync( "third_party/source-map.min-0.5.7.js.map", __webpack_require__(709) ); fs.writeFileSync( "third_party/speedometer-es2015-test-2.0.js", __webpack_require__(710) ); fs.writeFileSync( "third_party/todomvc/react/app.jsx", __webpack_require__(711) ); fs.writeFileSync( "third_party/todomvc/react/footer.jsx", __webpack_require__(712) ); fs.writeFileSync( "third_party/todomvc/react/todoItem.jsx", __webpack_require__(713) ); fs.writeFileSync( "third_party/todomvc/typescript-angular.ts", __webpack_require__(714) ); fs.writeFileSync( "third_party/underscore-1.8.3.js", __webpack_require__(715) ); fs.writeFileSync( "third_party/underscore.min-1.8.3.js.map", __webpack_require__(716) ); fs.writeFileSync( "third_party/vue.runtime.esm-nobuble-2.4.4.js", __webpack_require__(717) ); module.exports = fs; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.matchesAst = matchesAst; exports.isAstMatch = isAstMatch; exports.extract = extract; exports.matchesLength = matchesLength; var _fp = __webpack_require__(22); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * Creates a function that matches AST against the given pattern, * * See: isAstMatch() * * @param {Object} pattern Pattern to test against * @return {Function} Function that returns an object with * extracted fields or false when no match found. */ function matchesAst(pattern) { return function (ast) { return isAstMatch(ast, pattern); }; } /** * Matches AST against the given pattern, * * Similar to LoDash.isMatch(), but with the addition that a Function * can be provided to assert various conditions e.g. checking that * number is within a certain range. * * Additionally there are utility functions: * * - extract() can be used to give names to the parts of AST - * these are then returned as a map of key-value pairs. * * - matchesLength() ensures the exact array length is respected. * * @param {Object} ast The AST node to test * @param {Object} pattern Pattern to test against * @return {Object/Boolean} an object with extracted fields * or false when no match found. */ function isAstMatch(ast, pattern) { var extractedFields = {}; var matches = (0, _fp.isMatchWith)(function (value, matcher) { if (typeof matcher === 'function') { var result = matcher(value); if ((typeof result === 'undefined' ? 'undefined' : _typeof(result)) === 'object') { Object.assign(extractedFields, result); } return result; } }, pattern, ast); if (matches) { return extractedFields; } else { return false; } } /** * Utility for extracting values during matching with matchesAst() * * @param {String} fieldName The name to give for the value * @param {Function|Object} matcher Optional matching function or pattern for matchesAst() * @return {Function} */ function extract(fieldName, matcher) { return function (ast) { var extractedFields = _defineProperty({}, fieldName, ast); if ((typeof matcher === 'undefined' ? 'undefined' : _typeof(matcher)) === 'object') { matcher = matchesAst(matcher); } if (typeof matcher === 'function') { var result = matcher(ast); if ((typeof result === 'undefined' ? 'undefined' : _typeof(result)) === 'object') { return Object.assign(extractedFields, result); } if (!result) { return false; } } return extractedFields; }; } /** * Utility for asserting that AST also matches the exact length * of the specified array pattern (in addition to matching * the first items in the array). * * @param {Array} pattern * @return {Function} */ function matchesLength(pattern) { var matcher = matchesAst(pattern); return function (ast) { if (ast.length !== pattern.length) { return false; } return matcher(ast); }; } exports.default = matchesAst; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetFunctionRealm = GetFunctionRealm; exports.OrdinaryGet = OrdinaryGet; exports.GetGlobalObject = GetGlobalObject; exports.GetSubstitution = GetSubstitution; exports.GetMethod = GetMethod; exports.GetPrototypeFromConstructor = GetPrototypeFromConstructor; exports.Get = Get; exports.GetV = GetV; exports.GetThisValue = GetThisValue; exports.GetNewTarget = GetNewTarget; exports.GetTemplateObject = GetTemplateObject; var _completions = __webpack_require__(3); var _realm = __webpack_require__(11); var _index = __webpack_require__(0); var _environment = __webpack_require__(12); var _errors = __webpack_require__(6); var _integrity = __webpack_require__(609); var _index2 = __webpack_require__(5); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // ECMA262 7.3.22 function GetFunctionRealm(realm, obj) { // 1. Assert: obj is a callable object. (0, _invariant2.default)((0, _index2.IsCallable)(realm, obj), "expected callable object"); // ProxyValue moved to realm before // https://github.com/facebook/prepack/pull/1351 // 4. If obj is a Proxy exotic object, then if (obj instanceof _index.ProxyValue) { // a. If the value of the [[ProxyHandler]] internal slot of obj is null, throw a TypeError exception. if (obj.$ProxyHandler instanceof _index.NullValue) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "proxy handler is null"); } (0, _invariant2.default)(obj.$ProxyTarget instanceof _index.ObjectValue); // b. Let proxyTarget be the value of obj's [[ProxyTarget]] internal slot. let proxyTarget = obj.$ProxyTarget; // c. Return ? GetFunctionRealm(proxyTarget). return GetFunctionRealm(realm, proxyTarget); } // 2. If obj has a [[Realm]] internal slot, then if (obj.$Realm) { // a. Return obj's [[Realm]] internal slot. return obj.$Realm; } // 3. If obj is a Bound Function exotic object, then if (obj instanceof _index.BoundFunctionValue) { // a. Let target be obj's [[BoundTargetFunction]] internal slot. let target = obj.$BoundTargetFunction; // b. Return ? GetFunctionRealm(target). return GetFunctionRealm(realm, target); } // 5. Return the current Realm Record. return realm; } // ECMA262 9.1.8.1 /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function OrdinaryGet(realm, O, P, Receiver, dataOnly) { // 1. Assert: IsPropertyKey(P) is true. (0, _invariant2.default)((0, _index2.IsPropertyKey)(realm, P), "expected property key"); // 2. Let desc be ? O.[[GetOwnProperty]](P). let desc = O.$GetOwnProperty(P); if (desc !== undefined && desc.joinCondition !== undefined) { // joined descriptors need special treatment let joinCondition = desc.joinCondition; if (joinCondition !== undefined) { let descriptor2 = desc.descriptor2; desc = desc.descriptor1; let [compl1, gen1, bindings1, properties1, createdObj1] = _singletons.Path.withCondition(joinCondition, () => { return desc !== undefined ? realm.evaluateForEffects(() => OrdinaryGetHelper()) : (0, _realm.construct_empty_effects)(realm); }); desc = descriptor2; let [compl2, gen2, bindings2, properties2, createdObj2] = _singletons.Path.withInverseCondition(joinCondition, () => { return desc !== undefined ? realm.evaluateForEffects(() => OrdinaryGetHelper()) : (0, _realm.construct_empty_effects)(realm); }); // Join the effects, creating an abstract view of what happened, regardless // of the actual value of ownDesc.joinCondition. let joinedEffects = _singletons.Join.joinEffects(realm, joinCondition, [compl1, gen1, bindings1, properties1, createdObj1], [compl2, gen2, bindings2, properties2, createdObj2]); let completion = joinedEffects[0]; if (completion instanceof _completions.PossiblyNormalCompletion) { // in this case one of the branches may complete abruptly, which means that // not all control flow branches join into one flow at this point. // Consequently we have to continue tracking changes until the point where // all the branches come together into one. completion = realm.composeWithSavedCompletion(completion); } // Note that the effects of (non joining) abrupt branches are not included // in joinedEffects, but are tracked separately inside completion. realm.applyEffects(joinedEffects); // return or throw completion if (completion instanceof _completions.AbruptCompletion) throw completion; (0, _invariant2.default)(completion instanceof _index.Value); return completion; } } return OrdinaryGetHelper(); function OrdinaryGetHelper() { let descValue = !desc ? realm.intrinsics.undefined : desc.value === undefined ? realm.intrinsics.undefined : desc.value; (0, _invariant2.default)(descValue instanceof _index.Value); // 3. If desc is undefined, then if (!desc || descValue.mightHaveBeenDeleted()) { // a. Let parent be ? O.[[GetPrototypeOf]](). let parent = O.$GetPrototypeOf(); // b. If parent is null, return undefined. if (parent instanceof _index.NullValue) { // Return the property value since it is now known to be the right value // even in the case when it is empty. return descValue; } // c. Return ? parent.[[Get]](P, Receiver). if (descValue.mightHaveBeenDeleted() && descValue instanceof _index.AbstractValue) { // We don't know for sure that O.P does not exist. let parentVal = OrdinaryGet(realm, parent, P, descValue, true); if (parentVal instanceof _index.UndefinedValue) // even O.P returns undefined it is still the right value. return descValue; // Join with parent value with descValue because the actual value will be // descValue unless it is empty. // Only get the parent value if it does not involve a getter call. // Use a property get for the joined value since it does the check for empty. let cond = _index.AbstractValue.createFromBinaryOp(realm, "!==", descValue, realm.intrinsics.empty); return _singletons.Join.joinValuesAsConditional(realm, cond, descValue, parentVal); } (0, _invariant2.default)(!desc || descValue instanceof _index.EmptyValue); return parent.$Get(P, Receiver); } // 4. If IsDataDescriptor(desc) is true, return desc.[[Value]]. if ((0, _index2.IsDataDescriptor)(realm, desc)) return descValue; if (dataOnly) { (0, _invariant2.default)(descValue instanceof _index.AbstractValue); _index.AbstractValue.reportIntrospectionError(descValue); throw new _errors.FatalError(); } // 5. Assert: IsAccessorDescriptor(desc) is true. (0, _invariant2.default)((0, _index2.IsAccessorDescriptor)(realm, desc), "expected accessor descriptor"); // 6. Let getter be desc.[[Get]]. let getter = desc.get; // 7. If getter is undefined, return undefined. if (!getter || getter instanceof _index.UndefinedValue) return realm.intrinsics.undefined; // 8. Return ? Call(getter, Receiver). return (0, _index2.Call)(realm, getter, Receiver); } } // ECMA262 8.3.6 function GetGlobalObject(realm) { // 1. Let ctx be the running execution context. let ctx = realm.getRunningContext(); // 2. Let currentRealm be ctx's Realm. let currentRealm = ctx.realm; // 3. Return currentRealm.[[GlobalObject]]. return currentRealm.$GlobalObject; } // ECMA262 21.1.3.14.1 function GetSubstitution(realm, matched, str, position, captures, replacement) { // 1. Assert: Type(matched) is String. (0, _invariant2.default)(typeof matched === "string", "expected matched to be a stirng"); // 2. Let matchLength be the number of code units in matched. let matchLength = matched.length; // 3. Assert: Type(str) is String. (0, _invariant2.default)(typeof str === "string", "expected matched to be a stirng"); // 4. Let stringLength be the number of code units in str. let stringLength = str.length; // 5. Assert: position is a nonnegative integer. (0, _invariant2.default)(position >= 0, "expected position to be a nonegative integer"); // 6. Assert: position ≤ stringLength. (0, _invariant2.default)(position <= stringLength, "expected position to be less than string length"); // 7. Assert: captures is a possibly empty List of Strings. (0, _invariant2.default)(Array.isArray(captures), "expected captures to be an array"); // 8. Assert: Type(replacement) is String. (0, _invariant2.default)(typeof replacement === "string", "expected replacement to be a stirng"); // 9. Let tailPos be position + matchLength. let tailPos = position + matchLength; // 10. Let m be the number of elements in captures. let m = captures.length; // 11. Let result be a String value derived from replacement by copying code unit elements // from replacement to result while performing replacements as specified in Table 46. // These $ replacements are done left-to-right, and, once such a replacement is performed, // the new replacement text is not subject to further replacements. let result = ""; for (let i = 0; i < replacement.length; ++i) { let ch = replacement.charAt(i); if (ch !== "$" || i + 1 >= replacement.length) { result += ch; continue; } let peek = replacement.charAt(i + 1); if (peek === "&") { result += matched; } else if (peek === "$") { result += "$"; } else if (peek === "`") { result += str.substr(0, position); } else if (peek === "'") { result += str.substr(tailPos); } else if (peek >= "0" && peek <= "9") { let idx = peek.charCodeAt(0) - "0".charCodeAt(0); if (i + 2 < replacement.length) { let peek2 = replacement.charAt(i + 2); if (peek2 >= "0" && peek2 <= "9") { let newIdx = idx * 10 + (peek2.charCodeAt(0) - "0".charCodeAt(0)); if (newIdx <= m) { idx = newIdx; i += 1; } } } if (idx > 0 && idx <= m) { result += captures[idx - 1] || ""; } else { result += "$" + idx; } } else { result += "$" + peek; } i += 1; } // 12. Return result. return result; } // ECMA262 7.3.9 function GetMethod(realm, V, P) { // 1. Assert: IsPropertyKey(P) is true. (0, _invariant2.default)((0, _index2.IsPropertyKey)(realm, P), "expected property key"); // 2. Let func be ? GetV(V, P). let func = GetV(realm, V, P); // 3. If func is either undefined or null, return undefined. if ((0, _index2.HasSomeCompatibleType)(func, _index.NullValue, _index.UndefinedValue)) { return realm.intrinsics.undefined; } // 4. If IsCallable(func) is false, throw a TypeError exception. if (!(0, _index2.IsCallable)(realm, func)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not callable"); } // 5. Return func. return func; } // ECMA262 9.1.14 function GetPrototypeFromConstructor(realm, constructor, intrinsicDefaultProto) { // 1. Assert: intrinsicDefaultProto is a String value that is this specification's name of an intrinsic // object. The corresponding object must be an intrinsic that is intended to be used as the [[Prototype]] // value of an object. (0, _invariant2.default)(realm.intrinsics[intrinsicDefaultProto], "not a valid proto ref"); // 2. Assert: IsCallable(constructor) is true. (0, _invariant2.default)((0, _index2.IsCallable)(realm, constructor) === true, "expected constructor to be callable"); // 3. Let proto be ? Get(constructor, "prototype"). let proto = Get(realm, constructor, new _index.StringValue(realm, "prototype")); // 4. If Type(proto) is not Object, then if (!(proto instanceof _index.ObjectValue)) { // a. Let realm be ? GetFunctionRealm(constructor). realm = GetFunctionRealm(realm, constructor); // b. Let proto be realm's intrinsic object named intrinsicDefaultProto. proto = realm.intrinsics[intrinsicDefaultProto]; } // 5. Return proto. return proto; } // ECMA262 7.3.1 function Get(realm, O, P) { // 1. Assert: Type(O) is Object. (0, _invariant2.default)(O instanceof _index.ObjectValue || O instanceof _index.AbstractObjectValue, "Not an object value"); // 2. Assert: IsPropertyKey(P) is true. (0, _invariant2.default)((0, _index2.IsPropertyKey)(realm, P), "Not a valid property key"); // 3. Return ? O.[[Get]](P, O). return O.$Get(P, O); } // ECMA262 7.3.2 function GetV(realm, V, P) { // 1. Assert: IsPropertyKey(P) is true. (0, _invariant2.default)((0, _index2.IsPropertyKey)(realm, P), "Not a valid property key"); // 2. Let O be ? ToObject(V). let O = _singletons.To.ToObjectPartial(realm, V); // 3. Return ? O.[[Get]](P, V). return O.$Get(P, V); } // ECMA262 6.2.3.3 function GetThisValue(realm, V) { // 1. Assert: IsPropertyReference(V) is true. (0, _invariant2.default)(_singletons.Environment.IsPropertyReference(realm, V), "expected property reference"); // 2. If IsSuperReference(V) is true, then if (_singletons.Environment.IsSuperReference(realm, V)) { (0, _invariant2.default)(V.thisValue !== undefined); // a. Return the value of the thisValue component of the reference V. return V.thisValue; } // 3. Return GetBase(V). let result = _singletons.Environment.GetBase(realm, V); (0, _invariant2.default)(result instanceof _index.Value); return result; } // ECMA262 8.3.5 function GetNewTarget(realm) { // 1. Let envRec be GetThisEnvironment( ). let envRec = _singletons.Environment.GetThisEnvironment(realm); // 2. Assert: envRec has a [[NewTarget]] field. if (!("$NewTarget" in envRec)) { // In the spec we should not get here because earlier static checks are supposed to prevent it. // However, we do not have an appropriate place to do this check earlier. throw realm.createErrorThrowCompletion(realm.intrinsics.SyntaxError, "new.target not allowed here"); } // 3. Return envRec.[[NewTarget]]. return envRec.$NewTarget || realm.intrinsics.undefined; } function GetTemplateObject(realm, templateLiteral) { // 1. Let rawStrings be TemplateStrings of templateLiteral with argument true. let rawStrings = templateLiteral.quasis.map(quasi => quasi.value.raw); // 2. Let realm be the current Realm Record. realm; // 3. Let templateRegistry be realm.[[TemplateMap]]. let templateRegistry = realm.$TemplateMap; // 4. For each element e of templateRegistry, do for (let e of templateRegistry) { let same; if (e.$Strings.length === rawStrings.length) { same = true; for (let i = 0; i < rawStrings.length; ++i) { if (e.$Strings[i] !== rawStrings[i]) { same = false; break; } } } else { same = false; } // a. If e.[[Strings]] and rawStrings contain the same values in the same order, then if (same) { // i. Return e.[[Array]]. return e.$Array; } } // 5. Let cookedStrings be TemplateStrings of templateLiteral with argument false. let cookedStrings = templateLiteral.quasis.map(quasi => quasi.value.cooked); // 6. Let count be the number of elements in the List cookedStrings. let count = cookedStrings.length; // 7. Let template be ArrayCreate(count). let template = _singletons.Create.ArrayCreate(realm, count); // 8. Let rawObj be ArrayCreate(count). let rawObj = _singletons.Create.ArrayCreate(realm, count); // 9. Let index be 0. let index = 0; // 10. Repeat while index < count while (index < count) { // a. Let prop be ! ToString(index). let prop = _singletons.To.ToString(realm, new _index.NumberValue(realm, index)); // b. Let cookedValue be the String value cookedStrings[index]. let cookedValue = new _index.StringValue(realm, cookedStrings[index]); // c. Call template.[[DefineOwnProperty]](prop, PropertyDescriptor{[[Value]]: cookedValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false}). template.$DefineOwnProperty(prop, { value: cookedValue, writable: false, enumerable: true, configurable: false }); // d. Let rawValue be the String value rawStrings[index]. let rawValue = new _index.StringValue(realm, rawStrings[index]); // e. Call rawObj.[[DefineOwnProperty]](prop, PropertyDescriptor{[[Value]]: rawValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false}). rawObj.$DefineOwnProperty(prop, { value: rawValue, writable: false, enumerable: true, configurable: false }); // f. Let index be index+1. index = index + 1; } // 11. Perform SetIntegrityLevel(rawObj, "frozen"). (0, _integrity.SetIntegrityLevel)(realm, rawObj, "frozen"); // 12. Call template.[[DefineOwnProperty]]("raw", PropertyDescriptor{[[Value]]: rawObj, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false}). template.$DefineOwnProperty("raw", { value: rawObj, writable: false, enumerable: false, configurable: false }); // 13. Perform SetIntegrityLevel(template, "frozen"). (0, _integrity.SetIntegrityLevel)(realm, template, "frozen"); // 14. Append the Record{[[Strings]]: rawStrings, [[Array]]: template} to templateRegistry. templateRegistry.push({ $Strings: rawStrings, $Array: template }); // 15. Return template. return template; } //# sourceMappingURL=get.js.map /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _fp = __webpack_require__(22); var _estraverse = __webpack_require__(145); var _estraverse2 = _interopRequireDefault(_estraverse); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // JSX AST types, as documented in: // https://github.com/facebook/jsx/blob/master/AST.md var jsxExtensionKeys = { JSXIdentifier: [], JSXMemberExpression: ['object', 'property'], JSXNamespacedName: ['namespace', 'name'], JSXEmptyExpression: [], JSXExpressionContainer: ['expression'], JSXOpeningElement: ['name', 'attributes'], JSXClosingElement: ['name'], JSXAttribute: ['name', 'value'], JSXSpreadAttribute: ['argument'], JSXElement: ['openingElement', 'closingElement', 'children'] }; var experimentalExtensionKeys = { ExperimentalRestProperty: ['argument'], ExperimentalSpreadProperty: ['argument'] }; var extensions = { keys: Object.assign({}, jsxExtensionKeys, experimentalExtensionKeys) }; /** * Proxy for ESTraverse. * Providing a single place to easily extend its functionality. * * Exposes the traverse() and replace() methods just like ESTraverse, * plus some custom helpers. */ exports.default = { /** * Traverses AST like ESTraverse.traverse() * @param {Object} tree * @param {Object} cfg Object with optional enter() and leave() methods. * @return {Object} The transformed tree */ traverse: function traverse(tree, cfg) { return _estraverse2.default.traverse(tree, Object.assign(cfg, extensions)); }, /** * Traverses AST like ESTraverse.replace() * @param {Object} tree * @param {Object} cfg Object with optional enter() and leave() methods. * @return {Object} The transformed tree */ replace: function replace(tree, cfg) { return _estraverse2.default.replace(tree, Object.assign(cfg, extensions)); }, /** * Constants to return from enter()/leave() to control traversal: * * - Skip - skips walking child nodes * - Break - ends it all * - Remove - removes the current node (only with replace()) */ VisitorOption: _estraverse2.default.VisitorOption, /** * Searches in AST tree for node which satisfies the predicate. * @param {Object} tree * @param {Function|String} query Search function called with `node` and `parent` * Alternatively it can be string: the node type to search for. * @param {String[]} opts.skipTypes List of node types to skip (not traversing into these nodes) * @return {Object} The found node or undefined when not found */ find: function find(tree, query) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$skipTypes = _ref.skipTypes, skipTypes = _ref$skipTypes === undefined ? [] : _ref$skipTypes; var predicate = this.createFindPredicate(query); var found = void 0; this.traverse(tree, { enter: function enter(node, parent) { if ((0, _fp.includes)(node.type, skipTypes)) { return _estraverse2.default.VisitorOption.Skip; } if (predicate(node, parent)) { found = node; return _estraverse2.default.VisitorOption.Break; } } }); return found; }, createFindPredicate: function createFindPredicate(query) { if ((0, _fp.isString)(query)) { return function (node) { return node.type === query; }; } else { return query; } } }; module.exports = exports['default']; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(1857), __esModule: true }; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { var _ = __webpack_require__(1175).runInContext(); module.exports = __webpack_require__(1176)(_, _); /***/ }), /* 23 */ /***/ (function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default if(!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { Buffer = __webpack_require__(2280).Buffer; } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; } if (base === 16) { this._parseHex(number, start); } else { this._parseBase(number, base, start); } if (number[0] === '-') { this.negative = 1; } this.strip(); if (endian !== 'le') return; this._initArray(this.toArray(), base, endian); }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [ number & 0x3ffffff ]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [ 0 ]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this.strip(); }; function parseHex (str, start, end) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r <<= 4; // 'a' - 'f' if (c >= 49 && c <= 54) { r |= c - 49 + 0xa; // 'A' - 'F' } else if (c >= 17 && c <= 22) { r |= c - 17 + 0xa; // '0' - '9' } else { r |= c & 0xf; } } return r; } BN.prototype._parseHex = function _parseHex (number, start) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; // Scan 24-bit chunks and add them to the number var off = 0; for (i = number.length - 6, j = 0; i >= start; i -= 6) { w = parseHex(number, i, i + 6); this.words[j] |= (w << off) & 0x3ffffff; // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; off += 24; if (off >= 26) { off -= 26; j++; } } if (i + 6 !== start) { w = parseHex(number, start, i + 6); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; } this.strip(); }; function parseBase (str, start, end, mul) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { r += c - 49 + 0xa; // 'A' } else if (c >= 17) { r += c - 17 + 0xa; // '0' - '9' } else { r += c; } } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [ 0 ]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype.strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; BN.prototype.inspect = function inspect () { return (this.red ? ''; }; /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } off += 2; if (off >= 26) { off -= 26; i--; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16); }; BN.prototype.toBuffer = function toBuffer (endian, length) { assert(typeof Buffer !== 'undefined'); return this.toArrayLike(Buffer, endian, length); }; BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); this.strip(); var littleEndian = endian === 'le'; var res = new ArrayType(reqLength); var b, i; var q = this.clone(); if (!littleEndian) { // Assume big-endian for (i = 0; i < reqLength - byteLength; i++) { res[i] = 0; } for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[reqLength - i - 1] = b; } } else { for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[i] = b; } for (; i < reqLength; i++) { res[i] = 0; } } return res; }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this.strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this.strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this.strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this.strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this.strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out.strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out.strip(); } function jumboMulTo (self, num, out) { var fftm = new FFTM(); return fftm.mulp(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out.strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this.strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this.strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this.strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this.strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this.strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this.strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q.strip(); } a.strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modn = function modn (num) { assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return acc; }; // In-place division by number BN.prototype.idivn = function idivn (num) { assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } return this.strip(); }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this.strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { r.strip(); } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); return a.umod(this.m)._forceRed(this); }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })(typeof module === 'undefined' || module, this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(23)(module))) /***/ }), /* 25 */ /***/ (function(module, exports) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isArrayExpression = isArrayExpression; exports.isAssignmentExpression = isAssignmentExpression; exports.isBinaryExpression = isBinaryExpression; exports.isInterpreterDirective = isInterpreterDirective; exports.isDirective = isDirective; exports.isDirectiveLiteral = isDirectiveLiteral; exports.isBlockStatement = isBlockStatement; exports.isBreakStatement = isBreakStatement; exports.isCallExpression = isCallExpression; exports.isCatchClause = isCatchClause; exports.isConditionalExpression = isConditionalExpression; exports.isContinueStatement = isContinueStatement; exports.isDebuggerStatement = isDebuggerStatement; exports.isDoWhileStatement = isDoWhileStatement; exports.isEmptyStatement = isEmptyStatement; exports.isExpressionStatement = isExpressionStatement; exports.isFile = isFile; exports.isForInStatement = isForInStatement; exports.isForStatement = isForStatement; exports.isFunctionDeclaration = isFunctionDeclaration; exports.isFunctionExpression = isFunctionExpression; exports.isIdentifier = isIdentifier; exports.isIfStatement = isIfStatement; exports.isLabeledStatement = isLabeledStatement; exports.isStringLiteral = isStringLiteral; exports.isNumericLiteral = isNumericLiteral; exports.isNullLiteral = isNullLiteral; exports.isBooleanLiteral = isBooleanLiteral; exports.isRegExpLiteral = isRegExpLiteral; exports.isLogicalExpression = isLogicalExpression; exports.isMemberExpression = isMemberExpression; exports.isNewExpression = isNewExpression; exports.isProgram = isProgram; exports.isObjectExpression = isObjectExpression; exports.isObjectMethod = isObjectMethod; exports.isObjectProperty = isObjectProperty; exports.isRestElement = isRestElement; exports.isReturnStatement = isReturnStatement; exports.isSequenceExpression = isSequenceExpression; exports.isSwitchCase = isSwitchCase; exports.isSwitchStatement = isSwitchStatement; exports.isThisExpression = isThisExpression; exports.isThrowStatement = isThrowStatement; exports.isTryStatement = isTryStatement; exports.isUnaryExpression = isUnaryExpression; exports.isUpdateExpression = isUpdateExpression; exports.isVariableDeclaration = isVariableDeclaration; exports.isVariableDeclarator = isVariableDeclarator; exports.isWhileStatement = isWhileStatement; exports.isWithStatement = isWithStatement; exports.isAssignmentPattern = isAssignmentPattern; exports.isArrayPattern = isArrayPattern; exports.isArrowFunctionExpression = isArrowFunctionExpression; exports.isClassBody = isClassBody; exports.isClassDeclaration = isClassDeclaration; exports.isClassExpression = isClassExpression; exports.isExportAllDeclaration = isExportAllDeclaration; exports.isExportDefaultDeclaration = isExportDefaultDeclaration; exports.isExportNamedDeclaration = isExportNamedDeclaration; exports.isExportSpecifier = isExportSpecifier; exports.isForOfStatement = isForOfStatement; exports.isImportDeclaration = isImportDeclaration; exports.isImportDefaultSpecifier = isImportDefaultSpecifier; exports.isImportNamespaceSpecifier = isImportNamespaceSpecifier; exports.isImportSpecifier = isImportSpecifier; exports.isMetaProperty = isMetaProperty; exports.isClassMethod = isClassMethod; exports.isObjectPattern = isObjectPattern; exports.isSpreadElement = isSpreadElement; exports.isSuper = isSuper; exports.isTaggedTemplateExpression = isTaggedTemplateExpression; exports.isTemplateElement = isTemplateElement; exports.isTemplateLiteral = isTemplateLiteral; exports.isYieldExpression = isYieldExpression; exports.isAnyTypeAnnotation = isAnyTypeAnnotation; exports.isArrayTypeAnnotation = isArrayTypeAnnotation; exports.isBooleanTypeAnnotation = isBooleanTypeAnnotation; exports.isBooleanLiteralTypeAnnotation = isBooleanLiteralTypeAnnotation; exports.isNullLiteralTypeAnnotation = isNullLiteralTypeAnnotation; exports.isClassImplements = isClassImplements; exports.isDeclareClass = isDeclareClass; exports.isDeclareFunction = isDeclareFunction; exports.isDeclareInterface = isDeclareInterface; exports.isDeclareModule = isDeclareModule; exports.isDeclareModuleExports = isDeclareModuleExports; exports.isDeclareTypeAlias = isDeclareTypeAlias; exports.isDeclareOpaqueType = isDeclareOpaqueType; exports.isDeclareVariable = isDeclareVariable; exports.isDeclareExportDeclaration = isDeclareExportDeclaration; exports.isDeclareExportAllDeclaration = isDeclareExportAllDeclaration; exports.isDeclaredPredicate = isDeclaredPredicate; exports.isExistsTypeAnnotation = isExistsTypeAnnotation; exports.isFunctionTypeAnnotation = isFunctionTypeAnnotation; exports.isFunctionTypeParam = isFunctionTypeParam; exports.isGenericTypeAnnotation = isGenericTypeAnnotation; exports.isInferredPredicate = isInferredPredicate; exports.isInterfaceExtends = isInterfaceExtends; exports.isInterfaceDeclaration = isInterfaceDeclaration; exports.isInterfaceTypeAnnotation = isInterfaceTypeAnnotation; exports.isIntersectionTypeAnnotation = isIntersectionTypeAnnotation; exports.isMixedTypeAnnotation = isMixedTypeAnnotation; exports.isEmptyTypeAnnotation = isEmptyTypeAnnotation; exports.isNullableTypeAnnotation = isNullableTypeAnnotation; exports.isNumberLiteralTypeAnnotation = isNumberLiteralTypeAnnotation; exports.isNumberTypeAnnotation = isNumberTypeAnnotation; exports.isObjectTypeAnnotation = isObjectTypeAnnotation; exports.isObjectTypeInternalSlot = isObjectTypeInternalSlot; exports.isObjectTypeCallProperty = isObjectTypeCallProperty; exports.isObjectTypeIndexer = isObjectTypeIndexer; exports.isObjectTypeProperty = isObjectTypeProperty; exports.isObjectTypeSpreadProperty = isObjectTypeSpreadProperty; exports.isOpaqueType = isOpaqueType; exports.isQualifiedTypeIdentifier = isQualifiedTypeIdentifier; exports.isStringLiteralTypeAnnotation = isStringLiteralTypeAnnotation; exports.isStringTypeAnnotation = isStringTypeAnnotation; exports.isThisTypeAnnotation = isThisTypeAnnotation; exports.isTupleTypeAnnotation = isTupleTypeAnnotation; exports.isTypeofTypeAnnotation = isTypeofTypeAnnotation; exports.isTypeAlias = isTypeAlias; exports.isTypeAnnotation = isTypeAnnotation; exports.isTypeCastExpression = isTypeCastExpression; exports.isTypeParameter = isTypeParameter; exports.isTypeParameterDeclaration = isTypeParameterDeclaration; exports.isTypeParameterInstantiation = isTypeParameterInstantiation; exports.isUnionTypeAnnotation = isUnionTypeAnnotation; exports.isVariance = isVariance; exports.isVoidTypeAnnotation = isVoidTypeAnnotation; exports.isJSXAttribute = isJSXAttribute; exports.isJSXClosingElement = isJSXClosingElement; exports.isJSXElement = isJSXElement; exports.isJSXEmptyExpression = isJSXEmptyExpression; exports.isJSXExpressionContainer = isJSXExpressionContainer; exports.isJSXSpreadChild = isJSXSpreadChild; exports.isJSXIdentifier = isJSXIdentifier; exports.isJSXMemberExpression = isJSXMemberExpression; exports.isJSXNamespacedName = isJSXNamespacedName; exports.isJSXOpeningElement = isJSXOpeningElement; exports.isJSXSpreadAttribute = isJSXSpreadAttribute; exports.isJSXText = isJSXText; exports.isJSXFragment = isJSXFragment; exports.isJSXOpeningFragment = isJSXOpeningFragment; exports.isJSXClosingFragment = isJSXClosingFragment; exports.isNoop = isNoop; exports.isParenthesizedExpression = isParenthesizedExpression; exports.isAwaitExpression = isAwaitExpression; exports.isBindExpression = isBindExpression; exports.isClassProperty = isClassProperty; exports.isOptionalMemberExpression = isOptionalMemberExpression; exports.isOptionalCallExpression = isOptionalCallExpression; exports.isClassPrivateProperty = isClassPrivateProperty; exports.isImport = isImport; exports.isDecorator = isDecorator; exports.isDoExpression = isDoExpression; exports.isExportDefaultSpecifier = isExportDefaultSpecifier; exports.isExportNamespaceSpecifier = isExportNamespaceSpecifier; exports.isPrivateName = isPrivateName; exports.isBigIntLiteral = isBigIntLiteral; exports.isTSParameterProperty = isTSParameterProperty; exports.isTSDeclareFunction = isTSDeclareFunction; exports.isTSDeclareMethod = isTSDeclareMethod; exports.isTSQualifiedName = isTSQualifiedName; exports.isTSCallSignatureDeclaration = isTSCallSignatureDeclaration; exports.isTSConstructSignatureDeclaration = isTSConstructSignatureDeclaration; exports.isTSPropertySignature = isTSPropertySignature; exports.isTSMethodSignature = isTSMethodSignature; exports.isTSIndexSignature = isTSIndexSignature; exports.isTSAnyKeyword = isTSAnyKeyword; exports.isTSNumberKeyword = isTSNumberKeyword; exports.isTSObjectKeyword = isTSObjectKeyword; exports.isTSBooleanKeyword = isTSBooleanKeyword; exports.isTSStringKeyword = isTSStringKeyword; exports.isTSSymbolKeyword = isTSSymbolKeyword; exports.isTSVoidKeyword = isTSVoidKeyword; exports.isTSUndefinedKeyword = isTSUndefinedKeyword; exports.isTSNullKeyword = isTSNullKeyword; exports.isTSNeverKeyword = isTSNeverKeyword; exports.isTSThisType = isTSThisType; exports.isTSFunctionType = isTSFunctionType; exports.isTSConstructorType = isTSConstructorType; exports.isTSTypeReference = isTSTypeReference; exports.isTSTypePredicate = isTSTypePredicate; exports.isTSTypeQuery = isTSTypeQuery; exports.isTSTypeLiteral = isTSTypeLiteral; exports.isTSArrayType = isTSArrayType; exports.isTSTupleType = isTSTupleType; exports.isTSUnionType = isTSUnionType; exports.isTSIntersectionType = isTSIntersectionType; exports.isTSConditionalType = isTSConditionalType; exports.isTSInferType = isTSInferType; exports.isTSParenthesizedType = isTSParenthesizedType; exports.isTSTypeOperator = isTSTypeOperator; exports.isTSIndexedAccessType = isTSIndexedAccessType; exports.isTSMappedType = isTSMappedType; exports.isTSLiteralType = isTSLiteralType; exports.isTSExpressionWithTypeArguments = isTSExpressionWithTypeArguments; exports.isTSInterfaceDeclaration = isTSInterfaceDeclaration; exports.isTSInterfaceBody = isTSInterfaceBody; exports.isTSTypeAliasDeclaration = isTSTypeAliasDeclaration; exports.isTSAsExpression = isTSAsExpression; exports.isTSTypeAssertion = isTSTypeAssertion; exports.isTSEnumDeclaration = isTSEnumDeclaration; exports.isTSEnumMember = isTSEnumMember; exports.isTSModuleDeclaration = isTSModuleDeclaration; exports.isTSModuleBlock = isTSModuleBlock; exports.isTSImportEqualsDeclaration = isTSImportEqualsDeclaration; exports.isTSExternalModuleReference = isTSExternalModuleReference; exports.isTSNonNullExpression = isTSNonNullExpression; exports.isTSExportAssignment = isTSExportAssignment; exports.isTSNamespaceExportDeclaration = isTSNamespaceExportDeclaration; exports.isTSTypeAnnotation = isTSTypeAnnotation; exports.isTSTypeParameterInstantiation = isTSTypeParameterInstantiation; exports.isTSTypeParameterDeclaration = isTSTypeParameterDeclaration; exports.isTSTypeParameter = isTSTypeParameter; exports.isExpression = isExpression; exports.isBinary = isBinary; exports.isScopable = isScopable; exports.isBlockParent = isBlockParent; exports.isBlock = isBlock; exports.isStatement = isStatement; exports.isTerminatorless = isTerminatorless; exports.isCompletionStatement = isCompletionStatement; exports.isConditional = isConditional; exports.isLoop = isLoop; exports.isWhile = isWhile; exports.isExpressionWrapper = isExpressionWrapper; exports.isFor = isFor; exports.isForXStatement = isForXStatement; exports.isFunction = isFunction; exports.isFunctionParent = isFunctionParent; exports.isPureish = isPureish; exports.isDeclaration = isDeclaration; exports.isPatternLike = isPatternLike; exports.isLVal = isLVal; exports.isTSEntityName = isTSEntityName; exports.isLiteral = isLiteral; exports.isImmutable = isImmutable; exports.isUserWhitespacable = isUserWhitespacable; exports.isMethod = isMethod; exports.isObjectMember = isObjectMember; exports.isProperty = isProperty; exports.isUnaryLike = isUnaryLike; exports.isPattern = isPattern; exports.isClass = isClass; exports.isModuleDeclaration = isModuleDeclaration; exports.isExportDeclaration = isExportDeclaration; exports.isModuleSpecifier = isModuleSpecifier; exports.isFlow = isFlow; exports.isFlowType = isFlowType; exports.isFlowBaseAnnotation = isFlowBaseAnnotation; exports.isFlowDeclaration = isFlowDeclaration; exports.isFlowPredicate = isFlowPredicate; exports.isJSX = isJSX; exports.isPrivate = isPrivate; exports.isTSTypeElement = isTSTypeElement; exports.isTSType = isTSType; exports.isNumberLiteral = isNumberLiteral; exports.isRegexLiteral = isRegexLiteral; exports.isRestProperty = isRestProperty; exports.isSpreadProperty = isSpreadProperty; var _shallowEqual = _interopRequireDefault(__webpack_require__(235)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isArrayExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ArrayExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isAssignmentExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "AssignmentExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBinaryExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BinaryExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInterpreterDirective(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InterpreterDirective") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDirective(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Directive") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDirectiveLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DirectiveLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBlockStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BlockStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBreakStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BreakStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isCallExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "CallExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isCatchClause(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "CatchClause") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isConditionalExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ConditionalExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isContinueStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ContinueStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDebuggerStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DebuggerStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDoWhileStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DoWhileStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEmptyStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EmptyStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExpressionStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExpressionStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFile(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "File") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isForInStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ForInStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isForStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ForStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isIdentifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Identifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isIfStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "IfStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLabeledStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "LabeledStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isStringLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "StringLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNumericLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NumericLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNullLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NullLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBooleanLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BooleanLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isRegExpLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "RegExpLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLogicalExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "LogicalExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isMemberExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "MemberExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNewExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NewExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isProgram(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Program") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectMethod(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectMethod") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isRestElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "RestElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isReturnStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ReturnStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSequenceExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "SequenceExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSwitchCase(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "SwitchCase") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSwitchStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "SwitchStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isThisExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ThisExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isThrowStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ThrowStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTryStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TryStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUnaryExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UnaryExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUpdateExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UpdateExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isVariableDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "VariableDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isVariableDeclarator(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "VariableDeclarator") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isWhileStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "WhileStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isWithStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "WithStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isAssignmentPattern(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "AssignmentPattern") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isArrayPattern(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ArrayPattern") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isArrowFunctionExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ArrowFunctionExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassBody(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassBody") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportAllDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportAllDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportDefaultDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportDefaultDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportNamedDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportNamedDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isForOfStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ForOfStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImportDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ImportDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImportDefaultSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ImportDefaultSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImportNamespaceSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ImportNamespaceSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImportSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ImportSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isMetaProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "MetaProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassMethod(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassMethod") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectPattern(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectPattern") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSpreadElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "SpreadElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSuper(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Super") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTaggedTemplateExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TaggedTemplateExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTemplateElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TemplateElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTemplateLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TemplateLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isYieldExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "YieldExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isAnyTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "AnyTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isArrayTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ArrayTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBooleanTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BooleanTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBooleanLiteralTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BooleanLiteralTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNullLiteralTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NullLiteralTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassImplements(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassImplements") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareClass(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareClass") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareFunction(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareFunction") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareInterface(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareInterface") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareModule(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareModule") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareModuleExports(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareModuleExports") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareTypeAlias(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareTypeAlias") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareOpaqueType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareOpaqueType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareVariable(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareVariable") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareExportDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareExportDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareExportAllDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareExportAllDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclaredPredicate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclaredPredicate") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExistsTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExistsTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionTypeParam(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionTypeParam") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isGenericTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "GenericTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInferredPredicate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InferredPredicate") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInterfaceExtends(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InterfaceExtends") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInterfaceDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InterfaceDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInterfaceTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InterfaceTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isIntersectionTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "IntersectionTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isMixedTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "MixedTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEmptyTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EmptyTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNullableTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NullableTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNumberLiteralTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NumberLiteralTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNumberTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NumberTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeInternalSlot(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeInternalSlot") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeCallProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeCallProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeIndexer(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeIndexer") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeSpreadProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeSpreadProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isOpaqueType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "OpaqueType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isQualifiedTypeIdentifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "QualifiedTypeIdentifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isStringLiteralTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "StringLiteralTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isStringTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "StringTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isThisTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ThisTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTupleTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TupleTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeofTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeofTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeAlias(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeAlias") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeCastExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeCastExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeParameter(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeParameter") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeParameterDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeParameterDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeParameterInstantiation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeParameterInstantiation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUnionTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UnionTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isVariance(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Variance") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isVoidTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "VoidTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXAttribute(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXAttribute") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXClosingElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXClosingElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXEmptyExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXEmptyExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXExpressionContainer(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXExpressionContainer") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXSpreadChild(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXSpreadChild") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXIdentifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXIdentifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXMemberExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXMemberExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXNamespacedName(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXNamespacedName") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXOpeningElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXOpeningElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXSpreadAttribute(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXSpreadAttribute") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXText(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXText") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXFragment(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXFragment") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXOpeningFragment(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXOpeningFragment") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXClosingFragment(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXClosingFragment") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNoop(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Noop") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isParenthesizedExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ParenthesizedExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isAwaitExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "AwaitExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBindExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BindExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isOptionalMemberExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "OptionalMemberExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isOptionalCallExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "OptionalCallExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassPrivateProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassPrivateProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImport(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Import") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDecorator(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Decorator") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDoExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DoExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportDefaultSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportDefaultSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportNamespaceSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportNamespaceSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPrivateName(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "PrivateName") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBigIntLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BigIntLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSParameterProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSParameterProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSDeclareFunction(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSDeclareFunction") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSDeclareMethod(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSDeclareMethod") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSQualifiedName(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSQualifiedName") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSCallSignatureDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSCallSignatureDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSConstructSignatureDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSConstructSignatureDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSPropertySignature(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSPropertySignature") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSMethodSignature(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSMethodSignature") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSIndexSignature(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSIndexSignature") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSAnyKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSAnyKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNumberKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNumberKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSObjectKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSObjectKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSBooleanKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSBooleanKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSStringKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSStringKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSSymbolKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSSymbolKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSVoidKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSVoidKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSUndefinedKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSUndefinedKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNullKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNullKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNeverKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNeverKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSThisType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSThisType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSFunctionType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSFunctionType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSConstructorType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSConstructorType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeReference(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeReference") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypePredicate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypePredicate") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeQuery(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeQuery") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSArrayType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSArrayType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTupleType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTupleType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSUnionType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSUnionType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSIntersectionType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSIntersectionType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSConditionalType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSConditionalType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSInferType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSInferType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSParenthesizedType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSParenthesizedType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeOperator(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeOperator") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSIndexedAccessType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSIndexedAccessType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSMappedType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSMappedType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSLiteralType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSLiteralType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSExpressionWithTypeArguments(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSExpressionWithTypeArguments") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSInterfaceDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSInterfaceDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSInterfaceBody(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSInterfaceBody") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeAliasDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeAliasDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSAsExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSAsExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeAssertion(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeAssertion") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSEnumDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSEnumDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSEnumMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSEnumMember") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSModuleDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSModuleDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSModuleBlock(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSModuleBlock") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSImportEqualsDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSImportEqualsDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSExternalModuleReference(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSExternalModuleReference") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNonNullExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNonNullExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSExportAssignment(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSExportAssignment") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNamespaceExportDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNamespaceExportDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeParameterInstantiation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeParameterInstantiation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeParameterDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeParameterDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeParameter(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeParameter") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Expression" || "ArrayExpression" === nodeType || "AssignmentExpression" === nodeType || "BinaryExpression" === nodeType || "CallExpression" === nodeType || "ConditionalExpression" === nodeType || "FunctionExpression" === nodeType || "Identifier" === nodeType || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "LogicalExpression" === nodeType || "MemberExpression" === nodeType || "NewExpression" === nodeType || "ObjectExpression" === nodeType || "SequenceExpression" === nodeType || "ThisExpression" === nodeType || "UnaryExpression" === nodeType || "UpdateExpression" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassExpression" === nodeType || "MetaProperty" === nodeType || "Super" === nodeType || "TaggedTemplateExpression" === nodeType || "TemplateLiteral" === nodeType || "YieldExpression" === nodeType || "TypeCastExpression" === nodeType || "JSXElement" === nodeType || "JSXFragment" === nodeType || "ParenthesizedExpression" === nodeType || "AwaitExpression" === nodeType || "BindExpression" === nodeType || "OptionalMemberExpression" === nodeType || "OptionalCallExpression" === nodeType || "Import" === nodeType || "DoExpression" === nodeType || "BigIntLiteral" === nodeType || "TSAsExpression" === nodeType || "TSTypeAssertion" === nodeType || "TSNonNullExpression" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBinary(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Binary" || "BinaryExpression" === nodeType || "LogicalExpression" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isScopable(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Scopable" || "BlockStatement" === nodeType || "CatchClause" === nodeType || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "Program" === nodeType || "ObjectMethod" === nodeType || "SwitchStatement" === nodeType || "WhileStatement" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassDeclaration" === nodeType || "ClassExpression" === nodeType || "ForOfStatement" === nodeType || "ClassMethod" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBlockParent(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BlockParent" || "BlockStatement" === nodeType || "CatchClause" === nodeType || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "Program" === nodeType || "ObjectMethod" === nodeType || "SwitchStatement" === nodeType || "WhileStatement" === nodeType || "ArrowFunctionExpression" === nodeType || "ForOfStatement" === nodeType || "ClassMethod" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBlock(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Block" || "BlockStatement" === nodeType || "Program" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Statement" || "BlockStatement" === nodeType || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "DebuggerStatement" === nodeType || "DoWhileStatement" === nodeType || "EmptyStatement" === nodeType || "ExpressionStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "IfStatement" === nodeType || "LabeledStatement" === nodeType || "ReturnStatement" === nodeType || "SwitchStatement" === nodeType || "ThrowStatement" === nodeType || "TryStatement" === nodeType || "VariableDeclaration" === nodeType || "WhileStatement" === nodeType || "WithStatement" === nodeType || "ClassDeclaration" === nodeType || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ForOfStatement" === nodeType || "ImportDeclaration" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType || "TSDeclareFunction" === nodeType || "TSInterfaceDeclaration" === nodeType || "TSTypeAliasDeclaration" === nodeType || "TSEnumDeclaration" === nodeType || "TSModuleDeclaration" === nodeType || "TSImportEqualsDeclaration" === nodeType || "TSExportAssignment" === nodeType || "TSNamespaceExportDeclaration" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTerminatorless(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Terminatorless" || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "ReturnStatement" === nodeType || "ThrowStatement" === nodeType || "YieldExpression" === nodeType || "AwaitExpression" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isCompletionStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "CompletionStatement" || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "ReturnStatement" === nodeType || "ThrowStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isConditional(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Conditional" || "ConditionalExpression" === nodeType || "IfStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLoop(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Loop" || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "WhileStatement" === nodeType || "ForOfStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isWhile(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "While" || "DoWhileStatement" === nodeType || "WhileStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExpressionWrapper(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExpressionWrapper" || "ExpressionStatement" === nodeType || "TypeCastExpression" === nodeType || "ParenthesizedExpression" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFor(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "For" || "ForInStatement" === nodeType || "ForStatement" === nodeType || "ForOfStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isForXStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ForXStatement" || "ForInStatement" === nodeType || "ForOfStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunction(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Function" || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "ObjectMethod" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassMethod" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionParent(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionParent" || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "ObjectMethod" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassMethod" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPureish(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Pureish" || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassDeclaration" === nodeType || "ClassExpression" === nodeType || "BigIntLiteral" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Declaration" || "FunctionDeclaration" === nodeType || "VariableDeclaration" === nodeType || "ClassDeclaration" === nodeType || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ImportDeclaration" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType || "TSDeclareFunction" === nodeType || "TSInterfaceDeclaration" === nodeType || "TSTypeAliasDeclaration" === nodeType || "TSEnumDeclaration" === nodeType || "TSModuleDeclaration" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPatternLike(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "PatternLike" || "Identifier" === nodeType || "RestElement" === nodeType || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLVal(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "LVal" || "Identifier" === nodeType || "MemberExpression" === nodeType || "RestElement" === nodeType || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || "TSParameterProperty" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSEntityName(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSEntityName" || "Identifier" === nodeType || "TSQualifiedName" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Literal" || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "TemplateLiteral" === nodeType || "BigIntLiteral" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImmutable(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Immutable" || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "JSXAttribute" === nodeType || "JSXClosingElement" === nodeType || "JSXElement" === nodeType || "JSXExpressionContainer" === nodeType || "JSXSpreadChild" === nodeType || "JSXOpeningElement" === nodeType || "JSXText" === nodeType || "JSXFragment" === nodeType || "JSXOpeningFragment" === nodeType || "JSXClosingFragment" === nodeType || "BigIntLiteral" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUserWhitespacable(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UserWhitespacable" || "ObjectMethod" === nodeType || "ObjectProperty" === nodeType || "ObjectTypeInternalSlot" === nodeType || "ObjectTypeCallProperty" === nodeType || "ObjectTypeIndexer" === nodeType || "ObjectTypeProperty" === nodeType || "ObjectTypeSpreadProperty" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isMethod(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Method" || "ObjectMethod" === nodeType || "ClassMethod" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectMember" || "ObjectMethod" === nodeType || "ObjectProperty" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Property" || "ObjectProperty" === nodeType || "ClassProperty" === nodeType || "ClassPrivateProperty" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUnaryLike(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UnaryLike" || "UnaryExpression" === nodeType || "SpreadElement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPattern(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Pattern" || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClass(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Class" || "ClassDeclaration" === nodeType || "ClassExpression" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isModuleDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ModuleDeclaration" || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ImportDeclaration" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportDeclaration" || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isModuleSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ModuleSpecifier" || "ExportSpecifier" === nodeType || "ImportDefaultSpecifier" === nodeType || "ImportNamespaceSpecifier" === nodeType || "ImportSpecifier" === nodeType || "ExportDefaultSpecifier" === nodeType || "ExportNamespaceSpecifier" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlow(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Flow" || "AnyTypeAnnotation" === nodeType || "ArrayTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "BooleanLiteralTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "ClassImplements" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "DeclaredPredicate" === nodeType || "ExistsTypeAnnotation" === nodeType || "FunctionTypeAnnotation" === nodeType || "FunctionTypeParam" === nodeType || "GenericTypeAnnotation" === nodeType || "InferredPredicate" === nodeType || "InterfaceExtends" === nodeType || "InterfaceDeclaration" === nodeType || "InterfaceTypeAnnotation" === nodeType || "IntersectionTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NullableTypeAnnotation" === nodeType || "NumberLiteralTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "ObjectTypeAnnotation" === nodeType || "ObjectTypeInternalSlot" === nodeType || "ObjectTypeCallProperty" === nodeType || "ObjectTypeIndexer" === nodeType || "ObjectTypeProperty" === nodeType || "ObjectTypeSpreadProperty" === nodeType || "OpaqueType" === nodeType || "QualifiedTypeIdentifier" === nodeType || "StringLiteralTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "TupleTypeAnnotation" === nodeType || "TypeofTypeAnnotation" === nodeType || "TypeAlias" === nodeType || "TypeAnnotation" === nodeType || "TypeCastExpression" === nodeType || "TypeParameter" === nodeType || "TypeParameterDeclaration" === nodeType || "TypeParameterInstantiation" === nodeType || "UnionTypeAnnotation" === nodeType || "Variance" === nodeType || "VoidTypeAnnotation" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlowType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FlowType" || "AnyTypeAnnotation" === nodeType || "ArrayTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "BooleanLiteralTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "ExistsTypeAnnotation" === nodeType || "FunctionTypeAnnotation" === nodeType || "GenericTypeAnnotation" === nodeType || "InterfaceTypeAnnotation" === nodeType || "IntersectionTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NullableTypeAnnotation" === nodeType || "NumberLiteralTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "ObjectTypeAnnotation" === nodeType || "StringLiteralTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "TupleTypeAnnotation" === nodeType || "TypeofTypeAnnotation" === nodeType || "UnionTypeAnnotation" === nodeType || "VoidTypeAnnotation" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlowBaseAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FlowBaseAnnotation" || "AnyTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "VoidTypeAnnotation" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlowDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FlowDeclaration" || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlowPredicate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FlowPredicate" || "DeclaredPredicate" === nodeType || "InferredPredicate" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSX(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSX" || "JSXAttribute" === nodeType || "JSXClosingElement" === nodeType || "JSXElement" === nodeType || "JSXEmptyExpression" === nodeType || "JSXExpressionContainer" === nodeType || "JSXSpreadChild" === nodeType || "JSXIdentifier" === nodeType || "JSXMemberExpression" === nodeType || "JSXNamespacedName" === nodeType || "JSXOpeningElement" === nodeType || "JSXSpreadAttribute" === nodeType || "JSXText" === nodeType || "JSXFragment" === nodeType || "JSXOpeningFragment" === nodeType || "JSXClosingFragment" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPrivate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Private" || "ClassPrivateProperty" === nodeType || "PrivateName" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeElement" || "TSCallSignatureDeclaration" === nodeType || "TSConstructSignatureDeclaration" === nodeType || "TSPropertySignature" === nodeType || "TSMethodSignature" === nodeType || "TSIndexSignature" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSType" || "TSAnyKeyword" === nodeType || "TSNumberKeyword" === nodeType || "TSObjectKeyword" === nodeType || "TSBooleanKeyword" === nodeType || "TSStringKeyword" === nodeType || "TSSymbolKeyword" === nodeType || "TSVoidKeyword" === nodeType || "TSUndefinedKeyword" === nodeType || "TSNullKeyword" === nodeType || "TSNeverKeyword" === nodeType || "TSThisType" === nodeType || "TSFunctionType" === nodeType || "TSConstructorType" === nodeType || "TSTypeReference" === nodeType || "TSTypePredicate" === nodeType || "TSTypeQuery" === nodeType || "TSTypeLiteral" === nodeType || "TSArrayType" === nodeType || "TSTupleType" === nodeType || "TSUnionType" === nodeType || "TSIntersectionType" === nodeType || "TSConditionalType" === nodeType || "TSInferType" === nodeType || "TSParenthesizedType" === nodeType || "TSTypeOperator" === nodeType || "TSIndexedAccessType" === nodeType || "TSMappedType" === nodeType || "TSLiteralType" === nodeType || "TSExpressionWithTypeArguments" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNumberLiteral(node, opts) { console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); if (!node) return false; const nodeType = node.type; if (nodeType === "NumberLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isRegexLiteral(node, opts) { console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); if (!node) return false; const nodeType = node.type; if (nodeType === "RegexLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isRestProperty(node, opts) { console.trace("The node type RestProperty has been renamed to RestElement"); if (!node) return false; const nodeType = node.type; if (nodeType === "RestProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSpreadProperty(node, opts) { console.trace("The node type SpreadProperty has been renamed to SpreadElement"); if (!node) return false; const nodeType = node.type; if (nodeType === "SpreadProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isReactElement = isReactElement; exports.getReactSymbol = getReactSymbol; exports.isTagName = isTagName; exports.isReactComponent = isReactComponent; exports.valueIsClassComponent = valueIsClassComponent; exports.valueIsKnownReactAbstraction = valueIsKnownReactAbstraction; exports.valueIsReactLibraryObject = valueIsReactLibraryObject; exports.valueIsLegacyCreateClassComponent = valueIsLegacyCreateClassComponent; exports.valueIsFactoryClassComponent = valueIsFactoryClassComponent; exports.addKeyToReactElement = addKeyToReactElement; exports.getUniqueReactElementKey = getUniqueReactElementKey; exports.forEachArrayValue = forEachArrayValue; exports.convertSimpleClassComponentToFunctionalComponent = convertSimpleClassComponentToFunctionalComponent; exports.convertFunctionalComponentToComplexClassComponent = convertFunctionalComponentToComplexClassComponent; exports.normalizeFunctionalComponentParamaters = normalizeFunctionalComponentParamaters; exports.createReactHintObject = createReactHintObject; exports.getComponentTypeFromRootValue = getComponentTypeFromRootValue; exports.deleteRefAndKeyFromProps = deleteRefAndKeyFromProps; exports.objectHasNoPartialKeyAndRef = objectHasNoPartialKeyAndRef; exports.flattenChildren = flattenChildren; exports.evaluateComponentTreeBranch = evaluateComponentTreeBranch; exports.getProperty = getProperty; exports.isRenderPropFunctionSelfContained = isRenderPropFunctionSelfContained; exports.createReactEvaluatedNode = createReactEvaluatedNode; exports.getComponentName = getComponentName; exports.convertConfigObjectToReactComponentTreeConfig = convertConfigObjectToReactComponentTreeConfig; exports.getValueFromRenderCall = getValueFromRenderCall; exports.sanitizeReactElementForFirstRenderOnly = sanitizeReactElementForFirstRenderOnly; var _realm = __webpack_require__(11); var _environment = __webpack_require__(12); var _completions = __webpack_require__(3); var _index = __webpack_require__(0); var _generator = __webpack_require__(34); var _index2 = __webpack_require__(5); var _BinaryExpression = __webpack_require__(102); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _singletons = __webpack_require__(2); var _babelTraverse = __webpack_require__(60); var _babelTraverse2 = _interopRequireDefault(_babelTraverse); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); var _errors = __webpack_require__(6); var _AbstractValue = __webpack_require__(623); var _AbstractValue2 = _interopRequireDefault(_AbstractValue); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function isReactElement(val) { if (!(val instanceof _index.ObjectValue)) { return false; } let realm = val.$Realm; if (!realm.react.enabled) { return false; } if (realm.react.reactElements.has(val)) { return true; } if (val.properties.has("$$typeof")) { let $$typeof = (0, _index2.Get)(realm, val, "$$typeof"); let globalObject = realm.$GlobalObject; let globalSymbolValue = (0, _index2.Get)(realm, globalObject, "Symbol"); if (globalSymbolValue === realm.intrinsics.undefined) { if ($$typeof instanceof _index.NumberValue) { return $$typeof.value === 0xeac7; } } else if ($$typeof instanceof _index.SymbolValue) { let symbolFromRegistry = realm.globalSymbolRegistry.find(e => e.$Symbol === $$typeof); let _isReactElement = symbolFromRegistry !== undefined && symbolFromRegistry.$Key === "react.element"; if (_isReactElement) { // add to Set to speed up future lookups realm.react.reactElements.add(val); return true; } } } return false; } function getReactSymbol(symbolKey, realm) { let reactSymbol = realm.react.symbols.get(symbolKey); if (reactSymbol !== undefined) { return reactSymbol; } let SymbolFor = realm.intrinsics.Symbol.properties.get("for"); if (SymbolFor !== undefined) { let SymbolForDescriptor = SymbolFor.descriptor; if (SymbolForDescriptor !== undefined) { let SymbolForValue = SymbolForDescriptor.value; if (SymbolForValue !== undefined && typeof SymbolForValue.$Call === "function") { reactSymbol = SymbolForValue.$Call(realm.intrinsics.Symbol, [new _index.StringValue(realm, symbolKey)]); realm.react.symbols.set(symbolKey, reactSymbol); } } } (0, _invariant2.default)(reactSymbol instanceof _index.SymbolValue, `Symbol("${symbolKey}") could not be found in realm`); return reactSymbol; } function isTagName(ast) { return ast.type === "JSXIdentifier" && /^[a-z]|\-/.test(ast.name); } function isReactComponent(name) { return name.length > 0 && name[0] === name[0].toUpperCase(); } function valueIsClassComponent(realm, value) { if (!(value instanceof _index.FunctionValue)) { return false; } let prototype = (0, _index2.Get)(realm, value, "prototype"); if (prototype instanceof _index.ObjectValue) { return _singletons.To.ToBooleanPartial(realm, (0, _index2.Get)(realm, prototype, "isReactComponent")); } return false; } function valueIsKnownReactAbstraction(realm, value) { return value instanceof _index.AbstractObjectValue && realm.react.abstractHints.has(value); } // logger isn't typed otherwise it will increase flow cycle length :() function valueIsReactLibraryObject(realm, value, logger) { if (realm.fbLibraries.react === value) { return true; } // we check that the object is the React or React-like library by checking for // core properties that should exist on it let reactVersion = logger.tryQuery(() => (0, _index2.Get)(realm, value, "version"), undefined); if (!(reactVersion instanceof _index.StringValue)) { return false; } let reactCreateElement = logger.tryQuery(() => (0, _index2.Get)(realm, value, "createElement"), undefined); if (!(reactCreateElement instanceof _index.FunctionValue)) { return false; } let reactCloneElement = logger.tryQuery(() => (0, _index2.Get)(realm, value, "cloneElement"), undefined); if (!(reactCloneElement instanceof _index.FunctionValue)) { return false; } let reactIsValidElement = logger.tryQuery(() => (0, _index2.Get)(realm, value, "isValidElement"), undefined); if (!(reactIsValidElement instanceof _index.FunctionValue)) { return false; } let reactComponent = logger.tryQuery(() => (0, _index2.Get)(realm, value, "Component"), undefined); if (!(reactComponent instanceof _index.FunctionValue)) { return false; } let reactChildren = logger.tryQuery(() => (0, _index2.Get)(realm, value, "Children"), undefined); if (!(reactChildren instanceof _index.ObjectValue)) { return false; } return false; } function valueIsLegacyCreateClassComponent(realm, value) { if (!(value instanceof _index.FunctionValue)) { return false; } let prototype = (0, _index2.Get)(realm, value, "prototype"); if (prototype instanceof _index.ObjectValue) { return prototype.properties.has("__reactAutoBindPairs"); } return false; } function valueIsFactoryClassComponent(realm, value) { if (value instanceof _index.ObjectValue) { return _singletons.To.ToBooleanPartial(realm, (0, _index2.Get)(realm, value, "render")); } return false; } function addKeyToReactElement(realm, reactSerializerState, reactElement) { // we need to apply a key when we're branched let currentKeyValue = (0, _index2.Get)(realm, reactElement, "key") || realm.intrinsics.null; let uniqueKey = getUniqueReactElementKey("", reactSerializerState.usedReactElementKeys); let newKeyValue = new _index.StringValue(realm, uniqueKey); if (currentKeyValue !== realm.intrinsics.null) { newKeyValue = (0, _BinaryExpression.computeBinary)(realm, "+", currentKeyValue, newKeyValue); } // TODO: This might not be safe in DEV because these objects are frozen (Object.freeze). // We should probably go behind the scenes in this case to by-pass that. reactElement.$Set("key", newKeyValue, reactElement); } // we create a unique key for each JSXElement to prevent collisions // otherwise React will detect a missing/conflicting key at runtime and // this can break the reconcilation of JSXElements in arrays function getUniqueReactElementKey(index, usedReactElementKeys) { let key; do { key = Math.random().toString(36).replace(/[^a-z]+/g, "").substring(0, 2); } while (usedReactElementKeys.has(key)); usedReactElementKeys.add(key); if (index !== undefined) { return `${key}${index}`; } return key; } // a helper function to loop over ArrayValues function forEachArrayValue(realm, array, mapFunc) { let lengthValue = (0, _index2.Get)(realm, array, "length"); (0, _invariant2.default)(lengthValue instanceof _index.NumberValue, "Invalid length on ArrayValue during reconcilation"); let length = lengthValue.value; for (let i = 0; i < length; i++) { let elementProperty = array.properties.get("" + i); let elementPropertyDescriptor = elementProperty && elementProperty.descriptor; (0, _invariant2.default)(elementPropertyDescriptor, `Invalid ArrayValue[${i}] descriptor`); let elementValue = elementPropertyDescriptor.value; if (elementValue instanceof _index.Value) { mapFunc(elementValue, elementPropertyDescriptor); } } } function GetDescriptorForProperty(value, propertyName) { let object = value.properties.get(propertyName); (0, _invariant2.default)(object); return object.descriptor; } function convertSimpleClassComponentToFunctionalComponent(realm, complexComponentType, additionalFunctionEffects) { let prototype = complexComponentType.properties.get("prototype"); (0, _invariant2.default)(prototype); (0, _invariant2.default)(prototype.descriptor); prototype.descriptor.configurable = true; _singletons.Properties.DeletePropertyOrThrow(realm, complexComponentType, "prototype"); // fix the length as we've changed the arguments let lengthProperty = GetDescriptorForProperty(complexComponentType, "length"); (0, _invariant2.default)(lengthProperty); lengthProperty.writable = false; lengthProperty.enumerable = false; lengthProperty.configurable = true; // ensure the length value is set to the new value let lengthValue = (0, _index2.Get)(realm, complexComponentType, "length"); (0, _invariant2.default)(lengthValue instanceof _index.NumberValue); lengthValue.value = 2; // change the function kind complexComponentType.$FunctionKind = "normal"; // set the prototype back to an object complexComponentType.$Prototype = realm.intrinsics.FunctionPrototype; // give the function the functional components params complexComponentType.$FormalParameters = [t.identifier("props"), t.identifier("context")]; // add a transform to occur after the additional function has serialized the body of the class additionalFunctionEffects.transforms.push(body => { // as this was a class before and is now a functional component, we need to replace // this.props and this.context to props and context, via the function arugments let funcNode = t.functionExpression(null, [], t.blockStatement(body)); (0, _babelTraverse2.default)(t.file(t.program([t.expressionStatement(funcNode)])), { "Identifier|ThisExpression"(path) { let node = path.node; if (t.isIdentifier(node) && node.name === "this" || t.isThisExpression(node)) { let parentPath = path.parentPath; let parentNode = parentPath.node; if (t.isMemberExpression(parentNode)) { // remove the "this" from the member parentPath.replaceWith(parentNode.property); } else { throw new _errors.FatalError(`conversion of a simple class component to functional component failed due to "this" not being replaced`); } } } }, undefined, undefined, undefined); }); } function createBinding(descriptor, key, object) { return { descriptor, key, object }; } function cloneProperties(realm, properties, object) { let newProperties = new Map(); for (let [propertyName, { descriptor }] of properties) { newProperties.set(propertyName, createBinding((0, _index2.cloneDescriptor)(descriptor), propertyName, object)); } return newProperties; } function cloneSymbols(realm, symbols, object) { let newSymbols = new Map(); for (let [symbol, { descriptor }] of symbols) { newSymbols.set(symbol, createBinding((0, _index2.cloneDescriptor)(descriptor), symbol, object)); } return newSymbols; } function cloneValue(realm, originalValue, _prototype, copyToObject) { if (originalValue instanceof _index.FunctionValue) { return cloneFunction(realm, originalValue, _prototype, copyToObject); } (0, _invariant2.default)(false, "TODO: add support to cloneValue() for more value types"); } function cloneFunction(realm, originalValue, _prototype, copyToObject) { let newValue; if (originalValue instanceof _index.ECMAScriptSourceFunctionValue) { newValue = copyToObject || new _index.ECMAScriptSourceFunctionValue(realm, originalValue.intrinsicName); (0, _invariant2.default)(newValue instanceof _index.ECMAScriptSourceFunctionValue); // $FlowFixMe: complains about Object.assign Object.assign(newValue, originalValue); let properties = cloneProperties(realm, originalValue.properties, newValue); newValue.properties = properties; let symbols = cloneSymbols(realm, originalValue.symbols, newValue); newValue.symbols = symbols; // handle home object + prototype let originalPrototype = originalValue.$HomeObject; (0, _invariant2.default)(originalPrototype instanceof _index.ObjectValue); let prototype = _prototype || clonePrototype(realm, originalPrototype); newValue.$HomeObject = prototype; if (originalPrototype.properties.has("constructor")) { _singletons.Properties.Set(realm, prototype, "constructor", newValue, false); } if (originalValue.properties.has("prototype")) { _singletons.Properties.Set(realm, newValue, "prototype", prototype, false); } } (0, _invariant2.default)(newValue instanceof _index.FunctionValue, "TODO: add support to cloneValue() for more function types"); return newValue; } function clonePrototype(realm, prototype) { (0, _invariant2.default)(prototype instanceof _index.ObjectValue); let newPrototype = new _index.ObjectValue(realm, realm.intrinsics.ObjectPrototype, prototype.intrinsicName); Object.assign(newPrototype, prototype); for (let [propertyName] of prototype.properties) { if (propertyName !== "constructor") { let originalValue = (0, _index2.Get)(realm, prototype, propertyName); let newValue = cloneValue(realm, originalValue, prototype); _singletons.Properties.Set(realm, newPrototype, propertyName, newValue, false); } } for (let [symbol] of prototype.symbols) { let originalValue = (0, _index2.Get)(realm, prototype, symbol); let newValue = cloneValue(realm, originalValue, prototype); _singletons.Properties.Set(realm, newPrototype, symbol, newValue, false); } return newPrototype; } const skipFunctionProperties = new Set(["length", "prototype", "arguments", "name", "caller"]); function convertFunctionalComponentToComplexClassComponent(realm, functionalComponentType, complexComponentType, additionalFunctionEffects) { (0, _invariant2.default)(complexComponentType instanceof _index.ECMAScriptSourceFunctionValue); // get all properties on the functional component that were added in user-code // we add defaultProps as undefined, as merging a class component's defaultProps on to // a differnet component isn't right, we can discard defaultProps instead via folding // we also don't want propTypes from the class component, so we remove that too let userCodePropertiesToAdd = new Map([["defaultProps", createBinding(undefined, "defaultProps", functionalComponentType)], ["propTypes", createBinding(undefined, "propTypes", functionalComponentType)]]); let userCodeSymbolsToAdd = new Map(); for (let [propertyName, binding] of functionalComponentType.properties) { if (!skipFunctionProperties.has(propertyName)) { userCodePropertiesToAdd.set(propertyName, binding); } } for (let [symbol, binding] of functionalComponentType.symbols) { userCodeSymbolsToAdd.set(symbol, binding); } cloneValue(realm, complexComponentType, null, functionalComponentType); // then copy back and properties that were on the original functional component // ensuring we overwrite any existing ones for (let [propertyName, binding] of userCodePropertiesToAdd) { functionalComponentType.properties.set(propertyName, binding); } for (let [symbol, binding] of userCodeSymbolsToAdd) { functionalComponentType.symbols.set(symbol, binding); } // add a transform to occur after the additional function has serialized the body of the class additionalFunctionEffects.transforms.push(body => { // as we've converted a functional component to a complex one, we are going to have issues with // "props" and "context" references, as they're now going to be "this.props" and "this.context". // we simply need a to add to vars to beginning of the body to get around this // if they're not used, any DCE tool post-Prepack (GCC or Uglify) will remove them body.unshift(t.variableDeclaration("var", [t.variableDeclarator(t.identifier("props"), t.memberExpression(t.thisExpression(), t.identifier("props"))), t.variableDeclarator(t.identifier("context"), t.memberExpression(t.thisExpression(), t.identifier("context")))])); }); } function normalizeFunctionalComponentParamaters(func) { func.$FormalParameters = func.$FormalParameters.map((param, i) => { if (i === 0) { return t.isIdentifier(param) ? param : t.identifier("props"); } else { return t.isIdentifier(param) ? param : t.identifier("context"); } }); } function createReactHintObject(object, propertyName, args) { return { object, propertyName, args }; } function getComponentTypeFromRootValue(realm, value) { let _valueIsKnownReactAbstraction = valueIsKnownReactAbstraction(realm, value); if (!(value instanceof _index.ECMAScriptSourceFunctionValue || _valueIsKnownReactAbstraction)) { return null; } if (_valueIsKnownReactAbstraction) { (0, _invariant2.default)(value instanceof _AbstractValue2.default); let reactHint = realm.react.abstractHints.get(value); (0, _invariant2.default)(reactHint); if (typeof reactHint !== "string" && reactHint.object === realm.fbLibraries.reactRelay) { switch (reactHint.propertyName) { case "createFragmentContainer": case "createPaginationContainer": case "createRefetchContainer": (0, _invariant2.default)(Array.isArray(reactHint.args)); // componentType is the 1st argument of a ReactRelay container let componentType = reactHint.args[0]; (0, _invariant2.default)(componentType instanceof _index.ECMAScriptSourceFunctionValue); return componentType; default: (0, _invariant2.default)(false, `unsupported known React abstraction - ReactRelay property "${reactHint.propertyName}" not supported`); } } (0, _invariant2.default)(false, "unsupported known React abstraction"); } else { (0, _invariant2.default)(value instanceof _index.ECMAScriptSourceFunctionValue); return value; } } // props should never have "ref" or "key" properties, as they're part of ReactElement // object instead. to ensure that we can give this hint, we create them and then // delete them, so their descriptor is left undefined. we use this knowledge later // to ensure that when dealing with creating ReactElements with partial config, // we don't have to bail out becuase "config" may or may not have "key" or/and "ref" function deleteRefAndKeyFromProps(realm, props) { let objectValue; if (props instanceof _index.AbstractObjectValue) { let elements = props.values.getElements(); if (elements && elements.size > 0) { objectValue = Array.from(elements)[0]; } // we don't want to serialize in the output that we're making these deletes (0, _invariant2.default)(objectValue instanceof _index.ObjectValue); objectValue.refuseSerialization = true; } _singletons.Properties.Set(realm, props, "ref", realm.intrinsics.undefined, true); props.$Delete("ref"); _singletons.Properties.Set(realm, props, "key", realm.intrinsics.undefined, true); props.$Delete("key"); if (props instanceof _index.AbstractObjectValue) { (0, _invariant2.default)(objectValue instanceof _index.ObjectValue); objectValue.refuseSerialization = false; } } function objectHasNoPartialKeyAndRef(realm, object) { if (object instanceof _AbstractValue2.default) { return true; } return !((0, _index2.Get)(realm, object, "key") instanceof _AbstractValue2.default || (0, _index2.Get)(realm, object, "ref") instanceof _AbstractValue2.default); } function recursivelyFlattenArray(realm, array, targetArray) { forEachArrayValue(realm, array, item => { if (item instanceof _index.ArrayValue) { recursivelyFlattenArray(realm, item, targetArray); } else { let lengthValue = (0, _index2.Get)(realm, targetArray, "length"); (0, _invariant2.default)(lengthValue instanceof _index.NumberValue); _singletons.Properties.Set(realm, targetArray, "" + lengthValue.value, item, true); } }); } function flattenChildren(realm, array) { let flattenedChildren = _singletons.Create.ArrayCreate(realm, 0); recursivelyFlattenArray(realm, array, flattenedChildren); return flattenedChildren; } function evaluateComponentTreeBranch(realm, effects, nested, f) { let [value, generator, modifiedBindings, modifiedProperties, createdObjects] = effects; if (nested) { realm.applyEffects([value, new _generator.Generator(realm), modifiedBindings, modifiedProperties, createdObjects]); } try { return f(generator, value); } finally { if (nested) { realm.restoreBindings(modifiedBindings); realm.restoreProperties(modifiedProperties); } } } function getProperty(realm, object, property) { let binding; if (typeof property === "string") { binding = object.properties.get(property); } else { binding = object.symbols.get(property); } if (!binding) { return realm.intrinsics.undefined; } let descriptor = binding.descriptor; if (!descriptor) { return realm.intrinsics.undefined; } let value; if (descriptor.value) { value = descriptor.value; } else if (descriptor.get || descriptor.set) { _AbstractValue2.default.reportIntrospectionError(object, `react/utils/getProperty unsupported getter/setter property`); throw new _errors.FatalError(); } (0, _invariant2.default)(value instanceof _index.Value, `react/utils/getProperty should not be called on internal properties`); return value; } function visitName(path, state, name, read, write) { // Is the name bound to some local identifier? If so, we don't need to do anything if (path.scope.hasBinding(name, /*noGlobals*/true)) return; // Otherwise, let's record that there's an unbound identifier if (read) state.unboundReads.add(name); if (write) state.unboundWrites.add(name); } function ignorePath(path) { let parent = path.parent; return t.isLabeledStatement(parent) || t.isBreakStatement(parent) || t.isContinueStatement(parent); } let LeakedClosureRefVisitor = { ReferencedIdentifier(path, state) { if (ignorePath(path)) return; let innerName = path.node.name; if (innerName === "arguments") { return; } visitName(path, state, innerName, true, false); }, "AssignmentExpression|UpdateExpression"(path, state) { let doesRead = path.node.operator !== "="; for (let name in path.getBindingIdentifiers()) { visitName(path, state, name, doesRead, true); } } }; function getFunctionBindingInfo(value) { (0, _invariant2.default)(value instanceof _index.ECMAScriptSourceFunctionValue); (0, _invariant2.default)(value.constructor === _index.ECMAScriptSourceFunctionValue); let functionInfo = { unboundReads: new Set(), unboundWrites: new Set() }; let formalParameters = value.$FormalParameters; (0, _invariant2.default)(formalParameters != null); let code = value.$ECMAScriptCode; (0, _invariant2.default)(code != null); (0, _babelTraverse2.default)(t.file(t.program([t.expressionStatement(t.functionExpression(null, formalParameters, code))])), LeakedClosureRefVisitor, null, functionInfo); return functionInfo; } // if a render prop function (a nested additional function) makes // no accesses to bindings in the parent additional function scope // we can determine if the function is self contained function isRenderPropFunctionSelfContained(realm, parentFunc, renderProp, logger // otherwise Flow cycles increases ) { let { unboundReads, unboundWrites } = getFunctionBindingInfo(renderProp); let bindings = Array.from(unboundReads).concat(Array.from(unboundWrites)); for (let name of bindings) { let reference = logger.tryQuery(() => _singletons.Environment.ResolveBinding(realm, name, true, renderProp.$Environment), undefined); if (!reference) { return false; } if (reference.base instanceof _environment.FunctionEnvironmentRecord && reference.base.$FunctionObject === parentFunc) { return false; } } return true; } function createReactEvaluatedNode(status, name) { return { children: [], message: "", name, status }; } function getComponentName(realm, componentType) { (0, _invariant2.default)(componentType instanceof _index.ECMAScriptSourceFunctionValue || componentType instanceof _index.AbstractObjectValue || componentType instanceof _AbstractValue2.default); if (componentType.__originalName) { return componentType.__originalName; } if (realm.fbLibraries.reactRelay !== undefined) { if (componentType === (0, _index2.Get)(realm, realm.fbLibraries.reactRelay, "QueryRenderer")) { return "QueryRenderer"; } } if (componentType instanceof _index.ECMAScriptSourceFunctionValue) { let name = (0, _index2.Get)(realm, componentType, "name"); if (name instanceof _index.StringValue) { return name.value; } } return "Unknown"; } function convertConfigObjectToReactComponentTreeConfig(realm, config) { // defaults let firstRenderOnly = false; if (!(config instanceof _index.UndefinedValue)) { for (let [key] of config.properties) { let propValue = getProperty(realm, config, key); if (propValue instanceof _index.StringValue || propValue instanceof _index.NumberValue || propValue instanceof _index.BooleanValue) { let value = propValue.value; // boolean options if (typeof value === "boolean") { if (key === "firstRenderOnly") { firstRenderOnly = value; } } } else { let diagnostic = new _errors.CompilerDiagnostic("__optimizeReactComponentTree(rootComponent, config) has been called with invalid arguments", realm.currentLocation, "PP0024", "FatalError"); realm.handleError(diagnostic); if (realm.handleError(diagnostic) === "Fail") throw new _errors.FatalError(); } } } return { firstRenderOnly }; } function getValueFromRenderCall(realm, renderFunction, instance, args) { (0, _invariant2.default)(renderFunction.$Call, "Expected render function to be a FunctionValue with $Call method"); let funcCall = renderFunction.$Call; let effects; try { effects = realm.evaluateForEffects(() => funcCall(instance, args)); } catch (error) { throw error; } let completion = effects[0]; if (completion instanceof _completions.PossiblyNormalCompletion) { // in this case one of the branches may complete abruptly, which means that // not all control flow branches join into one flow at this point. // Consequently we have to continue tracking changes until the point where // all the branches come together into one. completion = realm.composeWithSavedCompletion(completion); } // Note that the effects of (non joining) abrupt branches are not included // in joinedEffects, but are tracked separately inside completion. realm.applyEffects(effects); // return or throw completion if (completion instanceof _completions.AbruptCompletion) throw completion; (0, _invariant2.default)(completion instanceof _index.Value); return completion; } function sanitizeReactElementForFirstRenderOnly(realm, reactElement) { let typeValue = (0, _index2.Get)(realm, reactElement, "type"); // ensure ref is null, as we don't use that on first render _singletons.Properties.Set(realm, reactElement, "ref", realm.intrinsics.null, false); // when dealing with host nodes, we want to sanitize them futher if (typeValue instanceof _index.StringValue) { let propsValue = (0, _index2.Get)(realm, reactElement, "props"); if (propsValue instanceof _index.ObjectValue) { // remove all values apart from string/number/boolean for (let [propName] of propsValue.properties) { (0, _invariant2.default)(propsValue instanceof _index.ObjectValue); let value = getProperty(realm, propsValue, propName); // skip children and style if (propName === "children" || propName === "style") { continue; } if (!(value instanceof _index.StringValue || value instanceof _index.NumberValue || value instanceof _index.BooleanValue)) { propsValue.$Delete(propName); } } } } return reactElement; } //# sourceMappingURL=utils.js.map /***/ }), /* 28 */ /***/ (function(module, exports) { var core = module.exports = { version: '2.5.5' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.URIUnescaped = exports.URIMark = exports.DecimalDigit = exports.URIAlpha = exports.URIReserved = undefined; exports.SplitMatch = SplitMatch; exports.RequireObjectCoercible = RequireObjectCoercible; exports.HasSameType = HasSameType; exports.AbstractRelationalComparison = AbstractRelationalComparison; exports.AbstractEqualityComparison = AbstractEqualityComparison; exports.StrictEqualityComparison = StrictEqualityComparison; exports.StrictEqualityComparisonPartial = StrictEqualityComparisonPartial; exports.SameValueZero = SameValueZero; exports.SameValueZeroPartial = SameValueZeroPartial; exports.SameValue = SameValue; exports.SameValuePartial = SameValuePartial; exports.SameValueNonNumber = SameValueNonNumber; exports.SamePropertyKey = SamePropertyKey; exports.Add = Add; exports.InstanceofOperator = InstanceofOperator; exports.OrdinaryHasInstance = OrdinaryHasInstance; exports.Type = Type; exports.SymbolDescriptiveString = SymbolDescriptiveString; exports.UpdateEmpty = UpdateEmpty; var _errors = __webpack_require__(6); var _index = __webpack_require__(0); var _call = __webpack_require__(30); var _is = __webpack_require__(16); var _completions = __webpack_require__(3); var _get = __webpack_require__(19); var _has = __webpack_require__(42); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const URIReserved = exports.URIReserved = ";/?:@&=+$,"; /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ const URIAlpha = exports.URIAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; const DecimalDigit = exports.DecimalDigit = "0123456789"; const URIMark = exports.URIMark = "-_.!~*'()"; const URIUnescaped = exports.URIUnescaped = URIAlpha + DecimalDigit + URIMark; // ECMA262 21.1.3.17.1 function SplitMatch(realm, S, q, R) { // 1. Assert: Type(R) is String. (0, _invariant2.default)(typeof R === "string", "expected a string"); // 2. Let r be the number of code units in R. let r = R.length; // 3. Let s be the number of code units in S. let s = S.length; // 4. If q+r > s, return false. if (q + r > s) return false; // 5. If there exists an integer i between 0 (inclusive) and r (exclusive) such that the code unit at index // q+i of S is different from the code unit at index i of R, return false. for (let i = 0; i < r; i++) { if (S[q + i] !== R[i]) { return false; } } // 6. Return q+r. return q + r; } // ECMA262 7.2.1 function RequireObjectCoercible(realm, arg, argLoc) { if (arg instanceof _index.AbstractValue && (arg.mightBeNull() || arg.mightBeUndefined())) { if (realm.isInPureScope()) { // In a pure function it is ok to throw if this happens to be null or undefined. return arg; } if (argLoc) { let error = new _errors.CompilerDiagnostic(`member expression object ${_index.AbstractValue.describe(arg)} is unknown`, argLoc, "PP0012", "FatalError"); realm.handleError(error); throw new _errors.FatalError(); } arg.throwIfNotConcrete(); } if (arg instanceof _index.NullValue || arg instanceof _index.UndefinedValue) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "null or undefined"); } else { return arg; } } function HasSameType(x, y) { const xType = x.getType(); const yType = y.getType(); return xType === yType || (xType === _index.IntegralValue || xType === _index.NumberValue) && (yType === _index.IntegralValue || yType === _index.NumberValue); } // ECMA262 7.2.12 Abstract Relational Comparison function AbstractRelationalComparison(realm, x, y, LeftFirst) { let px, py; // 1. If the LeftFirst flag is true, then if (LeftFirst) { // a. Let px be ? ToPrimitive(x, hint Number). px = _singletons.To.ToPrimitive(realm, x, "number"); // b. Let py be ? ToPrimitive(y, hint Number). py = _singletons.To.ToPrimitive(realm, y, "number"); } else { // 2. Else the order of evaluation needs to be reversed to preserve left to right evaluation // a. Let py be ? ToPrimitive(y, hint Number). py = _singletons.To.ToPrimitive(realm, y, "number"); // b. Let px be ? ToPrimitive(x, hint Number). px = _singletons.To.ToPrimitive(realm, x, "number"); } // 3. If both px and py are Strings, then if (px instanceof _index.StringValue && py instanceof _index.StringValue) { // a. If py is a prefix of px, return false. (A String value p is a prefix of String value q if q can be the result of concatenating p and some other String r. Note that any String is a prefix of itself, because r may be the empty String.) if (px.value.startsWith(py.value)) return realm.intrinsics.false; // b. If px is a prefix of py, return true. if (py.value.startsWith(px.value)) return realm.intrinsics.true; // c. Let k be the smallest nonnegative integer such that the code unit at index k within px is different from the code unit at index k within py. (There must be such a k, for neither String is a prefix of the other.) let k = 0; while (px.value.charCodeAt(k) === py.value.charCodeAt(k)) { k += 1; } // d. Let m be the integer that is the code unit value at index k within px. let m = px.value.charCodeAt(k); // e. Let n be the integer that is the code unit value at index k within py. let n = py.value.charCodeAt(k); // f. If m < n, return true. Otherwise, return false. return m < n ? realm.intrinsics.true : realm.intrinsics.false; } else { // 4. Else, // a. Let nx be ? ToNumber(px). Because px and py are primitive values evaluation order is not important. let nx = _singletons.To.ToNumber(realm, px); // b. Let ny be ? ToNumber(py). let ny = _singletons.To.ToNumber(realm, py); // c. If nx is NaN, return undefined. if (isNaN(nx)) return realm.intrinsics.undefined; // d. If ny is NaN, return undefined. if (isNaN(ny)) return realm.intrinsics.undefined; // e. If nx and ny are the same Number value, return false. if (Object.is(nx, ny)) { return realm.intrinsics.false; } // f. If nx is +0 and ny is -0, return false. if (Object.is(nx, +0) && Object.is(ny, -0)) { return realm.intrinsics.false; } // g. If nx is -0 and ny is +0, return false. if (Object.is(nx, -0) && Object.is(ny, +0)) { return realm.intrinsics.false; } // h. If nx is +∞, return false. // i. If ny is +∞, return true. // j. If ny is -∞, return false. // k. If nx is -∞, return true. // i. If the mathematical value of nx is less than the mathematical value of ny —note that these // mathematical values are both finite and not both zero—return true. Otherwise, return false. if (nx < ny) { return realm.intrinsics.true; } else { return realm.intrinsics.false; } } } // ECMA262 7.2.13 function AbstractEqualityComparison(realm, x, y) { // 1. If Type(x) is the same as Type(y), then if (HasSameType(x, y)) { // a. Return the result of performing Strict Equality Comparison x === y. return StrictEqualityComparison(realm, x, y); } // 2. If x is null and y is undefined, return true. if (x instanceof _index.NullValue && y instanceof _index.UndefinedValue) { return true; } // 3. If x is undefined and y is null, return true. if (x instanceof _index.UndefinedValue && y instanceof _index.NullValue) { return true; } // 4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y). if (x instanceof _index.NumberValue && y instanceof _index.StringValue) { return AbstractEqualityComparison(realm, x, new _index.NumberValue(realm, _singletons.To.ToNumber(realm, y))); } // 5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y. if (x instanceof _index.StringValue && y instanceof _index.NumberValue) { return AbstractEqualityComparison(realm, new _index.NumberValue(realm, _singletons.To.ToNumber(realm, x)), y); } // 6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y. if (x instanceof _index.BooleanValue) { return AbstractEqualityComparison(realm, new _index.NumberValue(realm, _singletons.To.ToNumber(realm, x)), y); } // 7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y). if (y instanceof _index.BooleanValue) { return AbstractEqualityComparison(realm, x, new _index.NumberValue(realm, _singletons.To.ToNumber(realm, y))); } // 8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y). if ((x instanceof _index.StringValue || x instanceof _index.NumberValue || x instanceof _index.SymbolValue) && y instanceof _index.ObjectValue) { return AbstractEqualityComparison(realm, x, _singletons.To.ToPrimitive(realm, y)); } // 9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y. if (x instanceof _index.ObjectValue && (y instanceof _index.StringValue || y instanceof _index.NumberValue || y instanceof _index.SymbolValue)) { return AbstractEqualityComparison(realm, _singletons.To.ToPrimitive(realm, x), y); } // 10. Return false. return false; } // ECMA262 7.2.14 Strict Equality Comparison function StrictEqualityComparison(realm, x, y) { // 1. If Type(x) is different from Type(y), return false. if (!HasSameType(x, y)) { return false; } // 2. If Type(x) is Number, then if (x instanceof _index.NumberValue && y instanceof _index.NumberValue) { // a. If x is NaN, return false. if (isNaN(x.value)) return false; // b. If y is NaN, return false. if (isNaN(y.value)) return false; // c. If x is the same Number value as y, return true. // d. If x is +0 and y is -0, return true. (handled by c) // e. If x is -0 and y is +0, return true. (handled by c) if (x.value === y.value) return true; // f. Return false. return false; } // 3. Return SameValueNonNumber(x, y). return SameValueNonNumber(realm, x, y); } function StrictEqualityComparisonPartial(realm, x, y) { return StrictEqualityComparison(realm, x.throwIfNotConcrete(), y.throwIfNotConcrete()); } // ECMA262 7.2.10 function SameValueZero(realm, x, y) { // 1. If Type(x) is different from Type(y), return false. if (!HasSameType(x, y)) { return false; } // 2. If Type(x) is Number, then if (x instanceof _index.NumberValue) { (0, _invariant2.default)(y instanceof _index.NumberValue); // a. If x is NaN and y is NaN, return true. if (isNaN(x.value) && isNaN(y.value)) return true; // b. If x is +0 and y is -0, return true. if (Object.is(x.value, +0) && Object.is(y.value, -0)) return true; // c. If x is -0 and y is +0, return true. if (Object.is(x.value, -0) && Object.is(y.value, +0)) return true; // d. If x is the same Number value as y, return true. if (x.value === y.value) return true; // e. Return false. return false; } // 3. Return SameValueNonNumber(x, y). return SameValueNonNumber(realm, x, y); } function SameValueZeroPartial(realm, x, y) { return SameValueZero(realm, x.throwIfNotConcrete(), y.throwIfNotConcrete()); } // ECMA262 7.2.9 function SameValue(realm, x, y) { // 1. If Type(x) is different from Type(y), return false. if (!HasSameType(x, y)) { return false; } // 2. If Type(x) is Number, then if (x instanceof _index.NumberValue && y instanceof _index.NumberValue) { // a. If x is NaN and y is NaN, return true. if (isNaN(x.value) && isNaN(y.value)) return true; // b. If x is +0 and y is -0, return false. if (Object.is(x.value, +0) && Object.is(y.value, -0)) return false; // c. If x is -0 and y is +0, return false. if (Object.is(x.value, -0) && Object.is(y.value, +0)) return false; // d. If x is the same Number value as y, return true. if (x.value === y.value) return true; // e. Return false. return false; } // 3. Return SameValueNonNumber(x, y). return SameValueNonNumber(realm, x, y); } function SameValuePartial(realm, x, y) { return SameValue(realm, x.throwIfNotConcrete(), y.throwIfNotConcrete()); } // ECMA262 7.2.11 function SameValueNonNumber(realm, x, y) { // 1. Assert: Type(x) is not Number. (0, _invariant2.default)(!(x instanceof _index.NumberValue), "numbers not allowed"); // 2. Assert: Type(x) is the same as Type(y). (0, _invariant2.default)(x.getType() === y.getType(), "must be same type"); // 3. If Type(x) is Undefined, return true. if (x instanceof _index.UndefinedValue) return true; // 4. If Type(x) is Null, return true. if (x instanceof _index.NullValue) return true; // 5. If Type(x) is String, then if (x instanceof _index.StringValue && y instanceof _index.StringValue) { // a. If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true; otherwise, return false. return x.value === y.value; } // 6. If Type(x) is Boolean, then if (x instanceof _index.BooleanValue && y instanceof _index.BooleanValue) { // a. If x and y are both true or both false, return true; otherwise, return false. return x.value === y.value; } // 7. If Type(x) is Symbol, then if (x instanceof _index.SymbolValue) { // a. If x and y are both the same Symbol value, return true; otherwise, return false. return x === y; } // 8. Return true if x and y are the same Object value. Otherwise, return false. return x === y; } // Checks if two property keys are identical. function SamePropertyKey(realm, x, y) { if (typeof x === "string" && typeof y === "string") { return x === y; } if (x instanceof _index.StringValue && y instanceof _index.StringValue) { return x.value === y.value; } if (x instanceof _index.SymbolValue && y instanceof _index.SymbolValue) { return x === y; } return false; } // ECMA262 12.8.5 Applying the Additive Operators to Numbers function Add(realm, a, b, subtract = false) { // If either operand is NaN, the result is NaN. if (isNaN(a) || isNaN(b)) { return realm.intrinsics.NaN; } // The sum of two infinities of opposite sign is NaN. // The sum of two infinities of the same sign is the infinity of that sign. // The sum of an infinity and a finite value is equal to the infinite operand. // The sum of two negative zeroes is -0. The sum of two positive zeroes, or of two zeroes of opposite sign, is +0. // The sum of a zero and a nonzero finite value is equal to the nonzero operand. // The sum of two nonzero finite values of the same magnitude and opposite sign is +0. let anum = a; let bnum = b; // The - operator performs subtraction when applied to two operands of numeric type, // producing the difference of its operands; the left operand is the minuend and the right // operand is the subtrahend. Given numeric operands a and b, it is always the case that // a-b produces the same result as a+(-b). if (subtract) { bnum = -bnum; } return _index.IntegralValue.createFromNumberValue(realm, anum + bnum); } // ECMA262 12.10.4 function InstanceofOperator(realm, O, C) { // 1. If Type(C) is not Object, throw a TypeError exception. if (!C.mightBeObject()) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Expecting a function in instanceof check"); } // 2. Let instOfHandler be ? GetMethod(C, @@hasInstance). let instOfHandler = (0, _get.GetMethod)(realm, C, realm.intrinsics.SymbolHasInstance); // 3. If instOfHandler is not undefined, then if (!(instOfHandler instanceof _index.UndefinedValue)) { // a. Return ToBoolean(? Call(instOfHandler, C, « O »)). return _singletons.To.ToBooleanPartial(realm, (0, _call.Call)(realm, instOfHandler, C, [O])); } // 4. If IsCallable(C) is false, throw a TypeError exception. if ((0, _is.IsCallable)(realm, C) === false) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Expecting a function in instanceof check"); } // 5. Return ? OrdinaryHasInstance(C, O). return OrdinaryHasInstance(realm, C, O); } // ECMA262 7.3.19 function OrdinaryHasInstance(realm, C, O) { // 1. If IsCallable(C) is false, return false. if ((0, _is.IsCallable)(realm, C) === false) return false; (0, _invariant2.default)(C instanceof _index.ObjectValue); // 2. If C has a [[BoundTargetFunction]] internal slot, then if (C instanceof _index.BoundFunctionValue) { // a. Let BC be the value of C's [[BoundTargetFunction]] internal slot. let BC = C.$BoundTargetFunction; // b. Return ? InstanceofOperator(O, BC). return InstanceofOperator(realm, O, BC); } // 3. If Type(O) is not Object, return false. O = O.throwIfNotConcrete(); if (!(O instanceof _index.ObjectValue)) return false; // 4. Let P be ? Get(C, "prototype"). let P = (0, _get.Get)(realm, C, "prototype").throwIfNotConcrete(); // 5. If Type(P) is not Object, throw a TypeError exception. if (!(P instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(P) is not Object"); } // 6. Repeat while (true) { // a. Let O be ? O.[[GetPrototypeOf]](). O = O.$GetPrototypeOf(); // b. If O is null, return false. if (O instanceof _index.NullValue) return false; // c. If SameValue(P, O) is true, return true. if (SameValue(realm, P, O) === true) return true; } return false; } // function Type(realm, val) { if (val instanceof _index.UndefinedValue) { return "Undefined"; } else if (val instanceof _index.NullValue) { return "Null"; } else if ((0, _has.HasCompatibleType)(val, _index.BooleanValue)) { return "Boolean"; } else if ((0, _has.HasCompatibleType)(val, _index.StringValue)) { return "String"; } else if ((0, _has.HasCompatibleType)(val, _index.SymbolValue)) { return "Symbol"; } else if ((0, _has.HasCompatibleType)(val, _index.IntegralValue)) { return "Number"; } else if ((0, _has.HasCompatibleType)(val, _index.NumberValue)) { return "Number"; } else if (!val.mightNotBeObject()) { return "Object"; } else { (0, _invariant2.default)(val instanceof _index.AbstractValue); _index.AbstractValue.reportIntrospectionError(val); throw new _errors.FatalError(); } } // ECMA262 19.4.3.2.1 function SymbolDescriptiveString(realm, sym) { // 1. Assert: Type(sym) is Symbol. (0, _invariant2.default)(sym instanceof _index.SymbolValue, "expected symbol"); // 2. Let desc be sym's [[Description]] value. let desc = sym.$Description; // 3. If desc is undefined, let desc be the empty string. if (!desc) desc = "";else desc = desc.throwIfNotConcreteString().value; // 4. Assert: Type(desc) is String. (0, _invariant2.default)(typeof desc === "string", "expected string"); // 5. Return the result of concatenating the strings "Symbol(", desc, and ")". return `Symbol(${desc})`; } // ECMA262 6.2.2.5 function UpdateEmpty(realm, completionRecord, value) { // 1. Assert: If completionRecord.[[Type]] is either return or throw, then completionRecord.[[Value]] is not empty. if (completionRecord instanceof _completions.ReturnCompletion || completionRecord instanceof _completions.ThrowCompletion) { (0, _invariant2.default)(completionRecord.value, "expected completion record to have a value"); } // 2. If completionRecord.[[Value]] is not empty, return Completion(completionRecord). if (completionRecord instanceof _index.EmptyValue) return value; if (completionRecord instanceof _index.Value || completionRecord.value && !(completionRecord.value instanceof _index.EmptyValue)) return completionRecord; // 3. Return Completion{[[Type]]: completionRecord.[[Type]], [[Value]]: value, [[Target]]: completionRecord.[[Target]] }.' completionRecord.value = value; return completionRecord; } //# sourceMappingURL=abstract.js.map /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ArgumentListEvaluation = ArgumentListEvaluation; exports.Invoke = Invoke; exports.EvaluateCall = EvaluateCall; exports.PrepareForOrdinaryCall = PrepareForOrdinaryCall; exports.OrdinaryCallBindThis = OrdinaryCallBindThis; exports.OrdinaryCallEvaluateBody = OrdinaryCallEvaluateBody; exports.EvaluateDirectCall = EvaluateDirectCall; exports.EvaluateDirectCallWithArgList = EvaluateDirectCallWithArgList; exports.PrepareForTailCall = PrepareForTailCall; exports.Call = Call; var _environment = __webpack_require__(12); var _errors = __webpack_require__(6); var _realm = __webpack_require__(11); var _Value = __webpack_require__(586); var _Value2 = _interopRequireDefault(_Value); var _index = __webpack_require__(0); var _index2 = __webpack_require__(5); var _generator = __webpack_require__(610); var _completions = __webpack_require__(3); var _get = __webpack_require__(19); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // ECMA262 12.3.6.1 function ArgumentListEvaluation(realm, strictCode, env, argNodes) { if (Array.isArray(argNodes)) { let args = []; for (let node_ of argNodes) { if (node_.type === "SpreadElement") { let node = node_; // 1. Let list be a new empty List. let list = args; // 2. Let spreadRef be the result of evaluating AssignmentExpression. let spreadRef = env.evaluate(node.argument, strictCode); // 3. Let spreadObj be ? GetValue(spreadRef). let spreadObj = _singletons.Environment.GetValue(realm, spreadRef); // 4. Let iterator be ? GetIterator(spreadObj). let iterator = (0, _index2.GetIterator)(realm, spreadObj); // 5. Repeat while (true) { // a. Let next be ? IteratorStep(iterator). let next = (0, _index2.IteratorStep)(realm, iterator); // b. If next is false, return list. if (!next) { break; } // c. Let nextArg be ? IteratorValue(next). let nextArg = (0, _index2.IteratorValue)(realm, next); // d. Append nextArg as the last element of list. list.push(nextArg); } } else { let ref = env.evaluate(node_, strictCode); let expr = _singletons.Environment.GetValue(realm, ref); args.push(expr); } } return args; } else { let node = argNodes; if (node.expressions.length === 0) { // 1. Let templateLiteral be this TemplateLiteral. let templateLiteral = node; // 2. Let siteObj be GetTemplateObject(templateLiteral). let siteObj = (0, _get.GetTemplateObject)(realm, templateLiteral); // 3. Return a List containing the one element which is siteObj. return [siteObj]; } else { // 1. Let templateLiteral be this TemplateLiteral. let templateLiteral = node; // 2. Let siteObj be GetTemplateObject(templateLiteral). let siteObj = (0, _get.GetTemplateObject)(realm, templateLiteral); // 3. Let firstSubRef be the result of evaluating Expression. let firstSubRef = env.evaluate(node.expressions[0], strictCode); // 4. Let firstSub be ? GetValue(firstSubRef). let firstSub = _singletons.Environment.GetValue(realm, firstSubRef); // 5. Let restSub be SubstitutionEvaluation of TemplateSpans. let restSub = node.expressions.slice(1, node.expressions.length).map(expr => { return _singletons.Environment.GetValue(realm, env.evaluate(expr, strictCode)); }); // 6. ReturnIfAbrupt(restSub). // 7. Assert: restSub is a List. (0, _invariant2.default)(restSub.constructor === Array, "restSub is a List"); // 8. Return a List whose first element is siteObj, whose second elements is firstSub, and whose subsequent elements are the elements of restSub, in order. restSub may contain no elements. return [siteObj, firstSub, ...restSub]; } } } // ECMA262 7.3.18 /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function Invoke(realm, V, P, argumentsList) { // 1. Assert: IsPropertyKey(P) is true. (0, _invariant2.default)((0, _index2.IsPropertyKey)(realm, P), "expected property key"); // 2. If argumentsList was not passed, let argumentsList be a new empty List. if (!argumentsList) argumentsList = []; // 3. Let func be ? GetV(V, P). let func = (0, _get.GetV)(realm, V, P); // 4. Return ? Call(func, V, argumentsList). return Call(realm, func, V, argumentsList); } // ECMA262 12.3.4.2 function EvaluateCall(realm, strictCode, env, ref, args) { let thisValue; // 1. Let func be ? GetValue(ref). let func = _singletons.Environment.GetValue(realm, ref); // 2. If Type(ref) is Reference, then if (ref instanceof _environment.Reference) { // a. If IsPropertyReference(ref) is true, then if (_singletons.Environment.IsPropertyReference(realm, ref)) { // i. Let thisValue be GetThisValue(ref). thisValue = (0, _get.GetThisValue)(realm, ref); } else { // b. Else, the base of ref is an Environment Record // i. Let refEnv be GetBase(ref). let refEnv = _singletons.Environment.GetBase(realm, ref); (0, _invariant2.default)(refEnv instanceof _environment.EnvironmentRecord); // ii. Let thisValue be refEnv.WithBaseObject(). thisValue = refEnv.WithBaseObject(); } } else { // 3. Else Type(ref) is not Reference, // a. Let thisValue be undefined. thisValue = realm.intrinsics.undefined; } // 4. Return ? EvaluateDirectCall(func, thisValue, arguments, tailPosition). return EvaluateDirectCall(realm, strictCode, env, ref, func, thisValue, args); } // ECMA262 9.2.1.1 function PrepareForOrdinaryCall(realm, F, newTarget) { // 1. Assert: Type(newTarget) is Undefined or Object. (0, _invariant2.default)(newTarget === undefined || newTarget instanceof _index.ObjectValue, "expected undefined or object value for new target"); // 2. Let callerContext be the running execution context. let callerContext = realm.getRunningContext(); // 3. Let calleeContext be a new ECMAScript code execution context. let calleeContext = realm.createExecutionContext(); // 4. Set the Function of calleeContext to F. calleeContext.setFunction(F); calleeContext.setCaller(realm.getRunningContext()); // 5. Let calleeRealm be the value of F's [[Realm]] internal slot. let calleeRealm = realm; // 6. Set the Realm of calleeContext to calleeRealm. calleeContext.realm = calleeRealm; // 7. Set the ScriptOrModule of calleeContext to the value of F's [[ScriptOrModule]] internal slot. calleeContext.ScriptOrModule = F.$ScriptOrModule; // 8. Let localEnv be NewFunctionEnvironment(F, newTarget). let localEnv = _singletons.Environment.NewFunctionEnvironment(realm, F, newTarget); // 9. Set the LexicalEnvironment of calleeContext to localEnv. calleeContext.lexicalEnvironment = localEnv; // 10. Set the VariableEnvironment of calleeContext to localEnv. calleeContext.variableEnvironment = localEnv; // 11. If callerContext is not already suspended, suspend callerContext. callerContext.suspend(); // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context. realm.pushContext(calleeContext); // 13. NOTE Any exception objects produced after this point are associated with calleeRealm. // 14. Return calleeContext. return calleeContext; } // ECMA262 9.2.1.2 function OrdinaryCallBindThis(realm, F, calleeContext, thisArgument) { // 1. Let thisMode be the value of F's [[ThisMode]] internal slot. let thisMode = F.$ThisMode; // 2. If thisMode is lexical, return NormalCompletion(undefined). if (thisMode === "lexical") return realm.intrinsics.undefined; // 3. Let calleeRealm be the value of F's [[Realm]] internal slot. let calleeRealm = F.$Realm; // 4. Let localEnv be the LexicalEnvironment of calleeContext. let localEnv = calleeContext.lexicalEnvironment; let thisValue; // 5. If thisMode is strict, let thisValue be thisArgument. if (thisMode === "strict") { thisValue = thisArgument; } else { // 6. Else, // a. If thisArgument is null or undefined, then if ((0, _index2.HasSomeCompatibleType)(thisArgument, _index.NullValue, _index.UndefinedValue)) { // i. Let globalEnv be calleeRealm.[[GlobalEnv]]. let globalEnv = realm.$GlobalEnv; // ii. Let globalEnvRec be globalEnv's EnvironmentRecord. let globalEnvRec = globalEnv.environmentRecord; (0, _invariant2.default)(globalEnvRec instanceof _environment.GlobalEnvironmentRecord); // iii. Let thisValue be globalEnvRec.[[GlobalThisValue]]. thisValue = globalEnvRec.$GlobalThisValue; } else { // b. Else, // i. Let thisValue be ! ToObject(thisArgument). thisValue = _singletons.To.ToObjectPartial(calleeRealm, thisArgument); // ii. NOTE ToObject produces wrapper objects using calleeRealm. } } // 7. Let envRec be localEnv's EnvironmentRecord. (0, _invariant2.default)(localEnv !== undefined); let envRec = localEnv.environmentRecord; // 8. Assert: The next step never returns an abrupt completion because envRec.[[ThisBindingStatus]] is not "initialized". // 9. Return envRec.BindThisValue(thisValue). return envRec.BindThisValue(thisValue); } // ECMA262 9.2.1.3 function OrdinaryCallEvaluateBody(realm, f, argumentsList) { if (f instanceof _index.NativeFunctionValue) { let env = realm.getRunningContext().lexicalEnvironment; try { return f.callCallback(env.environmentRecord.GetThisBinding(), argumentsList, env.environmentRecord.$NewTarget); } catch (err) { if (err instanceof _completions.AbruptCompletion) { return err; } else if (err instanceof Error) { throw err; } else { throw new _errors.FatalError(err); } } } else { (0, _invariant2.default)(f instanceof _index.ECMAScriptSourceFunctionValue); let F = f; if (F.$FunctionKind === "generator") { // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList). _singletons.Functions.FunctionDeclarationInstantiation(realm, F, argumentsList); // 2. Let G be ? OrdinaryCreateFromConstructor(functionObject, "%GeneratorPrototype%", « [[GeneratorState]], [[GeneratorContext]] »). let G = _singletons.Create.OrdinaryCreateFromConstructor(realm, F, "GeneratorPrototype", { $GeneratorState: undefined, $GeneratorContext: undefined }); // 3. Perform GeneratorStart(G, FunctionBody). let code = F.$ECMAScriptCode; (0, _invariant2.default)(code !== undefined); (0, _generator.GeneratorStart)(realm, G, code); // 4. Return Completion{[[Type]]: return, [[Value]]: G, [[Target]]: empty}. return new _completions.ReturnCompletion(G, realm.currentLocation); } else { if (!realm.useAbstractInterpretation || realm.pathConditions.length === 0) return normalCall(); let savedIsSelfRecursive = F.isSelfRecursive; try { F.isSelfRecursive = false; let effects = realm.evaluateForEffects(guardedCall); if (F.isSelfRecursive) { _index.AbstractValue.reportIntrospectionError(F, "call to function that calls itself"); throw new _errors.FatalError(); //todo: need to emit a specialized function that temporally captures the heap state at this point } else { realm.applyEffects(effects); let c = effects[0]; return processResult(() => { (0, _invariant2.default)(c instanceof _Value2.default || c instanceof _completions.AbruptCompletion); return c; }); } } finally { F.isSelfRecursive = savedIsSelfRecursive; } function guardedCall() { let currentLocation = realm.currentLocation; if (F.activeArguments !== undefined && F.activeArguments.has(currentLocation)) { let [previousPathLength, previousArguments] = F.activeArguments.get(currentLocation); if (realm.pathConditions.length > previousPathLength) { (0, _invariant2.default)(previousArguments !== undefined); // F is being called recursively while a call to it is still active F.isSelfRecursive = true; let widenedArgumentsList = _singletons.Widen.widenValues(realm, previousArguments, argumentsList); if (_singletons.Widen.containsArraysOfValue(realm, previousArguments, widenedArgumentsList)) { // Reached a fixed point. Executing this call will not add any knowledge // about the effects of the original call. return _index.AbstractValue.createFromType(realm, _Value2.default, "widened return result"); } else { argumentsList = widenedArgumentsList; } } } try { if (F.activeArguments === undefined) F.activeArguments = new Map(); F.activeArguments.set(currentLocation, [realm.pathConditions.length, argumentsList]); return normalCall(); } finally { F.activeArguments.delete(currentLocation); } } function normalCall() { // 1. Perform ? FunctionDeclarationInstantiation(F, argumentsList). _singletons.Functions.FunctionDeclarationInstantiation(realm, F, argumentsList); // 2. Return the result of EvaluateBody of the parsed code that is the value of F's // [[ECMAScriptCode]] internal slot passing F as the argument. let code = F.$ECMAScriptCode; (0, _invariant2.default)(code !== undefined); let context = realm.getRunningContext(); return processResult(() => context.lexicalEnvironment.evaluateCompletionDeref(code, F.$Strict)); } function processResult(getCompletion) { let priorSavedCompletion = realm.savedCompletion; try { realm.savedCompletion = undefined; let c = getCompletion(); // We are about the leave this function and this presents a join point where all non exeptional control flows // converge into a single flow using the joined effects as the new state. c = _singletons.Functions.incorporateSavedCompletion(realm, c); let joinedEffects; if (c instanceof _completions.PossiblyNormalCompletion) { let e = realm.getCapturedEffects(c); if (e !== undefined) { // There were earlier, conditional exits from the function // We join together the current effects with the effects of any earlier returns that are tracked in c. realm.stopEffectCaptureAndUndoEffects(c); } else { e = (0, _realm.construct_empty_effects)(realm); } joinedEffects = _singletons.Join.joinEffectsAndPromoteNestedReturnCompletions(realm, c, e); } else if (c instanceof _completions.JoinedAbruptCompletions) { joinedEffects = _singletons.Join.joinEffectsAndPromoteNestedReturnCompletions(realm, c, (0, _realm.construct_empty_effects)(realm)); } if (joinedEffects !== undefined) { let result = joinedEffects[0]; if (result instanceof _completions.ReturnCompletion) { realm.applyEffects(joinedEffects); return result; } (0, _invariant2.default)(result instanceof _completions.JoinedAbruptCompletions); if (!(result.consequent instanceof _completions.ReturnCompletion || result.alternate instanceof _completions.ReturnCompletion)) { realm.applyEffects(joinedEffects); throw result; } // There is a normal return exit, but also one or more throw completions. // The throw completions must be extracted into a saved possibly normal completion // so that the caller can pick them up in its next completion. joinedEffects = extractAndSavePossiblyNormalCompletion(result); result = joinedEffects[0]; (0, _invariant2.default)(result instanceof _completions.ReturnCompletion); realm.applyEffects(joinedEffects); return result; } else { (0, _invariant2.default)(c instanceof _Value2.default || c instanceof _completions.AbruptCompletion); return c; } } finally { realm.incorporatePriorSavedCompletion(priorSavedCompletion); } } } } function extractAndSavePossiblyNormalCompletion(c) { // There are throw completions that conditionally escape from the the call. // We need to carry on in normal mode (after arranging to capturing effects) // while stashing away the throw completions so that the next completion we return let [joinedEffects, possiblyNormalCompletion] = _singletons.Join.unbundleReturnCompletion(realm, c); realm.composeWithSavedCompletion(possiblyNormalCompletion); return joinedEffects; } } // ECMA262 12.3.4.3 function EvaluateDirectCall(realm, strictCode, env, ref, func, thisValue, args, tailPosition) { // 1. Let argList be ? ArgumentListEvaluation(arguments). let argList = ArgumentListEvaluation(realm, strictCode, env, args); return EvaluateDirectCallWithArgList(realm, strictCode, env, ref, func, thisValue, argList, tailPosition); } function EvaluateDirectCallWithArgList(realm, strictCode, env, ref, func, thisValue, argList, tailPosition) { if (func instanceof _index.AbstractObjectValue && _Value2.default.isTypeCompatibleWith(func.getType(), _index.FunctionValue)) { return _index.AbstractValue.createTemporalFromBuildFunction(realm, func.functionResultType || _Value2.default, [func].concat(argList), nodes => { let fun_args = nodes.slice(1); return t.callExpression(nodes[0], fun_args); }); } func = func.throwIfNotConcrete(); // 2. If Type(func) is not Object, throw a TypeError exception. if (!(func instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not an object"); } // 3. If IsCallable(func) is false, throw a TypeError exception. if (!(0, _index2.IsCallable)(realm, func)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not callable"); } // 4. If tailPosition is true, perform PrepareForTailCall(). if (tailPosition === true) PrepareForTailCall(realm); // 5. Let result be Call(func, thisValue, argList). let result = Call(realm, func, thisValue, argList); // 6. Assert: If tailPosition is true, the above call will not return here, but instead // evaluation will continue as if the following return has already occurred. // 7. Assert: If result is not an abrupt completion, then Type(result) is an ECMAScript language type. (0, _invariant2.default)(result instanceof _Value2.default, "expected language value type"); // 8. Return result. return result; } // ECMA262 14.6.3 function PrepareForTailCall(realm) { // 1. Let leafContext be the running execution context. let leafContext = realm.getRunningContext(); // 2. Suspend leafContext. leafContext.suspend(); // 3. Pop leafContext from the execution context stack. The execution context now on the // top of the stack becomes the running execution context. realm.onDestroyScope(leafContext.lexicalEnvironment); realm.popContext(leafContext); // TODO #1008 4. Assert: leafContext has no further use. It will never be activated as the running execution context. } // ECMA262 7.3.12 function Call(realm, F, V, argsList) { // 1. If argumentsList was not passed, let argumentsList be a new empty List. argsList = argsList || []; // 2. If IsCallable(F) is false, throw a TypeError exception. if ((0, _index2.IsCallable)(realm, F) === false) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not callable"); } if (F instanceof _index.AbstractValue && _Value2.default.isTypeCompatibleWith(F.getType(), _index.FunctionValue)) { _singletons.Havoc.value(realm, V); for (let arg of argsList) { _singletons.Havoc.value(realm, arg); } if (V === realm.intrinsics.undefined) { let fullArgs = [F].concat(argsList); return _index.AbstractValue.createTemporalFromBuildFunction(realm, _Value2.default, fullArgs, nodes => { let fun_args = nodes.slice(1); return t.callExpression(nodes[0], fun_args); }); } else { let fullArgs = [F, V].concat(argsList); return _index.AbstractValue.createTemporalFromBuildFunction(realm, _Value2.default, fullArgs, nodes => { let fun_args = nodes.slice(1); return t.callExpression(t.memberExpression(nodes[0], t.identifier("call")), fun_args); }); } } (0, _invariant2.default)(F instanceof _index.ObjectValue); // 3. Return ? F.[[Call]](V, argumentsList). (0, _invariant2.default)(F.$Call, "no call method on this value"); return F.$Call(V, argsList); } //# sourceMappingURL=call.js.map /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = exports.isAbsolute(path), trailingSlash = substr(path, -1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.isAbsolute = function(path) { return path.charAt(0) === '/'; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; function filter (xs, f) { if (xs.filter) return xs.filter(f); var res = []; for (var i = 0; i < xs.length; i++) { if (f(xs[i], i, xs)) res.push(xs[i]); } return res; } // String.prototype.substr - negative index don't work in IE8 var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { return str.substr(start, len) } : function (str, start, len) { if (start < 0) start = str.length + start; return str.substr(start, len); } ; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }), /* 32 */ /***/ (function(module, exports) { var Ap = Array.prototype; var slice = Ap.slice; var map = Ap.map; var each = Ap.forEach; var Op = Object.prototype; var objToStr = Op.toString; var funObjStr = objToStr.call(function(){}); var strObjStr = objToStr.call(""); var hasOwn = Op.hasOwnProperty; module.exports = function () { var exports = {}; // A type is an object with a .check method that takes a value and returns // true or false according to whether the value matches the type. function Type(check, name) { var self = this; if (!(self instanceof Type)) { throw new Error("Type constructor cannot be invoked without 'new'"); } // Unfortunately we can't elegantly reuse isFunction and isString, // here, because this code is executed while defining those types. if (objToStr.call(check) !== funObjStr) { throw new Error(check + " is not a function"); } // The `name` parameter can be either a function or a string. var nameObjStr = objToStr.call(name); if (!(nameObjStr === funObjStr || nameObjStr === strObjStr)) { throw new Error(name + " is neither a function nor a string"); } Object.defineProperties(self, { name: {value: name}, check: { value: function (value, deep) { var result = check.call(self, value, deep); if (!result && deep && objToStr.call(deep) === funObjStr) deep(self, value); return result; } } }); } var Tp = Type.prototype; // Throughout this file we use Object.defineProperty to prevent // redefinition of exported properties. exports.Type = Type; // Like .check, except that failure triggers an AssertionError. Tp.assert = function (value, deep) { if (!this.check(value, deep)) { var str = shallowStringify(value); throw new Error(str + " does not match type " + this); } return true; }; function shallowStringify(value) { if (isObject.check(value)) return "{" + Object.keys(value).map(function (key) { return key + ": " + value[key]; }).join(", ") + "}"; if (isArray.check(value)) return "[" + value.map(shallowStringify).join(", ") + "]"; return JSON.stringify(value); } Tp.toString = function () { var name = this.name; if (isString.check(name)) return name; if (isFunction.check(name)) return name.call(this) + ""; return name + " type"; }; var builtInCtorFns = []; var builtInCtorTypes = []; var builtInTypes = {}; exports.builtInTypes = builtInTypes; function defBuiltInType(example, name) { var objStr = objToStr.call(example); var type = new Type(function (value) { return objToStr.call(value) === objStr; }, name); builtInTypes[name] = type; if (example && typeof example.constructor === "function") { builtInCtorFns.push(example.constructor); builtInCtorTypes.push(type); } return type; } // These types check the underlying [[Class]] attribute of the given // value, rather than using the problematic typeof operator. Note however // that no subtyping is considered; so, for instance, isObject.check // returns false for [], /./, new Date, and null. var isString = defBuiltInType("truthy", "string"); var isFunction = defBuiltInType(function () {}, "function"); var isArray = defBuiltInType([], "array"); var isObject = defBuiltInType({}, "object"); var isRegExp = defBuiltInType(/./, "RegExp"); var isDate = defBuiltInType(new Date, "Date"); var isNumber = defBuiltInType(3, "number"); var isBoolean = defBuiltInType(true, "boolean"); var isNull = defBuiltInType(null, "null"); var isUndefined = defBuiltInType(void 0, "undefined"); // There are a number of idiomatic ways of expressing types, so this // function serves to coerce them all to actual Type objects. Note that // providing the name argument is not necessary in most cases. function toType(from, name) { // The toType function should of course be idempotent. if (from instanceof Type) return from; // The Def type is used as a helper for constructing compound // interface types for AST nodes. if (from instanceof Def) return from.type; // Support [ElemType] syntax. if (isArray.check(from)) return Type.fromArray(from); // Support { someField: FieldType, ... } syntax. if (isObject.check(from)) return Type.fromObject(from); if (isFunction.check(from)) { var bicfIndex = builtInCtorFns.indexOf(from); if (bicfIndex >= 0) { return builtInCtorTypes[bicfIndex]; } // If isFunction.check(from), and from is not a built-in // constructor, assume from is a binary predicate function we can // use to define the type. return new Type(from, name); } // As a last resort, toType returns a type that matches any value that // is === from. This is primarily useful for literal values like // toType(null), but it has the additional advantage of allowing // toType to be a total function. return new Type(function (value) { return value === from; }, isUndefined.check(name) ? function () { return from + ""; } : name); } // Returns a type that matches the given value iff any of type1, type2, // etc. match the value. Type.or = function (/* type1, type2, ... */) { var types = []; var len = arguments.length; for (var i = 0; i < len; ++i) types.push(toType(arguments[i])); return new Type(function (value, deep) { for (var i = 0; i < len; ++i) if (types[i].check(value, deep)) return true; return false; }, function () { return types.join(" | "); }); }; Type.fromArray = function (arr) { if (!isArray.check(arr)) { throw new Error(""); } if (arr.length !== 1) { throw new Error("only one element type is permitted for typed arrays"); } return toType(arr[0]).arrayOf(); }; Tp.arrayOf = function () { var elemType = this; return new Type(function (value, deep) { return isArray.check(value) && value.every(function (elem) { return elemType.check(elem, deep); }); }, function () { return "[" + elemType + "]"; }); }; Type.fromObject = function (obj) { var fields = Object.keys(obj).map(function (name) { return new Field(name, obj[name]); }); return new Type(function (value, deep) { return isObject.check(value) && fields.every(function (field) { return field.type.check(value[field.name], deep); }); }, function () { return "{ " + fields.join(", ") + " }"; }); }; function Field(name, type, defaultFn, hidden) { var self = this; if (!(self instanceof Field)) { throw new Error("Field constructor cannot be invoked without 'new'"); } isString.assert(name); type = toType(type); var properties = { name: {value: name}, type: {value: type}, hidden: {value: !!hidden} }; if (isFunction.check(defaultFn)) { properties.defaultFn = {value: defaultFn}; } Object.defineProperties(self, properties); } var Fp = Field.prototype; Fp.toString = function () { return JSON.stringify(this.name) + ": " + this.type; }; Fp.getValue = function (obj) { var value = obj[this.name]; if (!isUndefined.check(value)) return value; if (this.defaultFn) value = this.defaultFn.call(obj); return value; }; // Define a type whose name is registered in a namespace (the defCache) so // that future definitions will return the same type given the same name. // In particular, this system allows for circular and forward definitions. // The Def object d returned from Type.def may be used to configure the // type d.type by calling methods such as d.bases, d.build, and d.field. Type.def = function (typeName) { isString.assert(typeName); return hasOwn.call(defCache, typeName) ? defCache[typeName] : defCache[typeName] = new Def(typeName); }; // In order to return the same Def instance every time Type.def is called // with a particular name, those instances need to be stored in a cache. var defCache = Object.create(null); function Def(typeName) { var self = this; if (!(self instanceof Def)) { throw new Error("Def constructor cannot be invoked without 'new'"); } Object.defineProperties(self, { typeName: {value: typeName}, baseNames: {value: []}, ownFields: {value: Object.create(null)}, // These two are populated during finalization. allSupertypes: {value: Object.create(null)}, // Includes own typeName. supertypeList: {value: []}, // Linear inheritance hierarchy. allFields: {value: Object.create(null)}, // Includes inherited fields. fieldNames: {value: []}, // Non-hidden keys of allFields. type: { value: new Type(function (value, deep) { return self.check(value, deep); }, typeName) } }); } Def.fromValue = function (value) { if (value && typeof value === "object") { var type = value.type; if (typeof type === "string" && hasOwn.call(defCache, type)) { var d = defCache[type]; if (d.finalized) { return d; } } } return null; }; var Dp = Def.prototype; Dp.isSupertypeOf = function (that) { if (that instanceof Def) { if (this.finalized !== true || that.finalized !== true) { throw new Error(""); } return hasOwn.call(that.allSupertypes, this.typeName); } else { throw new Error(that + " is not a Def"); } }; // Note that the list returned by this function is a copy of the internal // supertypeList, *without* the typeName itself as the first element. exports.getSupertypeNames = function (typeName) { if (!hasOwn.call(defCache, typeName)) { throw new Error(""); } var d = defCache[typeName]; if (d.finalized !== true) { throw new Error(""); } return d.supertypeList.slice(1); }; // Returns an object mapping from every known type in the defCache to the // most specific supertype whose name is an own property of the candidates // object. exports.computeSupertypeLookupTable = function (candidates) { var table = {}; var typeNames = Object.keys(defCache); var typeNameCount = typeNames.length; for (var i = 0; i < typeNameCount; ++i) { var typeName = typeNames[i]; var d = defCache[typeName]; if (d.finalized !== true) { throw new Error("" + typeName); } for (var j = 0; j < d.supertypeList.length; ++j) { var superTypeName = d.supertypeList[j]; if (hasOwn.call(candidates, superTypeName)) { table[typeName] = superTypeName; break; } } } return table; }; Dp.checkAllFields = function (value, deep) { var allFields = this.allFields; if (this.finalized !== true) { throw new Error("" + this.typeName); } function checkFieldByName(name) { var field = allFields[name]; var type = field.type; var child = field.getValue(value); return type.check(child, deep); } return isObject.check(value) && Object.keys(allFields).every(checkFieldByName); }; Dp.check = function (value, deep) { if (this.finalized !== true) { throw new Error( "prematurely checking unfinalized type " + this.typeName ); } // A Def type can only match an object value. if (!isObject.check(value)) return false; var vDef = Def.fromValue(value); if (!vDef) { // If we couldn't infer the Def associated with the given value, // and we expected it to be a SourceLocation or a Position, it was // probably just missing a "type" field (because Esprima does not // assign a type property to such nodes). Be optimistic and let // this.checkAllFields make the final decision. if (this.typeName === "SourceLocation" || this.typeName === "Position") { return this.checkAllFields(value, deep); } // Calling this.checkAllFields for any other type of node is both // bad for performance and way too forgiving. return false; } // If checking deeply and vDef === this, then we only need to call // checkAllFields once. Calling checkAllFields is too strict when deep // is false, because then we only care about this.isSupertypeOf(vDef). if (deep && vDef === this) return this.checkAllFields(value, deep); // In most cases we rely exclusively on isSupertypeOf to make O(1) // subtyping determinations. This suffices in most situations outside // of unit tests, since interface conformance is checked whenever new // instances are created using builder functions. if (!this.isSupertypeOf(vDef)) return false; // The exception is when deep is true; then, we recursively check all // fields. if (!deep) return true; // Use the more specific Def (vDef) to perform the deep check, but // shallow-check fields defined by the less specific Def (this). return vDef.checkAllFields(value, deep) && this.checkAllFields(value, false); }; Dp.bases = function () { var args = slice.call(arguments); var bases = this.baseNames; if (this.finalized) { if (args.length !== bases.length) { throw new Error(""); } for (var i = 0; i < args.length; i++) { if (args[i] !== bases[i]) { throw new Error(""); } } return this; } args.forEach(function (baseName) { isString.assert(baseName); // This indexOf lookup may be O(n), but the typical number of base // names is very small, and indexOf is a native Array method. if (bases.indexOf(baseName) < 0) bases.push(baseName); }); return this; // For chaining. }; // False by default until .build(...) is called on an instance. Object.defineProperty(Dp, "buildable", {value: false}); var builders = {}; exports.builders = builders; // This object is used as prototype for any node created by a builder. var nodePrototype = {}; // Call this function to define a new method to be shared by all AST // nodes. The replaced method (if any) is returned for easy wrapping. exports.defineMethod = function (name, func) { var old = nodePrototype[name]; // Pass undefined as func to delete nodePrototype[name]. if (isUndefined.check(func)) { delete nodePrototype[name]; } else { isFunction.assert(func); Object.defineProperty(nodePrototype, name, { enumerable: true, // For discoverability. configurable: true, // For delete proto[name]. value: func }); } return old; }; var isArrayOfString = isString.arrayOf(); // Calling the .build method of a Def simultaneously marks the type as // buildable (by defining builders[getBuilderName(typeName)]) and // specifies the order of arguments that should be passed to the builder // function to create an instance of the type. Dp.build = function (/* param1, param2, ... */) { var self = this; var newBuildParams = slice.call(arguments); isArrayOfString.assert(newBuildParams); // Calling Def.prototype.build multiple times has the effect of merely // redefining this property. Object.defineProperty(self, "buildParams", { value: newBuildParams, writable: false, enumerable: false, configurable: true }); if (self.buildable) { // If this Def is already buildable, update self.buildParams and // continue using the old builder function. return self; } // Every buildable type will have its "type" field filled in // automatically. This includes types that are not subtypes of Node, // like SourceLocation, but that seems harmless (TODO?). self.field("type", String, function () { return self.typeName }); // Override Dp.buildable for this Def instance. Object.defineProperty(self, "buildable", {value: true}); Object.defineProperty(builders, getBuilderName(self.typeName), { enumerable: true, value: function () { var args = arguments; var argc = args.length; var built = Object.create(nodePrototype); if (!self.finalized) { throw new Error( "attempting to instantiate unfinalized type " + self.typeName ); } function add(param, i) { if (hasOwn.call(built, param)) return; var all = self.allFields; if (!hasOwn.call(all, param)) { throw new Error("" + param); } var field = all[param]; var type = field.type; var value; if (isNumber.check(i) && i < argc) { value = args[i]; } else if (field.defaultFn) { // Expose the partially-built object to the default // function as its `this` object. value = field.defaultFn.call(built); } else { var message = "no value or default function given for field " + JSON.stringify(param) + " of " + self.typeName + "(" + self.buildParams.map(function (name) { return all[name]; }).join(", ") + ")"; throw new Error(message); } if (!type.check(value)) { throw new Error( shallowStringify(value) + " does not match field " + field + " of type " + self.typeName ); } // TODO Could attach getters and setters here to enforce // dynamic type safety. built[param] = value; } self.buildParams.forEach(function (param, i) { add(param, i); }); Object.keys(self.allFields).forEach(function (param) { add(param); // Use the default value. }); // Make sure that the "type" field was filled automatically. if (built.type !== self.typeName) { throw new Error(""); } return built; } }); return self; // For chaining. }; function getBuilderName(typeName) { return typeName.replace(/^[A-Z]+/, function (upperCasePrefix) { var len = upperCasePrefix.length; switch (len) { case 0: return ""; // If there's only one initial capital letter, just lower-case it. case 1: return upperCasePrefix.toLowerCase(); default: // If there's more than one initial capital letter, lower-case // all but the last one, so that XMLDefaultDeclaration (for // example) becomes xmlDefaultDeclaration. return upperCasePrefix.slice( 0, len - 1).toLowerCase() + upperCasePrefix.charAt(len - 1); } }); } exports.getBuilderName = getBuilderName; function getStatementBuilderName(typeName) { typeName = getBuilderName(typeName); return typeName.replace(/(Expression)?$/, "Statement"); } exports.getStatementBuilderName = getStatementBuilderName; // The reason fields are specified using .field(...) instead of an object // literal syntax is somewhat subtle: the object literal syntax would // support only one key and one value, but with .field(...) we can pass // any number of arguments to specify the field. Dp.field = function (name, type, defaultFn, hidden) { if (this.finalized) { console.error("Ignoring attempt to redefine field " + JSON.stringify(name) + " of finalized type " + JSON.stringify(this.typeName)); return this; } this.ownFields[name] = new Field(name, type, defaultFn, hidden); return this; // For chaining. }; var namedTypes = {}; exports.namedTypes = namedTypes; // Like Object.keys, but aware of what fields each AST type should have. function getFieldNames(object) { var d = Def.fromValue(object); if (d) { return d.fieldNames.slice(0); } if ("type" in object) { throw new Error( "did not recognize object of type " + JSON.stringify(object.type) ); } return Object.keys(object); } exports.getFieldNames = getFieldNames; // Get the value of an object property, taking object.type and default // functions into account. function getFieldValue(object, fieldName) { var d = Def.fromValue(object); if (d) { var field = d.allFields[fieldName]; if (field) { return field.getValue(object); } } return object && object[fieldName]; } exports.getFieldValue = getFieldValue; // Iterate over all defined fields of an object, including those missing // or undefined, passing each field name and effective value (as returned // by getFieldValue) to the callback. If the object has no corresponding // Def, the callback will never be called. exports.eachField = function (object, callback, context) { getFieldNames(object).forEach(function (name) { callback.call(this, name, getFieldValue(object, name)); }, context); }; // Similar to eachField, except that iteration stops as soon as the // callback returns a truthy value. Like Array.prototype.some, the final // result is either true or false to indicates whether the callback // returned true for any element or not. exports.someField = function (object, callback, context) { return getFieldNames(object).some(function (name) { return callback.call(this, name, getFieldValue(object, name)); }, context); }; // This property will be overridden as true by individual Def instances // when they are finalized. Object.defineProperty(Dp, "finalized", {value: false}); Dp.finalize = function () { var self = this; // It's not an error to finalize a type more than once, but only the // first call to .finalize does anything. if (!self.finalized) { var allFields = self.allFields; var allSupertypes = self.allSupertypes; self.baseNames.forEach(function (name) { var def = defCache[name]; if (def instanceof Def) { def.finalize(); extend(allFields, def.allFields); extend(allSupertypes, def.allSupertypes); } else { var message = "unknown supertype name " + JSON.stringify(name) + " for subtype " + JSON.stringify(self.typeName); throw new Error(message); } }); // TODO Warn if fields are overridden with incompatible types. extend(allFields, self.ownFields); allSupertypes[self.typeName] = self; self.fieldNames.length = 0; for (var fieldName in allFields) { if (hasOwn.call(allFields, fieldName) && !allFields[fieldName].hidden) { self.fieldNames.push(fieldName); } } // Types are exported only once they have been finalized. Object.defineProperty(namedTypes, self.typeName, { enumerable: true, value: self.type }); Object.defineProperty(self, "finalized", {value: true}); // A linearization of the inheritance hierarchy. populateSupertypeList(self.typeName, self.supertypeList); if (self.buildable && self.supertypeList.lastIndexOf("Expression") >= 0) { wrapExpressionBuilderWithStatement(self.typeName); } } }; // Adds an additional builder for Expression subtypes // that wraps the built Expression in an ExpressionStatements. function wrapExpressionBuilderWithStatement(typeName) { var wrapperName = getStatementBuilderName(typeName); // skip if the builder already exists if (builders[wrapperName]) return; // the builder function to wrap with builders.ExpressionStatement var wrapped = builders[getBuilderName(typeName)]; // skip if there is nothing to wrap if (!wrapped) return; builders[wrapperName] = function () { return builders.expressionStatement(wrapped.apply(builders, arguments)); }; } function populateSupertypeList(typeName, list) { list.length = 0; list.push(typeName); var lastSeen = Object.create(null); for (var pos = 0; pos < list.length; ++pos) { typeName = list[pos]; var d = defCache[typeName]; if (d.finalized !== true) { throw new Error(""); } // If we saw typeName earlier in the breadth-first traversal, // delete the last-seen occurrence. if (hasOwn.call(lastSeen, typeName)) { delete list[lastSeen[typeName]]; } // Record the new index of the last-seen occurrence of typeName. lastSeen[typeName] = pos; // Enqueue the base names of this type. list.push.apply(list, d.baseNames); } // Compaction loop to remove array holes. for (var to = 0, from = to, len = list.length; from < len; ++from) { if (hasOwn.call(list, from)) { list[to++] = list[from]; } } list.length = to; } function extend(into, from) { Object.keys(from).forEach(function (name) { into[name] = from[name]; }); return into; }; exports.finalize = function () { Object.keys(defCache).forEach(function (name) { defCache[name].finalize(); }); }; return exports; }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var TAG = exports.TAG = 'tag'; var STRING = exports.STRING = 'string'; var SELECTOR = exports.SELECTOR = 'selector'; var ROOT = exports.ROOT = 'root'; var PSEUDO = exports.PSEUDO = 'pseudo'; var NESTING = exports.NESTING = 'nesting'; var ID = exports.ID = 'id'; var COMMENT = exports.COMMENT = 'comment'; var COMBINATOR = exports.COMBINATOR = 'combinator'; var CLASS = exports.CLASS = 'class'; var ATTRIBUTE = exports.ATTRIBUTE = 'attribute'; var UNIVERSAL = exports.UNIVERSAL = 'universal'; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PreludeGenerator = exports.NameGenerator = exports.Generator = undefined; var _index = __webpack_require__(0); var _index2 = __webpack_require__(5); var _index3 = __webpack_require__(35); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _internalizer = __webpack_require__(125); var _singletons = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function serializeBody(generator, context) { let statements = context.serializeGenerator(generator); if (statements.length === 1 && statements[0].type === "BlockStatement") return statements[0]; return t.blockStatement(statements); } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ class Generator { constructor(realm, name) { (0, _invariant2.default)(realm.useAbstractInterpretation); let realmPreludeGenerator = realm.preludeGenerator; (0, _invariant2.default)(realmPreludeGenerator); this.preludeGenerator = realmPreludeGenerator; this.realm = realm; this._entries = []; this.id = realm.nextGeneratorId++; this._name = name; } getName() { return this._name || `#${this.id}`; } getAsPropertyNameExpression(key, canBeIdentifier = true) { // If key is a non-negative numeric string literal, parse it and set it as a numeric index instead. let index = Number.parseInt(key, 10); if (index >= 0 && index.toString() === key) { return t.numericLiteral(index); } if (canBeIdentifier) { // TODO #1020: revert this when Unicode identifiers are supported by all targetted JavaScript engines let keyIsAscii = /^[\u0000-\u007f]*$/.test(key); if (t.isValidIdentifier(key) && keyIsAscii) return t.identifier(key); } return t.stringLiteral(key); } empty() { return this._entries.length === 0; } emitGlobalDeclaration(key, value) { this.preludeGenerator.declaredGlobals.add(key); if (!(value instanceof _index.UndefinedValue)) this.emitGlobalAssignment(key, value, true); } emitGlobalAssignment(key, value, strictMode) { this._addEntry({ args: [value], buildNode: ([valueNode]) => t.expressionStatement(t.assignmentExpression("=", this.preludeGenerator.globalReference(key, !strictMode), valueNode)) }); } emitConcreteModel(key, value) { this._addEntry({ args: [(0, _singletons.concretize)(this.realm, value)], buildNode: ([valueNode]) => t.expressionStatement(t.assignmentExpression("=", this.preludeGenerator.globalReference(key, false), valueNode)) }); } emitGlobalDelete(key, strictMode) { this._addEntry({ args: [], buildNode: ([]) => t.expressionStatement(t.unaryExpression("delete", this.preludeGenerator.globalReference(key, !strictMode))) }); } emitBindingAssignment(binding, value) { this._addEntry({ args: [value], buildNode: ([valueNode], context) => t.expressionStatement(t.assignmentExpression("=", context.serializeBinding(binding), valueNode)) }); } emitPropertyAssignment(object, key, value) { if (object.refuseSerialization) return; let propName = this.getAsPropertyNameExpression(key); this._addEntry({ args: [object, value], buildNode: ([objectNode, valueNode]) => t.expressionStatement(t.assignmentExpression("=", t.memberExpression(objectNode, propName, !t.isIdentifier(propName)), valueNode)) }); } emitDefineProperty(object, key, desc, isDescChanged = true) { if (object.refuseSerialization) return; if (desc.enumerable && desc.configurable && desc.writable && desc.value && !isDescChanged) { let descValue = desc.value; (0, _invariant2.default)(descValue instanceof _index.Value); this.emitPropertyAssignment(object, key, descValue); } else { desc = Object.assign({}, desc); let descValue = desc.value || object.$Realm.intrinsics.undefined; (0, _invariant2.default)(descValue instanceof _index.Value); this._addEntry({ args: [object, descValue, desc.get || object.$Realm.intrinsics.undefined, desc.set || object.$Realm.intrinsics.undefined], buildNode: (_, context) => context.emitDefinePropertyBody(object, key, desc) }); } } emitPropertyDelete(object, key) { if (object.refuseSerialization) return; let propName = this.getAsPropertyNameExpression(key); this._addEntry({ args: [object], buildNode: ([objectNode]) => t.expressionStatement(t.unaryExpression("delete", t.memberExpression(objectNode, propName, !t.isIdentifier(propName)))) }); } emitCall(createCallee, args) { this._addEntry({ args, buildNode: values => t.expressionStatement(t.callExpression(createCallee(), [...values])) }); } emitConsoleLog(method, args) { this.emitCall(() => t.memberExpression(t.identifier("console"), t.identifier(method)), args.map(v => typeof v === "string" ? new _index.StringValue(this.realm, v) : v)); } // test must be a temporal value, which means that it must have a defined intrinsicName emitDoWhileStatement(test, body) { this._addEntry({ args: [], buildNode: function ([], context) { let testId = test.intrinsicName; (0, _invariant2.default)(testId !== undefined); let statements = context.serializeGenerator(body); let block = t.blockStatement(statements); return t.doWhileStatement(t.identifier(testId), block); }, dependencies: [body] }); } // Checks the full set of possible concrete values as well as typeof // for any AbstractValues // e.g: (obj.property !== undefined && typeof obj.property !== "object") // NB: if the type of the AbstractValue is top, skips the invariant emitFullInvariant(object, key, value) { let propertyIdentifier = this.getAsPropertyNameExpression(key); let computed = !t.isIdentifier(propertyIdentifier); let accessedPropertyOf = objectNode => t.memberExpression(objectNode, propertyIdentifier, computed); let condition; if (value instanceof _index.AbstractValue) { let isTop = false; let concreteComparisons = []; let typeComparisons = new Set(); function populateComparisonsLists(absValue) { if (absValue.kind === "abstractConcreteUnion") { // recurse for (let nestedValue of absValue.args) if (nestedValue instanceof _index.ConcreteValue) { concreteComparisons.push(nestedValue); } else { (0, _invariant2.default)(nestedValue instanceof _index.AbstractValue); populateComparisonsLists(nestedValue); } } else if (absValue.getType().isTop || absValue.getType() === _index.Value) { isTop = true; } else { typeComparisons.add(absValue.getType()); } } populateComparisonsLists(value); // No point in doing the invariant if we don't know the type // of one of the nested abstract values if (isTop) { return; } else { condition = ([valueNode]) => { // Create `object.property !== concreteValue` let checks = concreteComparisons.map(concreteValue => t.binaryExpression("!==", valueNode, t.valueToNode(concreteValue.serialize()))); // Create `typeof object.property !== typeValue` checks = checks.concat([...typeComparisons].map(typeValue => { let typeString = _singletons.Utils.typeToString(typeValue); (0, _invariant2.default)(typeString !== undefined, typeValue); return t.binaryExpression("!==", t.unaryExpression("typeof", valueNode, true), t.stringLiteral(typeString)); })); return checks.reduce((expr, newCondition) => t.logicalExpression("&&", expr, newCondition)); }; this.emitInvariant([value, value], condition, valueNode => valueNode); } } else { condition = ([objectNode, valueNode]) => t.binaryExpression("!==", accessedPropertyOf(objectNode), valueNode); this.emitInvariant([object, value, object], condition, objnode => accessedPropertyOf(objnode)); } } emitInvariant(args, violationConditionFn, appendLastToInvariantFn) { if (this.realm.omitInvariants) return; this._addEntry({ args, buildNode: nodes => { let throwString = t.stringLiteral("Prepack model invariant violation"); if (appendLastToInvariantFn) { let last = nodes.pop(); throwString = t.binaryExpression("+", t.stringLiteral("Prepack model invariant violation: "), appendLastToInvariantFn(last)); } let condition = violationConditionFn(nodes); let throwblock = t.blockStatement([t.throwStatement(t.newExpression(t.identifier("Error"), [throwString]))]); return t.ifStatement(condition, throwblock); } }); } emitCallAndCaptureResult(types, values, createCallee, args, kind) { return this.derive(types, values, args, nodes => t.callExpression(createCallee(), nodes)); } emitStatement(args, buildNode_) { this._addEntry({ args, buildNode: buildNode_ }); } emitVoidExpression(types, values, args, buildNode_) { this._addEntry({ args, buildNode: nodes => t.expressionStatement(buildNode_ instanceof Function ? buildNode_(nodes) : buildNode_) }); return this.realm.intrinsics.undefined; } emitForInStatement(o, lh, sourceObject, targetObject, boundName) { this._addEntry({ // duplicate args to ensure refcount > 1 args: [o, targetObject, sourceObject, targetObject, sourceObject], buildNode: ([obj, tgt, src, obj1, tgt1, src1]) => { return t.forInStatement(lh, obj, t.blockStatement([t.expressionStatement(t.assignmentExpression("=", t.memberExpression(tgt, boundName, true), t.memberExpression(src, boundName, true)))])); } }); } derive(types, values, args, buildNode_, optionalArgs) { (0, _invariant2.default)(buildNode_ instanceof Function || args.length === 0); let id = t.identifier(this.preludeGenerator.nameGenerator.generate("derived")); this.preludeGenerator.derivedIds.set(id.name, args); let options = {}; if (optionalArgs && optionalArgs.kind) options.kind = optionalArgs.kind; let Constructor = _index.Value.isTypeCompatibleWith(types.getType(), _index.ObjectValue) ? _index.AbstractObjectValue : _index.AbstractValue; let res = new Constructor(this.realm, types, values, (0, _index2.hashString)(id.name), [], id, options); this._addEntry({ isPure: optionalArgs ? optionalArgs.isPure : undefined, declared: res, args, buildNode: (nodes, context) => { return t.variableDeclaration("var", [t.variableDeclarator(id, buildNode_ instanceof Function ? buildNode_(nodes, context) : buildNode_)]); } }); let type = types.getType(); res.intrinsicName = id.name; if (optionalArgs && optionalArgs.skipInvariant) return res; let typeofString; if (type instanceof _index.FunctionValue) typeofString = "function";else if (type === _index.UndefinedValue) (0, _invariant2.default)(false);else if (type === _index.NullValue) (0, _invariant2.default)(false);else if (type === _index.StringValue) typeofString = "string";else if (type === _index.BooleanValue) typeofString = "boolean";else if (type === _index.NumberValue) typeofString = "number";else if (type === _index.IntegralValue) typeofString = "number";else if (type === _index.SymbolValue) typeofString = "symbol";else if (type === _index.ObjectValue) typeofString = "object"; if (typeofString !== undefined) { // Verify that the types are as expected, a failure of this invariant // should mean the model is wrong. this.emitInvariant([res, res], nodes => { (0, _invariant2.default)(typeofString !== undefined); let condition = t.binaryExpression("!==", t.unaryExpression("typeof", nodes[0]), t.stringLiteral(typeofString)); if (typeofString === "object") { condition = t.logicalExpression("&&", condition, t.binaryExpression("!==", t.unaryExpression("typeof", nodes[0]), t.stringLiteral("function"))); condition = t.logicalExpression("||", condition, t.binaryExpression("===", nodes[0], _internalizer.nullExpression)); } return condition; }, node => node); } return res; } serialize(context) { for (let entry of this._entries) { if (!entry.isPure || !entry.declared || !context.canOmit(entry.declared)) { let nodes = entry.args.map((boundArg, i) => context.serializeValue(boundArg)); if (entry.buildNode) { let node = entry.buildNode(nodes, context); if (node.type === "BlockStatement") { let block = node; let statements = block.body; if (statements.length === 0) continue; if (statements.length === 1) { node = statements[0]; } } context.emit(node); } if (entry.declared !== undefined) context.declare(entry.declared); } } } visitEntry(entry, callbacks) { if (entry.isPure && entry.declared && callbacks.canSkip(entry.declared)) { callbacks.recordDelayedEntry(this, entry); } else { if (entry.declared) callbacks.recordDeclaration(entry.declared); callbacks.visitValues(entry.args); if (entry.dependencies) for (let dependency of entry.dependencies) callbacks.visitGenerator(dependency, this); } } visit(callbacks) { for (let entry of this._entries) this.visitEntry(entry, callbacks); } _addEntry(entry) { this._entries.push(entry); } appendGenerator(other, leadingComment) { if (other.empty()) return; this._addEntry({ args: [], buildNode: function (args, context) { let statements = context.serializeGenerator(other); if (statements.length === 1) { let statement = statements[0]; if (leadingComment.length > 0) statement.leadingComments = [{ type: "BlockComment", value: leadingComment }]; return statement; } let block = t.blockStatement(statements); if (leadingComment.length > 0) block.leadingComments = [{ type: "BlockComment", value: leadingComment }]; return block; }, dependencies: [other] }); } composeGenerators(generator1, generator2) { this._addEntry({ args: [], buildNode: function ([], context) { let statements1 = generator1.empty() ? [] : context.serializeGenerator(generator1); let statements2 = generator2.empty() ? [] : context.serializeGenerator(generator2); let statements = statements1.concat(statements2); if (statements.length === 1) return statements[0]; return t.blockStatement(statements); }, dependencies: [generator1, generator2] }); } joinGenerators(joinCondition, generator1, generator2) { this._addEntry({ args: [joinCondition], buildNode: function ([cond], context) { let block1 = generator1.empty() ? null : serializeBody(generator1, context); let block2 = generator2.empty() ? null : serializeBody(generator2, context); if (block1) return t.ifStatement(cond, block1, block2); (0, _invariant2.default)(block2); return t.ifStatement(t.unaryExpression("!", cond), block2); }, dependencies: [generator1, generator2] }); } } exports.Generator = Generator; // some characters are invalid within a JavaScript identifier, // such as: . , : ( ) ' " ` [ ] - // so we replace these character instances with an underscore function replaceInvalidCharactersWithUnderscore(string) { return string.replace(/[.,:\(\)\"\'\`\[\]\-]/g, "_"); } const base62characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; function base62encode(n) { (0, _invariant2.default)((n | 0) === n && n >= 0); if (n === 0) return "0"; let s = ""; while (n > 0) { let f = n % base62characters.length; s = base62characters[f] + s; n = (n - f) / base62characters.length; } return s; } class NameGenerator { constructor(forbiddenNames, debugNames, uniqueSuffix, prefix) { this.prefix = prefix; this.uidCounter = 0; this.debugNames = debugNames; this.forbiddenNames = forbiddenNames; this.uniqueSuffix = uniqueSuffix; } generate(debugSuffix) { let id; do { id = this.prefix + base62encode(this.uidCounter++); if (this.uniqueSuffix.length > 0) id += this.uniqueSuffix; if (this.debugNames) { if (debugSuffix) id += "_" + replaceInvalidCharactersWithUnderscore(debugSuffix);else id += "_"; } } while (this.forbiddenNames.has(id)); return id; } } exports.NameGenerator = NameGenerator; class PreludeGenerator { constructor(debugNames, uniqueSuffix) { this.prelude = []; this.derivedIds = new Map(); this.memoizedRefs = new Map(); this.nameGenerator = new NameGenerator(new Set(), !!debugNames, uniqueSuffix || "", "_$"); this.usesThis = false; this.declaredGlobals = new Set(); } createNameGenerator(prefix) { return new NameGenerator(this.nameGenerator.forbiddenNames, this.nameGenerator.debugNames, this.nameGenerator.uniqueSuffix, prefix); } convertStringToMember(str) { return str.split(".").map(name => { if (name === "global") { return this.memoizeReference(name); } else if (name === "this") { return t.thisExpression(); } else { return t.identifier(name); } }).reduce((obj, prop) => t.memberExpression(obj, prop)); } globalReference(key, globalScope = false) { if (globalScope && t.isValidIdentifier(key)) return t.identifier(key); let keyNode = t.isValidIdentifier(key) ? t.identifier(key) : t.stringLiteral(key); return t.memberExpression(this.memoizeReference("global"), keyNode, !t.isIdentifier(keyNode)); } memoizeReference(key) { let ref = this.memoizedRefs.get(key); if (ref) return ref; let init; if (key.includes("(") || key.includes("[")) { // Horrible but effective hack: // Some internal object have intrinsic names such as // ([][Symbol.iterator]().__proto__.__proto__) // and // RegExp.prototype[Symbol.match] // which get turned into a babel node here. // TODO: We should properly parse such a string, and memoize all references in it separately. // Instead, we just turn it into a funky identifier, which Babel seems to accept. init = t.identifier(key); } else if (key === "global") { this.usesThis = true; init = t.thisExpression(); } else { let i = key.lastIndexOf("."); if (i === -1) { init = t.memberExpression(this.memoizeReference("global"), t.identifier(key)); } else { init = t.memberExpression(this.memoizeReference(key.substr(0, i)), t.identifier(key.substr(i + 1))); } } ref = t.identifier(this.nameGenerator.generate(key)); this.prelude.push(t.variableDeclaration("var", [t.variableDeclarator(ref, init)])); this.memoizedRefs.set(key, ref); return ref; } } exports.PreludeGenerator = PreludeGenerator; //# sourceMappingURL=generator.js.map /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _TypesDomain = __webpack_require__(1909); Object.defineProperty(exports, "TypesDomain", { enumerable: true, get: function () { return _interopRequireDefault(_TypesDomain).default; } }); var _ValuesDomain = __webpack_require__(1910); Object.defineProperty(exports, "ValuesDomain", { enumerable: true, get: function () { return _interopRequireDefault(_ValuesDomain).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } //# sourceMappingURL=index.js.map /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js // original notice: /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ function compare(a, b) { if (a === b) { return 0; } var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) { return -1; } if (y < x) { return 1; } return 0; } function isBuffer(b) { if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { return global.Buffer.isBuffer(b); } return !!(b != null && b._isBuffer); } // based on node assert, original notice: // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. var util = __webpack_require__(98); var hasOwn = Object.prototype.hasOwnProperty; var pSlice = Array.prototype.slice; var functionsHaveNames = (function () { return function foo() {}.name === 'foo'; }()); function pToString (obj) { return Object.prototype.toString.call(obj); } function isView(arrbuf) { if (isBuffer(arrbuf)) { return false; } if (typeof global.ArrayBuffer !== 'function') { return false; } if (typeof ArrayBuffer.isView === 'function') { return ArrayBuffer.isView(arrbuf); } if (!arrbuf) { return false; } if (arrbuf instanceof DataView) { return true; } if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { return true; } return false; } // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) var regex = /\s*function\s+([^\(\s]*)\s*/; // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js function getName(func) { if (!util.isFunction(func)) { return; } if (functionsHaveNames) { return func.name; } var str = func.toString(); var match = str.match(regex); return match && match[1]; } assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // non v8 browsers so we can have a stacktrace var err = new Error(); if (err.stack) { var out = err.stack; // try to strip useless frames var fn_name = getName(stackStartFunction); var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { // once we have located the function frame // we need to strip out everything before it (and its line) var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function truncate(s, n) { if (typeof s === 'string') { return s.length < n ? s : s.slice(0, n); } else { return s; } } function inspect(something) { if (functionsHaveNames || !util.isFunction(something)) { return util.inspect(something); } var rawname = getName(something); var name = rawname ? ': ' + rawname : ''; return '[Function' + name + ']'; } function getMessage(self) { return truncate(inspect(self.actual), 128) + ' ' + self.operator + ' ' + truncate(inspect(self.expected), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (!_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); } }; function _deepEqual(actual, expected, strict, memos) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (isBuffer(actual) && isBuffer(expected)) { return compare(actual, expected) === 0; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) { return strict ? actual === expected : actual == expected; // If both values are instances of typed arrays, wrap their underlying // ArrayBuffers in a Buffer each to increase performance // This optimization requires the arrays to have the same type as checked by // Object.prototype.toString (aka pToString). Never perform binary // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their // bit patterns are not identical. } else if (isView(actual) && isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || actual instanceof Float64Array)) { return compare(new Uint8Array(actual.buffer), new Uint8Array(expected.buffer)) === 0; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else if (isBuffer(actual) !== isBuffer(expected)) { return false; } else { memos = memos || {actual: [], expected: []}; var actualIndex = memos.actual.indexOf(actual); if (actualIndex !== -1) { if (actualIndex === memos.expected.indexOf(expected)) { return true; } } memos.actual.push(actual); memos.expected.push(expected); return objEquiv(actual, expected, strict, memos); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; // if one is a primitive, the other must be same if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; var aIsArgs = isArguments(a); var bIsArgs = isArguments(b); if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) return false; if (aIsArgs) { a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b, strict); } var ka = objectKeys(a); var kb = objectKeys(b); var key, i; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length !== kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] !== kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; assert.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); } } // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } try { if (actual instanceof expected) { return true; } } catch (e) { // Ignore. The instanceof check doesn't work for arrow functions. } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function _tryBlock(block) { var error; try { block(); } catch (e) { error = e; } return error; } function _throws(shouldThrow, block, expected, message) { var actual; if (typeof block !== 'function') { throw new TypeError('"block" argument must be a function'); } if (typeof expected === 'string') { message = expected; expected = null; } actual = _tryBlock(block); message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } var userProvidedMessage = typeof message === 'string'; var isUnwantedException = !shouldThrow && util.isError(actual); var isUnexpectedException = !shouldThrow && actual && !expected; if ((isUnwantedException && userProvidedMessage && expectedException(actual, expected)) || isUnexpectedException) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws(true, block, error, message); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { _throws(false, block, error, message); }; assert.ifError = function(err) { if (err) throw err; }; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(14))) /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var elliptic = exports; elliptic.version = __webpack_require__(2286).version; elliptic.utils = __webpack_require__(2287); elliptic.rand = __webpack_require__(665); elliptic.curve = __webpack_require__(231); elliptic.curves = __webpack_require__(2292); // Protocols elliptic.ec = __webpack_require__(2300); elliptic.eddsa = __webpack_require__(2304); /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Return flexbox spec versions by prefix */ module.exports = function (prefix) { var spec = void 0; if (prefix === '-webkit- 2009' || prefix === '-moz-') { spec = 2009; } else if (prefix === '-ms-') { spec = 2012; } else if (prefix === '-webkit-') { spec = 'final'; } if (prefix === '-webkit- 2009') { prefix = '-webkit-'; } return [spec, prefix]; }; /***/ }), /* 39 */ /***/ (function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _declaration = __webpack_require__(284); var _declaration2 = _interopRequireDefault(_declaration); var _processor = __webpack_require__(509); var _processor2 = _interopRequireDefault(_processor); var _stringify = __webpack_require__(286); var _stringify2 = _interopRequireDefault(_stringify); var _comment = __webpack_require__(288); var _comment2 = _interopRequireDefault(_comment); var _atRule = __webpack_require__(212); var _atRule2 = _interopRequireDefault(_atRule); var _vendor = __webpack_require__(1296); var _vendor2 = _interopRequireDefault(_vendor); var _parse = __webpack_require__(287); var _parse2 = _interopRequireDefault(_parse); var _list = __webpack_require__(511); var _list2 = _interopRequireDefault(_list); var _rule = __webpack_require__(213); var _rule2 = _interopRequireDefault(_rule); var _root = __webpack_require__(290); var _root2 = _interopRequireDefault(_root); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Create a new {@link Processor} instance that will apply `plugins` * as CSS processors. * * @param {Array.|Processor} plugins - PostCSS * plugins. See {@link Processor#use} for plugin format. * * @return {Processor} Processor to process multiple CSS * * @example * import postcss from 'postcss'; * * postcss(plugins).process(css, { from, to }).then(result => { * console.log(result.css); * }); * * @namespace postcss */ function postcss() { for (var _len = arguments.length, plugins = Array(_len), _key = 0; _key < _len; _key++) { plugins[_key] = arguments[_key]; } if (plugins.length === 1 && Array.isArray(plugins[0])) { plugins = plugins[0]; } return new _processor2.default(plugins); } /** * Creates a PostCSS plugin with a standard API. * * The newly-wrapped function will provide both the name and PostCSS * version of the plugin. * * ```js * const processor = postcss([replace]); * processor.plugins[0].postcssPlugin //=> 'postcss-replace' * processor.plugins[0].postcssVersion //=> '5.1.0' * ``` * * The plugin function receives 2 arguments: {@link Root} * and {@link Result} instance. The function should mutate the provided * `Root` node. Alternatively, you can create a new `Root` node * and override the `result.root` property. * * ```js * const cleaner = postcss.plugin('postcss-cleaner', () => { * return (root, result) => { * result.root = postcss.root(); * }; * }); * ``` * * As a convenience, plugins also expose a `process` method so that you can use * them as standalone tools. * * ```js * cleaner.process(css, processOpts, pluginOpts); * // This is equivalent to: * postcss([ cleaner(pluginOpts) ]).process(css, processOpts); * ``` * * Asynchronous plugins should return a `Promise` instance. * * ```js * postcss.plugin('postcss-import', () => { * return (root, result) => { * return new Promise( (resolve, reject) => { * fs.readFile('base.css', (base) => { * root.prepend(base); * resolve(); * }); * }); * }; * }); * ``` * * Add warnings using the {@link Node#warn} method. * Send data to other plugins using the {@link Result#messages} array. * * ```js * postcss.plugin('postcss-caniuse-test', () => { * return (root, result) => { * css.walkDecls(decl => { * if ( !caniuse.support(decl.prop) ) { * decl.warn(result, 'Some browsers do not support ' + decl.prop); * } * }); * }; * }); * ``` * * @param {string} name - PostCSS plugin name. Same as in `name` * property in `package.json`. It will be saved * in `plugin.postcssPlugin` property. * @param {function} initializer - will receive plugin options * and should return {@link pluginFunction} * * @return {Plugin} PostCSS plugin */ postcss.plugin = function plugin(name, initializer) { var creator = function creator() { var transformer = initializer.apply(undefined, arguments); transformer.postcssPlugin = name; transformer.postcssVersion = new _processor2.default().version; return transformer; }; var cache = void 0; Object.defineProperty(creator, 'postcss', { get: function get() { if (!cache) cache = creator(); return cache; } }); creator.process = function (css, processOpts, pluginOpts) { return postcss([creator(pluginOpts)]).process(css, processOpts); }; return creator; }; /** * Default function to convert a node tree into a CSS string. * * @param {Node} node - start node for stringifing. Usually {@link Root}. * @param {builder} builder - function to concatenate CSS from node’s parts * or generate string and source map * * @return {void} * * @function */ postcss.stringify = _stringify2.default; /** * Parses source css and returns a new {@link Root} node, * which contains the source CSS nodes. * * @param {string|toString} css - string with input CSS or any object * with toString() method, like a Buffer * @param {processOptions} [opts] - options with only `from` and `map` keys * * @return {Root} PostCSS AST * * @example * // Simple CSS concatenation with source map support * const root1 = postcss.parse(css1, { from: file1 }); * const root2 = postcss.parse(css2, { from: file2 }); * root1.append(root2).toResult().css; * * @function */ postcss.parse = _parse2.default; /** * @member {vendor} - Contains the {@link vendor} module. * * @example * postcss.vendor.unprefixed('-moz-tab') //=> ['tab'] */ postcss.vendor = _vendor2.default; /** * @member {list} - Contains the {@link list} module. * * @example * postcss.list.space('5px calc(10% + 5px)') //=> ['5px', 'calc(10% + 5px)'] */ postcss.list = _list2.default; /** * Creates a new {@link Comment} node. * * @param {object} [defaults] - properties for the new node. * * @return {Comment} new Comment node * * @example * postcss.comment({ text: 'test' }) */ postcss.comment = function (defaults) { return new _comment2.default(defaults); }; /** * Creates a new {@link AtRule} node. * * @param {object} [defaults] - properties for the new node. * * @return {AtRule} new AtRule node * * @example * postcss.atRule({ name: 'charset' }).toString() //=> "@charset" */ postcss.atRule = function (defaults) { return new _atRule2.default(defaults); }; /** * Creates a new {@link Declaration} node. * * @param {object} [defaults] - properties for the new node. * * @return {Declaration} new Declaration node * * @example * postcss.decl({ prop: 'color', value: 'red' }).toString() //=> "color: red" */ postcss.decl = function (defaults) { return new _declaration2.default(defaults); }; /** * Creates a new {@link Rule} node. * * @param {object} [defaults] - properties for the new node. * * @return {Rule} new Rule node * * @example * postcss.rule({ selector: 'a' }).toString() //=> "a {\n}" */ postcss.rule = function (defaults) { return new _rule2.default(defaults); }; /** * Creates a new {@link Root} node. * * @param {object} [defaults] - properties for the new node. * * @return {Root} new Root node * * @example * postcss.root({ after: '\n' }).toString() //=> "\n" */ postcss.root = function (defaults) { return new _root2.default(defaults); }; exports.default = postcss; module.exports = exports['default']; //# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInBvc3Rjc3MuZXM2Il0sIm5hbWVzIjpbInBvc3Rjc3MiLCJwbHVnaW5zIiwibGVuZ3RoIiwiQXJyYXkiLCJpc0FycmF5IiwicGx1Z2luIiwibmFtZSIsImluaXRpYWxpemVyIiwiY3JlYXRvciIsInRyYW5zZm9ybWVyIiwicG9zdGNzc1BsdWdpbiIsInBvc3Rjc3NWZXJzaW9uIiwidmVyc2lvbiIsImNhY2hlIiwiT2JqZWN0IiwiZGVmaW5lUHJvcGVydHkiLCJnZXQiLCJwcm9jZXNzIiwiY3NzIiwicHJvY2Vzc09wdHMiLCJwbHVnaW5PcHRzIiwic3RyaW5naWZ5IiwicGFyc2UiLCJ2ZW5kb3IiLCJsaXN0IiwiY29tbWVudCIsImRlZmF1bHRzIiwiYXRSdWxlIiwiZGVjbCIsInJ1bGUiLCJyb290Il0sIm1hcHBpbmdzIjoiOzs7O0FBQUE7Ozs7QUFDQTs7OztBQUNBOzs7O0FBQ0E7Ozs7QUFDQTs7OztBQUNBOzs7O0FBQ0E7Ozs7QUFDQTs7OztBQUNBOzs7O0FBQ0E7Ozs7OztBQUVBOzs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFrQkEsU0FBU0EsT0FBVCxHQUE2QjtBQUFBLG9DQUFUQyxPQUFTO0FBQVRBLFdBQVM7QUFBQTs7QUFDekIsTUFBS0EsUUFBUUMsTUFBUixLQUFtQixDQUFuQixJQUF3QkMsTUFBTUMsT0FBTixDQUFjSCxRQUFRLENBQVIsQ0FBZCxDQUE3QixFQUF5RDtBQUNyREEsY0FBVUEsUUFBUSxDQUFSLENBQVY7QUFDSDtBQUNELFNBQU8sd0JBQWNBLE9BQWQsQ0FBUDtBQUNIOztBQUVEOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUF3RUFELFFBQVFLLE1BQVIsR0FBaUIsU0FBU0EsTUFBVCxDQUFnQkMsSUFBaEIsRUFBc0JDLFdBQXRCLEVBQW1DO0FBQ2hELE1BQUlDLFVBQVUsU0FBVkEsT0FBVSxHQUFtQjtBQUM3QixRQUFJQyxjQUFjRix1Q0FBbEI7QUFDQUUsZ0JBQVlDLGFBQVosR0FBNkJKLElBQTdCO0FBQ0FHLGdCQUFZRSxjQUFaLEdBQThCLHlCQUFELENBQWtCQyxPQUEvQztBQUNBLFdBQU9ILFdBQVA7QUFDSCxHQUxEOztBQU9BLE1BQUlJLGNBQUo7QUFDQUMsU0FBT0MsY0FBUCxDQUFzQlAsT0FBdEIsRUFBK0IsU0FBL0IsRUFBMEM7QUFDdENRLE9BRHNDLGlCQUNoQztBQUNGLFVBQUssQ0FBQ0gsS0FBTixFQUFjQSxRQUFRTCxTQUFSO0FBQ2QsYUFBT0ssS0FBUDtBQUNIO0FBSnFDLEdBQTFDOztBQU9BTCxVQUFRUyxPQUFSLEdBQWtCLFVBQVVDLEdBQVYsRUFBZUMsV0FBZixFQUE0QkMsVUFBNUIsRUFBd0M7QUFDdEQsV0FBT3BCLFFBQVEsQ0FBRVEsUUFBUVksVUFBUixDQUFGLENBQVIsRUFBaUNILE9BQWpDLENBQXlDQyxHQUF6QyxFQUE4Q0MsV0FBOUMsQ0FBUDtBQUNILEdBRkQ7O0FBSUEsU0FBT1gsT0FBUDtBQUNILENBckJEOztBQXVCQTs7Ozs7Ozs7Ozs7QUFXQVIsUUFBUXFCLFNBQVI7O0FBRUE7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQWtCQXJCLFFBQVFzQixLQUFSOztBQUVBOzs7Ozs7QUFNQXRCLFFBQVF1QixNQUFSOztBQUVBOzs7Ozs7QUFNQXZCLFFBQVF3QixJQUFSOztBQUVBOzs7Ozs7Ozs7O0FBVUF4QixRQUFReUIsT0FBUixHQUFrQjtBQUFBLFNBQVksc0JBQVlDLFFBQVosQ0FBWjtBQUFBLENBQWxCOztBQUVBOzs7Ozs7Ozs7O0FBVUExQixRQUFRMkIsTUFBUixHQUFpQjtBQUFBLFNBQVkscUJBQVdELFFBQVgsQ0FBWjtBQUFBLENBQWpCOztBQUVBOzs7Ozs7Ozs7O0FBVUExQixRQUFRNEIsSUFBUixHQUFlO0FBQUEsU0FBWSwwQkFBZ0JGLFFBQWhCLENBQVo7QUFBQSxDQUFmOztBQUVBOzs7Ozs7Ozs7O0FBVUExQixRQUFRNkIsSUFBUixHQUFlO0FBQUEsU0FBWSxtQkFBU0gsUUFBVCxDQUFaO0FBQUEsQ0FBZjs7QUFFQTs7Ozs7Ozs7OztBQVVBMUIsUUFBUThCLElBQVIsR0FBZTtBQUFBLFNBQVksbUJBQVNKLFFBQVQsQ0FBWjtBQUFBLENBQWY7O2tCQUVlMUIsTyIsImZpbGUiOiJwb3N0Y3NzLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERlY2xhcmF0aW9uIGZyb20gJy4vZGVjbGFyYXRpb24nO1xuaW1wb3J0IFByb2Nlc3NvciAgIGZyb20gJy4vcHJvY2Vzc29yJztcbmltcG9ydCBzdHJpbmdpZnkgICBmcm9tICcuL3N0cmluZ2lmeSc7XG5pbXBvcnQgQ29tbWVudCAgICAgZnJvbSAnLi9jb21tZW50JztcbmltcG9ydCBBdFJ1bGUgICAgICBmcm9tICcuL2F0LXJ1bGUnO1xuaW1wb3J0IHZlbmRvciAgICAgIGZyb20gJy4vdmVuZG9yJztcbmltcG9ydCBwYXJzZSAgICAgICBmcm9tICcuL3BhcnNlJztcbmltcG9ydCBsaXN0ICAgICAgICBmcm9tICcuL2xpc3QnO1xuaW1wb3J0IFJ1bGUgICAgICAgIGZyb20gJy4vcnVsZSc7XG5pbXBvcnQgUm9vdCAgICAgICAgZnJvbSAnLi9yb290JztcblxuLyoqXG4gKiBDcmVhdGUgYSBuZXcge0BsaW5rIFByb2Nlc3Nvcn0gaW5zdGFuY2UgdGhhdCB3aWxsIGFwcGx5IGBwbHVnaW5zYFxuICogYXMgQ1NTIHByb2Nlc3NvcnMuXG4gKlxuICogQHBhcmFtIHtBcnJheS48UGx1Z2lufHBsdWdpbkZ1bmN0aW9uPnxQcm9jZXNzb3J9IHBsdWdpbnMgLSBQb3N0Q1NTXG4gKiAgICAgICAgcGx1Z2lucy4gU2VlIHtAbGluayBQcm9jZXNzb3IjdXNlfSBmb3IgcGx1Z2luIGZvcm1hdC5cbiAqXG4gKiBAcmV0dXJuIHtQcm9jZXNzb3J9IFByb2Nlc3NvciB0byBwcm9jZXNzIG11bHRpcGxlIENTU1xuICpcbiAqIEBleGFtcGxlXG4gKiBpbXBvcnQgcG9zdGNzcyBmcm9tICdwb3N0Y3NzJztcbiAqXG4gKiBwb3N0Y3NzKHBsdWdpbnMpLnByb2Nlc3MoY3NzLCB7IGZyb20sIHRvIH0pLnRoZW4ocmVzdWx0ID0+IHtcbiAqICAgY29uc29sZS5sb2cocmVzdWx0LmNzcyk7XG4gKiB9KTtcbiAqXG4gKiBAbmFtZXNwYWNlIHBvc3Rjc3NcbiAqL1xuZnVuY3Rpb24gcG9zdGNzcyguLi5wbHVnaW5zKSB7XG4gICAgaWYgKCBwbHVnaW5zLmxlbmd0aCA9PT0gMSAmJiBBcnJheS5pc0FycmF5KHBsdWdpbnNbMF0pICkge1xuICAgICAgICBwbHVnaW5zID0gcGx1Z2luc1swXTtcbiAgICB9XG4gICAgcmV0dXJuIG5ldyBQcm9jZXNzb3IocGx1Z2lucyk7XG59XG5cbi8qKlxuICogQ3JlYXRlcyBhIFBvc3RDU1MgcGx1Z2luIHdpdGggYSBzdGFuZGFyZCBBUEkuXG4gKlxuICogVGhlIG5ld2x5LXdyYXBwZWQgZnVuY3Rpb24gd2lsbCBwcm92aWRlIGJvdGggdGhlIG5hbWUgYW5kIFBvc3RDU1NcbiAqIHZlcnNpb24gb2YgdGhlIHBsdWdpbi5cbiAqXG4gKiBgYGBqc1xuICogIGNvbnN0IHByb2Nlc3NvciA9IHBvc3Rjc3MoW3JlcGxhY2VdKTtcbiAqICBwcm9jZXNzb3IucGx1Z2luc1swXS5wb3N0Y3NzUGx1Z2luICAvLz0+ICdwb3N0Y3NzLXJlcGxhY2UnXG4gKiAgcHJvY2Vzc29yLnBsdWdpbnNbMF0ucG9zdGNzc1ZlcnNpb24gLy89PiAnNS4xLjAnXG4gKiBgYGBcbiAqXG4gKiBUaGUgcGx1Z2luIGZ1bmN0aW9uIHJlY2VpdmVzIDIgYXJndW1lbnRzOiB7QGxpbmsgUm9vdH1cbiAqIGFuZCB7QGxpbmsgUmVzdWx0fSBpbnN0YW5jZS4gVGhlIGZ1bmN0aW9uIHNob3VsZCBtdXRhdGUgdGhlIHByb3ZpZGVkXG4gKiBgUm9vdGAgbm9kZS4gQWx0ZXJuYXRpdmVseSwgeW91IGNhbiBjcmVhdGUgYSBuZXcgYFJvb3RgIG5vZGVcbiAqIGFuZCBvdmVycmlkZSB0aGUgYHJlc3VsdC5yb290YCBwcm9wZXJ0eS5cbiAqXG4gKiBgYGBqc1xuICogY29uc3QgY2xlYW5lciA9IHBvc3Rjc3MucGx1Z2luKCdwb3N0Y3NzLWNsZWFuZXInLCAoKSA9PiB7XG4gKiAgIHJldHVybiAocm9vdCwgcmVzdWx0KSA9PiB7XG4gKiAgICAgcmVzdWx0LnJvb3QgPSBwb3N0Y3NzLnJvb3QoKTtcbiAqICAgfTtcbiAqIH0pO1xuICogYGBgXG4gKlxuICogQXMgYSBjb252ZW5pZW5jZSwgcGx1Z2lucyBhbHNvIGV4cG9zZSBhIGBwcm9jZXNzYCBtZXRob2Qgc28gdGhhdCB5b3UgY2FuIHVzZVxuICogdGhlbSBhcyBzdGFuZGFsb25lIHRvb2xzLlxuICpcbiAqIGBgYGpzXG4gKiBjbGVhbmVyLnByb2Nlc3MoY3NzLCBwcm9jZXNzT3B0cywgcGx1Z2luT3B0cyk7XG4gKiAvLyBUaGlzIGlzIGVxdWl2YWxlbnQgdG86XG4gKiBwb3N0Y3NzKFsgY2xlYW5lcihwbHVnaW5PcHRzKSBdKS5wcm9jZXNzKGNzcywgcHJvY2Vzc09wdHMpO1xuICogYGBgXG4gKlxuICogQXN5bmNocm9ub3VzIHBsdWdpbnMgc2hvdWxkIHJldHVybiBhIGBQcm9taXNlYCBpbnN0YW5jZS5cbiAqXG4gKiBgYGBqc1xuICogcG9zdGNzcy5wbHVnaW4oJ3Bvc3Rjc3MtaW1wb3J0JywgKCkgPT4ge1xuICogICByZXR1cm4gKHJvb3QsIHJlc3VsdCkgPT4ge1xuICogICAgIHJldHVybiBuZXcgUHJvbWlzZSggKHJlc29sdmUsIHJlamVjdCkgPT4ge1xuICogICAgICAgZnMucmVhZEZpbGUoJ2Jhc2UuY3NzJywgKGJhc2UpID0+IHtcbiAqICAgICAgICAgcm9vdC5wcmVwZW5kKGJhc2UpO1xuICogICAgICAgICByZXNvbHZlKCk7XG4gKiAgICAgICB9KTtcbiAqICAgICB9KTtcbiAqICAgfTtcbiAqIH0pO1xuICogYGBgXG4gKlxuICogQWRkIHdhcm5pbmdzIHVzaW5nIHRoZSB7QGxpbmsgTm9kZSN3YXJufSBtZXRob2QuXG4gKiBTZW5kIGRhdGEgdG8gb3RoZXIgcGx1Z2lucyB1c2luZyB0aGUge0BsaW5rIFJlc3VsdCNtZXNzYWdlc30gYXJyYXkuXG4gKlxuICogYGBganNcbiAqIHBvc3Rjc3MucGx1Z2luKCdwb3N0Y3NzLWNhbml1c2UtdGVzdCcsICgpID0+IHtcbiAqICAgcmV0dXJuIChyb290LCByZXN1bHQpID0+IHtcbiAqICAgICBjc3Mud2Fsa0RlY2xzKGRlY2wgPT4ge1xuICogICAgICAgaWYgKCAhY2FuaXVzZS5zdXBwb3J0KGRlY2wucHJvcCkgKSB7XG4gKiAgICAgICAgIGRlY2wud2FybihyZXN1bHQsICdTb21lIGJyb3dzZXJzIGRvIG5vdCBzdXBwb3J0ICcgKyBkZWNsLnByb3ApO1xuICogICAgICAgfVxuICogICAgIH0pO1xuICogICB9O1xuICogfSk7XG4gKiBgYGBcbiAqXG4gKiBAcGFyYW0ge3N0cmluZ30gbmFtZSAgICAgICAgICAtIFBvc3RDU1MgcGx1Z2luIG5hbWUuIFNhbWUgYXMgaW4gYG5hbWVgXG4gKiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHByb3BlcnR5IGluIGBwYWNrYWdlLmpzb25gLiBJdCB3aWxsIGJlIHNhdmVkXG4gKiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGluIGBwbHVnaW4ucG9zdGNzc1BsdWdpbmAgcHJvcGVydHkuXG4gKiBAcGFyYW0ge2Z1bmN0aW9ufSBpbml0aWFsaXplciAtIHdpbGwgcmVjZWl2ZSBwbHVnaW4gb3B0aW9uc1xuICogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBhbmQgc2hvdWxkIHJldHVybiB7QGxpbmsgcGx1Z2luRnVuY3Rpb259XG4gKlxuICogQHJldHVybiB7UGx1Z2lufSBQb3N0Q1NTIHBsdWdpblxuICovXG5wb3N0Y3NzLnBsdWdpbiA9IGZ1bmN0aW9uIHBsdWdpbihuYW1lLCBpbml0aWFsaXplcikge1xuICAgIGxldCBjcmVhdG9yID0gZnVuY3Rpb24gKC4uLmFyZ3MpIHtcbiAgICAgICAgbGV0IHRyYW5zZm9ybWVyID0gaW5pdGlhbGl6ZXIoLi4uYXJncyk7XG4gICAgICAgIHRyYW5zZm9ybWVyLnBvc3Rjc3NQbHVnaW4gID0gbmFtZTtcbiAgICAgICAgdHJhbnNmb3JtZXIucG9zdGNzc1ZlcnNpb24gPSAobmV3IFByb2Nlc3NvcigpKS52ZXJzaW9uO1xuICAgICAgICByZXR1cm4gdHJhbnNmb3JtZXI7XG4gICAgfTtcblxuICAgIGxldCBjYWNoZTtcbiAgICBPYmplY3QuZGVmaW5lUHJvcGVydHkoY3JlYXRvciwgJ3Bvc3Rjc3MnLCB7XG4gICAgICAgIGdldCgpIHtcbiAgICAgICAgICAgIGlmICggIWNhY2hlICkgY2FjaGUgPSBjcmVhdG9yKCk7XG4gICAgICAgICAgICByZXR1cm4gY2FjaGU7XG4gICAgICAgIH1cbiAgICB9KTtcblxuICAgIGNyZWF0b3IucHJvY2VzcyA9IGZ1bmN0aW9uIChjc3MsIHByb2Nlc3NPcHRzLCBwbHVnaW5PcHRzKSB7XG4gICAgICAgIHJldHVybiBwb3N0Y3NzKFsgY3JlYXRvcihwbHVnaW5PcHRzKSBdKS5wcm9jZXNzKGNzcywgcHJvY2Vzc09wdHMpO1xuICAgIH07XG5cbiAgICByZXR1cm4gY3JlYXRvcjtcbn07XG5cbi8qKlxuICogRGVmYXVsdCBmdW5jdGlvbiB0byBjb252ZXJ0IGEgbm9kZSB0cmVlIGludG8gYSBDU1Mgc3RyaW5nLlxuICpcbiAqIEBwYXJhbSB7Tm9kZX0gbm9kZSAgICAgICAtIHN0YXJ0IG5vZGUgZm9yIHN0cmluZ2lmaW5nLiBVc3VhbGx5IHtAbGluayBSb290fS5cbiAqIEBwYXJhbSB7YnVpbGRlcn0gYnVpbGRlciAtIGZ1bmN0aW9uIHRvIGNvbmNhdGVuYXRlIENTUyBmcm9tIG5vZGXigJlzIHBhcnRzXG4gKiAgICAgICAgICAgICAgICAgICAgICAgICAgICBvciBnZW5lcmF0ZSBzdHJpbmcgYW5kIHNvdXJjZSBtYXBcbiAqXG4gKiBAcmV0dXJuIHt2b2lkfVxuICpcbiAqIEBmdW5jdGlvblxuICovXG5wb3N0Y3NzLnN0cmluZ2lmeSA9IHN0cmluZ2lmeTtcblxuLyoqXG4gKiBQYXJzZXMgc291cmNlIGNzcyBhbmQgcmV0dXJucyBhIG5ldyB7QGxpbmsgUm9vdH0gbm9kZSxcbiAqIHdoaWNoIGNvbnRhaW5zIHRoZSBzb3VyY2UgQ1NTIG5vZGVzLlxuICpcbiAqIEBwYXJhbSB7c3RyaW5nfHRvU3RyaW5nfSBjc3MgICAtIHN0cmluZyB3aXRoIGlucHV0IENTUyBvciBhbnkgb2JqZWN0XG4gKiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB3aXRoIHRvU3RyaW5nKCkgbWV0aG9kLCBsaWtlIGEgQnVmZmVyXG4gKiBAcGFyYW0ge3Byb2Nlc3NPcHRpb25zfSBbb3B0c10gLSBvcHRpb25zIHdpdGggb25seSBgZnJvbWAgYW5kIGBtYXBgIGtleXNcbiAqXG4gKiBAcmV0dXJuIHtSb290fSBQb3N0Q1NTIEFTVFxuICpcbiAqIEBleGFtcGxlXG4gKiAvLyBTaW1wbGUgQ1NTIGNvbmNhdGVuYXRpb24gd2l0aCBzb3VyY2UgbWFwIHN1cHBvcnRcbiAqIGNvbnN0IHJvb3QxID0gcG9zdGNzcy5wYXJzZShjc3MxLCB7IGZyb206IGZpbGUxIH0pO1xuICogY29uc3Qgcm9vdDIgPSBwb3N0Y3NzLnBhcnNlKGNzczIsIHsgZnJvbTogZmlsZTIgfSk7XG4gKiByb290MS5hcHBlbmQocm9vdDIpLnRvUmVzdWx0KCkuY3NzO1xuICpcbiAqIEBmdW5jdGlvblxuICovXG5wb3N0Y3NzLnBhcnNlID0gcGFyc2U7XG5cbi8qKlxuICogQG1lbWJlciB7dmVuZG9yfSAtIENvbnRhaW5zIHRoZSB7QGxpbmsgdmVuZG9yfSBtb2R1bGUuXG4gKlxuICogQGV4YW1wbGVcbiAqIHBvc3Rjc3MudmVuZG9yLnVucHJlZml4ZWQoJy1tb3otdGFiJykgLy89PiBbJ3RhYiddXG4gKi9cbnBvc3Rjc3MudmVuZG9yID0gdmVuZG9yO1xuXG4vKipcbiAqIEBtZW1iZXIge2xpc3R9IC0gQ29udGFpbnMgdGhlIHtAbGluayBsaXN0fSBtb2R1bGUuXG4gKlxuICogQGV4YW1wbGVcbiAqIHBvc3Rjc3MubGlzdC5zcGFjZSgnNXB4IGNhbGMoMTAlICsgNXB4KScpIC8vPT4gWyc1cHgnLCAnY2FsYygxMCUgKyA1cHgpJ11cbiAqL1xucG9zdGNzcy5saXN0ID0gbGlzdDtcblxuLyoqXG4gKiBDcmVhdGVzIGEgbmV3IHtAbGluayBDb21tZW50fSBub2RlLlxuICpcbiAqIEBwYXJhbSB7b2JqZWN0fSBbZGVmYXVsdHNdIC0gcHJvcGVydGllcyBmb3IgdGhlIG5ldyBub2RlLlxuICpcbiAqIEByZXR1cm4ge0NvbW1lbnR9IG5ldyBDb21tZW50IG5vZGVcbiAqXG4gKiBAZXhhbXBsZVxuICogcG9zdGNzcy5jb21tZW50KHsgdGV4dDogJ3Rlc3QnIH0pXG4gKi9cbnBvc3Rjc3MuY29tbWVudCA9IGRlZmF1bHRzID0+IG5ldyBDb21tZW50KGRlZmF1bHRzKTtcblxuLyoqXG4gKiBDcmVhdGVzIGEgbmV3IHtAbGluayBBdFJ1bGV9IG5vZGUuXG4gKlxuICogQHBhcmFtIHtvYmplY3R9IFtkZWZhdWx0c10gLSBwcm9wZXJ0aWVzIGZvciB0aGUgbmV3IG5vZGUuXG4gKlxuICogQHJldHVybiB7QXRSdWxlfSBuZXcgQXRSdWxlIG5vZGVcbiAqXG4gKiBAZXhhbXBsZVxuICogcG9zdGNzcy5hdFJ1bGUoeyBuYW1lOiAnY2hhcnNldCcgfSkudG9TdHJpbmcoKSAvLz0+IFwiQGNoYXJzZXRcIlxuICovXG5wb3N0Y3NzLmF0UnVsZSA9IGRlZmF1bHRzID0+IG5ldyBBdFJ1bGUoZGVmYXVsdHMpO1xuXG4vKipcbiAqIENyZWF0ZXMgYSBuZXcge0BsaW5rIERlY2xhcmF0aW9ufSBub2RlLlxuICpcbiAqIEBwYXJhbSB7b2JqZWN0fSBbZGVmYXVsdHNdIC0gcHJvcGVydGllcyBmb3IgdGhlIG5ldyBub2RlLlxuICpcbiAqIEByZXR1cm4ge0RlY2xhcmF0aW9ufSBuZXcgRGVjbGFyYXRpb24gbm9kZVxuICpcbiAqIEBleGFtcGxlXG4gKiBwb3N0Y3NzLmRlY2woeyBwcm9wOiAnY29sb3InLCB2YWx1ZTogJ3JlZCcgfSkudG9TdHJpbmcoKSAvLz0+IFwiY29sb3I6IHJlZFwiXG4gKi9cbnBvc3Rjc3MuZGVjbCA9IGRlZmF1bHRzID0+IG5ldyBEZWNsYXJhdGlvbihkZWZhdWx0cyk7XG5cbi8qKlxuICogQ3JlYXRlcyBhIG5ldyB7QGxpbmsgUnVsZX0gbm9kZS5cbiAqXG4gKiBAcGFyYW0ge29iamVjdH0gW2RlZmF1bHRzXSAtIHByb3BlcnRpZXMgZm9yIHRoZSBuZXcgbm9kZS5cbiAqXG4gKiBAcmV0dXJuIHtSdWxlfSBuZXcgUnVsZSBub2RlXG4gKlxuICogQGV4YW1wbGVcbiAqIHBvc3Rjc3MucnVsZSh7IHNlbGVjdG9yOiAnYScgfSkudG9TdHJpbmcoKSAvLz0+IFwiYSB7XFxufVwiXG4gKi9cbnBvc3Rjc3MucnVsZSA9IGRlZmF1bHRzID0+IG5ldyBSdWxlKGRlZmF1bHRzKTtcblxuLyoqXG4gKiBDcmVhdGVzIGEgbmV3IHtAbGluayBSb290fSBub2RlLlxuICpcbiAqIEBwYXJhbSB7b2JqZWN0fSBbZGVmYXVsdHNdIC0gcHJvcGVydGllcyBmb3IgdGhlIG5ldyBub2RlLlxuICpcbiAqIEByZXR1cm4ge1Jvb3R9IG5ldyBSb290IG5vZGVcbiAqXG4gKiBAZXhhbXBsZVxuICogcG9zdGNzcy5yb290KHsgYWZ0ZXI6ICdcXG4nIH0pLnRvU3RyaW5nKCkgLy89PiBcIlxcblwiXG4gKi9cbnBvc3Rjc3Mucm9vdCA9IGRlZmF1bHRzID0+IG5ldyBSb290KGRlZmF1bHRzKTtcblxuZXhwb3J0IGRlZmF1bHQgcG9zdGNzcztcbiJdfQ== /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HasName = HasName; exports.HasProperty = HasProperty; exports.HasOwnProperty = HasOwnProperty; exports.OrdinaryHasProperty = OrdinaryHasProperty; exports.HasCompatibleType = HasCompatibleType; exports.HasSomeCompatibleType = HasSomeCompatibleType; var _errors = __webpack_require__(6); var _index = __webpack_require__(5); var _index2 = __webpack_require__(0); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // 12.2.1.2 Static Semantics: HasName // 14.1.9 Static Semantics: HasName // 14.2.7 Static Semantics: HasName // 14.5.6 Static Semantics: HasName // 14.2.7 Static Semantics: HasName function HasName(realm, ast) { // 12.2.1.2 Static Semantics: HasName // CoverParenthesizedExpressionAndArrowParameterList // 14.2.7 Static Semantics: HasName if (ast.type === "ArrowFunctionExpression") return false; // 14.1.9 Static Semantics: HasName if (ast.type === "FunctionExpression") { // FunctionExpression: function (FormalParameters) {FunctionBody} if (ast.id === null) // 1. Return false. return false; // FunctionExpression: functionBindingIdentifier (FormalParameters) {FunctionBody} if (ast.id !== null) // 2. Return true return true; } // 14.5.6 Static Semantics: HasName if (ast.type === "ClassExpression") { // ClassExpression : class ClassTail if (ast.id === null) //1. Return false. return false; // ClassExpression : class BindingIdentifier ClassTail if (ast.id !== null) //1. return true; return true; } // 14.4.7 Static Semantics: HasName // GeneratorExpression throw Error("Unexpected AST node type : " + ast.type); } // ECMA262 7.3.10 /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function HasProperty(realm, O, P) { // 1. Assert: Type(O) is Object. // 2. Assert: IsPropertyKey(P) is true. (0, _invariant2.default)((0, _index.IsPropertyKey)(realm, P), "expected property key"); // 3. Return ? O.[[HasProperty]](P). return O.$HasProperty(P); } // ECMA262 7.3.11 function HasOwnProperty(realm, O, P) { // 1. Assert: Type(O) is Object. // 2. Assert: IsPropertyKey(P) is true. (0, _invariant2.default)((0, _index.IsPropertyKey)(realm, P), "not a valid property key"); // 3. Let desc be ? O.[[GetOwnProperty]](P). let desc = O.$GetOwnProperty(P); // 4. If desc is undefined, return false. if (desc === undefined) return false; _singletons.Properties.ThrowIfMightHaveBeenDeleted(desc.value); // 5. Return true. return true; } // ECMA262 9.1.7.1 function OrdinaryHasProperty(realm, O, P) { // 1. Assert: IsPropertyKey(P) is true. (0, _invariant2.default)(typeof P === "string" || (0, _index.IsPropertyKey)(realm, P), "expected property key"); // 2. Let hasOwn be ? O.[[GetOwnProperty]](P). let hasOwn = O.$GetOwnProperty(P); // 3. If hasOwn is not undefined, return true. if (hasOwn !== undefined) { _singletons.Properties.ThrowIfMightHaveBeenDeleted(hasOwn.value); return true; } // 4. Let parent be ? O.[[GetPrototypeOf]](). let parent = O.$GetPrototypeOf(); // 5. If parent is not null, then if (!(parent instanceof _index2.NullValue)) { (0, _invariant2.default)(parent instanceof _index2.ObjectValue); // a. Return ? parent.[[HasProperty]](P). return parent.$HasProperty(P); } // 6. Return false. return false; } // Checks if the given value is equal to or a subtype of the given type. // If the value is an abstract value without precise type information, // an introspection error is thrown. function HasCompatibleType(value, type) { let valueType = value.getType(); if (valueType === _index2.Value) { (0, _invariant2.default)(value instanceof _index2.AbstractValue); _index2.AbstractValue.reportIntrospectionError(value); throw new _errors.FatalError(); } return _index2.Value.isTypeCompatibleWith(valueType, type); } function HasSomeCompatibleType(value, ...manyTypes) { let valueType = value.getType(); if (valueType === _index2.Value) { (0, _invariant2.default)(value instanceof _index2.AbstractValue); _index2.AbstractValue.reportIntrospectionError(value); throw new _errors.FatalError(); } return manyTypes.some(_index2.Value.isTypeCompatibleWith.bind(null, valueType)); } //# sourceMappingURL=has.js.map /***/ }), /* 43 */ /***/ (function(module, exports) { module.exports = assert; function assert(val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } assert.equal = function assertEqual(l, r, msg) { if (l != r) throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); }; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrayExpression = exports.ArrayExpression = ArrayExpression; exports.assignmentExpression = exports.AssignmentExpression = AssignmentExpression; exports.binaryExpression = exports.BinaryExpression = BinaryExpression; exports.interpreterDirective = exports.InterpreterDirective = InterpreterDirective; exports.directive = exports.Directive = Directive; exports.directiveLiteral = exports.DirectiveLiteral = DirectiveLiteral; exports.blockStatement = exports.BlockStatement = BlockStatement; exports.breakStatement = exports.BreakStatement = BreakStatement; exports.callExpression = exports.CallExpression = CallExpression; exports.catchClause = exports.CatchClause = CatchClause; exports.conditionalExpression = exports.ConditionalExpression = ConditionalExpression; exports.continueStatement = exports.ContinueStatement = ContinueStatement; exports.debuggerStatement = exports.DebuggerStatement = DebuggerStatement; exports.doWhileStatement = exports.DoWhileStatement = DoWhileStatement; exports.emptyStatement = exports.EmptyStatement = EmptyStatement; exports.expressionStatement = exports.ExpressionStatement = ExpressionStatement; exports.file = exports.File = File; exports.forInStatement = exports.ForInStatement = ForInStatement; exports.forStatement = exports.ForStatement = ForStatement; exports.functionDeclaration = exports.FunctionDeclaration = FunctionDeclaration; exports.functionExpression = exports.FunctionExpression = FunctionExpression; exports.identifier = exports.Identifier = Identifier; exports.ifStatement = exports.IfStatement = IfStatement; exports.labeledStatement = exports.LabeledStatement = LabeledStatement; exports.stringLiteral = exports.StringLiteral = StringLiteral; exports.numericLiteral = exports.NumericLiteral = NumericLiteral; exports.nullLiteral = exports.NullLiteral = NullLiteral; exports.booleanLiteral = exports.BooleanLiteral = BooleanLiteral; exports.regExpLiteral = exports.RegExpLiteral = RegExpLiteral; exports.logicalExpression = exports.LogicalExpression = LogicalExpression; exports.memberExpression = exports.MemberExpression = MemberExpression; exports.newExpression = exports.NewExpression = NewExpression; exports.program = exports.Program = Program; exports.objectExpression = exports.ObjectExpression = ObjectExpression; exports.objectMethod = exports.ObjectMethod = ObjectMethod; exports.objectProperty = exports.ObjectProperty = ObjectProperty; exports.restElement = exports.RestElement = RestElement; exports.returnStatement = exports.ReturnStatement = ReturnStatement; exports.sequenceExpression = exports.SequenceExpression = SequenceExpression; exports.switchCase = exports.SwitchCase = SwitchCase; exports.switchStatement = exports.SwitchStatement = SwitchStatement; exports.thisExpression = exports.ThisExpression = ThisExpression; exports.throwStatement = exports.ThrowStatement = ThrowStatement; exports.tryStatement = exports.TryStatement = TryStatement; exports.unaryExpression = exports.UnaryExpression = UnaryExpression; exports.updateExpression = exports.UpdateExpression = UpdateExpression; exports.variableDeclaration = exports.VariableDeclaration = VariableDeclaration; exports.variableDeclarator = exports.VariableDeclarator = VariableDeclarator; exports.whileStatement = exports.WhileStatement = WhileStatement; exports.withStatement = exports.WithStatement = WithStatement; exports.assignmentPattern = exports.AssignmentPattern = AssignmentPattern; exports.arrayPattern = exports.ArrayPattern = ArrayPattern; exports.arrowFunctionExpression = exports.ArrowFunctionExpression = ArrowFunctionExpression; exports.classBody = exports.ClassBody = ClassBody; exports.classDeclaration = exports.ClassDeclaration = ClassDeclaration; exports.classExpression = exports.ClassExpression = ClassExpression; exports.exportAllDeclaration = exports.ExportAllDeclaration = ExportAllDeclaration; exports.exportDefaultDeclaration = exports.ExportDefaultDeclaration = ExportDefaultDeclaration; exports.exportNamedDeclaration = exports.ExportNamedDeclaration = ExportNamedDeclaration; exports.exportSpecifier = exports.ExportSpecifier = ExportSpecifier; exports.forOfStatement = exports.ForOfStatement = ForOfStatement; exports.importDeclaration = exports.ImportDeclaration = ImportDeclaration; exports.importDefaultSpecifier = exports.ImportDefaultSpecifier = ImportDefaultSpecifier; exports.importNamespaceSpecifier = exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; exports.importSpecifier = exports.ImportSpecifier = ImportSpecifier; exports.metaProperty = exports.MetaProperty = MetaProperty; exports.classMethod = exports.ClassMethod = ClassMethod; exports.objectPattern = exports.ObjectPattern = ObjectPattern; exports.spreadElement = exports.SpreadElement = SpreadElement; exports.super = exports.Super = Super; exports.taggedTemplateExpression = exports.TaggedTemplateExpression = TaggedTemplateExpression; exports.templateElement = exports.TemplateElement = TemplateElement; exports.templateLiteral = exports.TemplateLiteral = TemplateLiteral; exports.yieldExpression = exports.YieldExpression = YieldExpression; exports.anyTypeAnnotation = exports.AnyTypeAnnotation = AnyTypeAnnotation; exports.arrayTypeAnnotation = exports.ArrayTypeAnnotation = ArrayTypeAnnotation; exports.booleanTypeAnnotation = exports.BooleanTypeAnnotation = BooleanTypeAnnotation; exports.booleanLiteralTypeAnnotation = exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; exports.nullLiteralTypeAnnotation = exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; exports.classImplements = exports.ClassImplements = ClassImplements; exports.declareClass = exports.DeclareClass = DeclareClass; exports.declareFunction = exports.DeclareFunction = DeclareFunction; exports.declareInterface = exports.DeclareInterface = DeclareInterface; exports.declareModule = exports.DeclareModule = DeclareModule; exports.declareModuleExports = exports.DeclareModuleExports = DeclareModuleExports; exports.declareTypeAlias = exports.DeclareTypeAlias = DeclareTypeAlias; exports.declareOpaqueType = exports.DeclareOpaqueType = DeclareOpaqueType; exports.declareVariable = exports.DeclareVariable = DeclareVariable; exports.declareExportDeclaration = exports.DeclareExportDeclaration = DeclareExportDeclaration; exports.declareExportAllDeclaration = exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration; exports.declaredPredicate = exports.DeclaredPredicate = DeclaredPredicate; exports.existsTypeAnnotation = exports.ExistsTypeAnnotation = ExistsTypeAnnotation; exports.functionTypeAnnotation = exports.FunctionTypeAnnotation = FunctionTypeAnnotation; exports.functionTypeParam = exports.FunctionTypeParam = FunctionTypeParam; exports.genericTypeAnnotation = exports.GenericTypeAnnotation = GenericTypeAnnotation; exports.inferredPredicate = exports.InferredPredicate = InferredPredicate; exports.interfaceExtends = exports.InterfaceExtends = InterfaceExtends; exports.interfaceDeclaration = exports.InterfaceDeclaration = InterfaceDeclaration; exports.interfaceTypeAnnotation = exports.InterfaceTypeAnnotation = InterfaceTypeAnnotation; exports.intersectionTypeAnnotation = exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; exports.mixedTypeAnnotation = exports.MixedTypeAnnotation = MixedTypeAnnotation; exports.emptyTypeAnnotation = exports.EmptyTypeAnnotation = EmptyTypeAnnotation; exports.nullableTypeAnnotation = exports.NullableTypeAnnotation = NullableTypeAnnotation; exports.numberLiteralTypeAnnotation = exports.NumberLiteralTypeAnnotation = NumberLiteralTypeAnnotation; exports.numberTypeAnnotation = exports.NumberTypeAnnotation = NumberTypeAnnotation; exports.objectTypeAnnotation = exports.ObjectTypeAnnotation = ObjectTypeAnnotation; exports.objectTypeInternalSlot = exports.ObjectTypeInternalSlot = ObjectTypeInternalSlot; exports.objectTypeCallProperty = exports.ObjectTypeCallProperty = ObjectTypeCallProperty; exports.objectTypeIndexer = exports.ObjectTypeIndexer = ObjectTypeIndexer; exports.objectTypeProperty = exports.ObjectTypeProperty = ObjectTypeProperty; exports.objectTypeSpreadProperty = exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; exports.opaqueType = exports.OpaqueType = OpaqueType; exports.qualifiedTypeIdentifier = exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; exports.stringLiteralTypeAnnotation = exports.StringLiteralTypeAnnotation = StringLiteralTypeAnnotation; exports.stringTypeAnnotation = exports.StringTypeAnnotation = StringTypeAnnotation; exports.thisTypeAnnotation = exports.ThisTypeAnnotation = ThisTypeAnnotation; exports.tupleTypeAnnotation = exports.TupleTypeAnnotation = TupleTypeAnnotation; exports.typeofTypeAnnotation = exports.TypeofTypeAnnotation = TypeofTypeAnnotation; exports.typeAlias = exports.TypeAlias = TypeAlias; exports.typeAnnotation = exports.TypeAnnotation = TypeAnnotation; exports.typeCastExpression = exports.TypeCastExpression = TypeCastExpression; exports.typeParameter = exports.TypeParameter = TypeParameter; exports.typeParameterDeclaration = exports.TypeParameterDeclaration = TypeParameterDeclaration; exports.typeParameterInstantiation = exports.TypeParameterInstantiation = TypeParameterInstantiation; exports.unionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation; exports.variance = exports.Variance = Variance; exports.voidTypeAnnotation = exports.VoidTypeAnnotation = VoidTypeAnnotation; exports.jSXAttribute = exports.jsxAttribute = exports.JSXAttribute = JSXAttribute; exports.jSXClosingElement = exports.jsxClosingElement = exports.JSXClosingElement = JSXClosingElement; exports.jSXElement = exports.jsxElement = exports.JSXElement = JSXElement; exports.jSXEmptyExpression = exports.jsxEmptyExpression = exports.JSXEmptyExpression = JSXEmptyExpression; exports.jSXExpressionContainer = exports.jsxExpressionContainer = exports.JSXExpressionContainer = JSXExpressionContainer; exports.jSXSpreadChild = exports.jsxSpreadChild = exports.JSXSpreadChild = JSXSpreadChild; exports.jSXIdentifier = exports.jsxIdentifier = exports.JSXIdentifier = JSXIdentifier; exports.jSXMemberExpression = exports.jsxMemberExpression = exports.JSXMemberExpression = JSXMemberExpression; exports.jSXNamespacedName = exports.jsxNamespacedName = exports.JSXNamespacedName = JSXNamespacedName; exports.jSXOpeningElement = exports.jsxOpeningElement = exports.JSXOpeningElement = JSXOpeningElement; exports.jSXSpreadAttribute = exports.jsxSpreadAttribute = exports.JSXSpreadAttribute = JSXSpreadAttribute; exports.jSXText = exports.jsxText = exports.JSXText = JSXText; exports.jSXFragment = exports.jsxFragment = exports.JSXFragment = JSXFragment; exports.jSXOpeningFragment = exports.jsxOpeningFragment = exports.JSXOpeningFragment = JSXOpeningFragment; exports.jSXClosingFragment = exports.jsxClosingFragment = exports.JSXClosingFragment = JSXClosingFragment; exports.noop = exports.Noop = Noop; exports.parenthesizedExpression = exports.ParenthesizedExpression = ParenthesizedExpression; exports.awaitExpression = exports.AwaitExpression = AwaitExpression; exports.bindExpression = exports.BindExpression = BindExpression; exports.classProperty = exports.ClassProperty = ClassProperty; exports.optionalMemberExpression = exports.OptionalMemberExpression = OptionalMemberExpression; exports.optionalCallExpression = exports.OptionalCallExpression = OptionalCallExpression; exports.classPrivateProperty = exports.ClassPrivateProperty = ClassPrivateProperty; exports.import = exports.Import = Import; exports.decorator = exports.Decorator = Decorator; exports.doExpression = exports.DoExpression = DoExpression; exports.exportDefaultSpecifier = exports.ExportDefaultSpecifier = ExportDefaultSpecifier; exports.exportNamespaceSpecifier = exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; exports.privateName = exports.PrivateName = PrivateName; exports.bigIntLiteral = exports.BigIntLiteral = BigIntLiteral; exports.tSParameterProperty = exports.tsParameterProperty = exports.TSParameterProperty = TSParameterProperty; exports.tSDeclareFunction = exports.tsDeclareFunction = exports.TSDeclareFunction = TSDeclareFunction; exports.tSDeclareMethod = exports.tsDeclareMethod = exports.TSDeclareMethod = TSDeclareMethod; exports.tSQualifiedName = exports.tsQualifiedName = exports.TSQualifiedName = TSQualifiedName; exports.tSCallSignatureDeclaration = exports.tsCallSignatureDeclaration = exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration; exports.tSConstructSignatureDeclaration = exports.tsConstructSignatureDeclaration = exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration; exports.tSPropertySignature = exports.tsPropertySignature = exports.TSPropertySignature = TSPropertySignature; exports.tSMethodSignature = exports.tsMethodSignature = exports.TSMethodSignature = TSMethodSignature; exports.tSIndexSignature = exports.tsIndexSignature = exports.TSIndexSignature = TSIndexSignature; exports.tSAnyKeyword = exports.tsAnyKeyword = exports.TSAnyKeyword = TSAnyKeyword; exports.tSNumberKeyword = exports.tsNumberKeyword = exports.TSNumberKeyword = TSNumberKeyword; exports.tSObjectKeyword = exports.tsObjectKeyword = exports.TSObjectKeyword = TSObjectKeyword; exports.tSBooleanKeyword = exports.tsBooleanKeyword = exports.TSBooleanKeyword = TSBooleanKeyword; exports.tSStringKeyword = exports.tsStringKeyword = exports.TSStringKeyword = TSStringKeyword; exports.tSSymbolKeyword = exports.tsSymbolKeyword = exports.TSSymbolKeyword = TSSymbolKeyword; exports.tSVoidKeyword = exports.tsVoidKeyword = exports.TSVoidKeyword = TSVoidKeyword; exports.tSUndefinedKeyword = exports.tsUndefinedKeyword = exports.TSUndefinedKeyword = TSUndefinedKeyword; exports.tSNullKeyword = exports.tsNullKeyword = exports.TSNullKeyword = TSNullKeyword; exports.tSNeverKeyword = exports.tsNeverKeyword = exports.TSNeverKeyword = TSNeverKeyword; exports.tSThisType = exports.tsThisType = exports.TSThisType = TSThisType; exports.tSFunctionType = exports.tsFunctionType = exports.TSFunctionType = TSFunctionType; exports.tSConstructorType = exports.tsConstructorType = exports.TSConstructorType = TSConstructorType; exports.tSTypeReference = exports.tsTypeReference = exports.TSTypeReference = TSTypeReference; exports.tSTypePredicate = exports.tsTypePredicate = exports.TSTypePredicate = TSTypePredicate; exports.tSTypeQuery = exports.tsTypeQuery = exports.TSTypeQuery = TSTypeQuery; exports.tSTypeLiteral = exports.tsTypeLiteral = exports.TSTypeLiteral = TSTypeLiteral; exports.tSArrayType = exports.tsArrayType = exports.TSArrayType = TSArrayType; exports.tSTupleType = exports.tsTupleType = exports.TSTupleType = TSTupleType; exports.tSUnionType = exports.tsUnionType = exports.TSUnionType = TSUnionType; exports.tSIntersectionType = exports.tsIntersectionType = exports.TSIntersectionType = TSIntersectionType; exports.tSConditionalType = exports.tsConditionalType = exports.TSConditionalType = TSConditionalType; exports.tSInferType = exports.tsInferType = exports.TSInferType = TSInferType; exports.tSParenthesizedType = exports.tsParenthesizedType = exports.TSParenthesizedType = TSParenthesizedType; exports.tSTypeOperator = exports.tsTypeOperator = exports.TSTypeOperator = TSTypeOperator; exports.tSIndexedAccessType = exports.tsIndexedAccessType = exports.TSIndexedAccessType = TSIndexedAccessType; exports.tSMappedType = exports.tsMappedType = exports.TSMappedType = TSMappedType; exports.tSLiteralType = exports.tsLiteralType = exports.TSLiteralType = TSLiteralType; exports.tSExpressionWithTypeArguments = exports.tsExpressionWithTypeArguments = exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments; exports.tSInterfaceDeclaration = exports.tsInterfaceDeclaration = exports.TSInterfaceDeclaration = TSInterfaceDeclaration; exports.tSInterfaceBody = exports.tsInterfaceBody = exports.TSInterfaceBody = TSInterfaceBody; exports.tSTypeAliasDeclaration = exports.tsTypeAliasDeclaration = exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration; exports.tSAsExpression = exports.tsAsExpression = exports.TSAsExpression = TSAsExpression; exports.tSTypeAssertion = exports.tsTypeAssertion = exports.TSTypeAssertion = TSTypeAssertion; exports.tSEnumDeclaration = exports.tsEnumDeclaration = exports.TSEnumDeclaration = TSEnumDeclaration; exports.tSEnumMember = exports.tsEnumMember = exports.TSEnumMember = TSEnumMember; exports.tSModuleDeclaration = exports.tsModuleDeclaration = exports.TSModuleDeclaration = TSModuleDeclaration; exports.tSModuleBlock = exports.tsModuleBlock = exports.TSModuleBlock = TSModuleBlock; exports.tSImportEqualsDeclaration = exports.tsImportEqualsDeclaration = exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration; exports.tSExternalModuleReference = exports.tsExternalModuleReference = exports.TSExternalModuleReference = TSExternalModuleReference; exports.tSNonNullExpression = exports.tsNonNullExpression = exports.TSNonNullExpression = TSNonNullExpression; exports.tSExportAssignment = exports.tsExportAssignment = exports.TSExportAssignment = TSExportAssignment; exports.tSNamespaceExportDeclaration = exports.tsNamespaceExportDeclaration = exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration; exports.tSTypeAnnotation = exports.tsTypeAnnotation = exports.TSTypeAnnotation = TSTypeAnnotation; exports.tSTypeParameterInstantiation = exports.tsTypeParameterInstantiation = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation; exports.tSTypeParameterDeclaration = exports.tsTypeParameterDeclaration = exports.TSTypeParameterDeclaration = TSTypeParameterDeclaration; exports.tSTypeParameter = exports.tsTypeParameter = exports.TSTypeParameter = TSTypeParameter; exports.numberLiteral = exports.NumberLiteral = NumberLiteral; exports.regexLiteral = exports.RegexLiteral = RegexLiteral; exports.restProperty = exports.RestProperty = RestProperty; exports.spreadProperty = exports.SpreadProperty = SpreadProperty; var _builder = _interopRequireDefault(__webpack_require__(728)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function ArrayExpression(...args) { return (0, _builder.default)("ArrayExpression", ...args); } function AssignmentExpression(...args) { return (0, _builder.default)("AssignmentExpression", ...args); } function BinaryExpression(...args) { return (0, _builder.default)("BinaryExpression", ...args); } function InterpreterDirective(...args) { return (0, _builder.default)("InterpreterDirective", ...args); } function Directive(...args) { return (0, _builder.default)("Directive", ...args); } function DirectiveLiteral(...args) { return (0, _builder.default)("DirectiveLiteral", ...args); } function BlockStatement(...args) { return (0, _builder.default)("BlockStatement", ...args); } function BreakStatement(...args) { return (0, _builder.default)("BreakStatement", ...args); } function CallExpression(...args) { return (0, _builder.default)("CallExpression", ...args); } function CatchClause(...args) { return (0, _builder.default)("CatchClause", ...args); } function ConditionalExpression(...args) { return (0, _builder.default)("ConditionalExpression", ...args); } function ContinueStatement(...args) { return (0, _builder.default)("ContinueStatement", ...args); } function DebuggerStatement(...args) { return (0, _builder.default)("DebuggerStatement", ...args); } function DoWhileStatement(...args) { return (0, _builder.default)("DoWhileStatement", ...args); } function EmptyStatement(...args) { return (0, _builder.default)("EmptyStatement", ...args); } function ExpressionStatement(...args) { return (0, _builder.default)("ExpressionStatement", ...args); } function File(...args) { return (0, _builder.default)("File", ...args); } function ForInStatement(...args) { return (0, _builder.default)("ForInStatement", ...args); } function ForStatement(...args) { return (0, _builder.default)("ForStatement", ...args); } function FunctionDeclaration(...args) { return (0, _builder.default)("FunctionDeclaration", ...args); } function FunctionExpression(...args) { return (0, _builder.default)("FunctionExpression", ...args); } function Identifier(...args) { return (0, _builder.default)("Identifier", ...args); } function IfStatement(...args) { return (0, _builder.default)("IfStatement", ...args); } function LabeledStatement(...args) { return (0, _builder.default)("LabeledStatement", ...args); } function StringLiteral(...args) { return (0, _builder.default)("StringLiteral", ...args); } function NumericLiteral(...args) { return (0, _builder.default)("NumericLiteral", ...args); } function NullLiteral(...args) { return (0, _builder.default)("NullLiteral", ...args); } function BooleanLiteral(...args) { return (0, _builder.default)("BooleanLiteral", ...args); } function RegExpLiteral(...args) { return (0, _builder.default)("RegExpLiteral", ...args); } function LogicalExpression(...args) { return (0, _builder.default)("LogicalExpression", ...args); } function MemberExpression(...args) { return (0, _builder.default)("MemberExpression", ...args); } function NewExpression(...args) { return (0, _builder.default)("NewExpression", ...args); } function Program(...args) { return (0, _builder.default)("Program", ...args); } function ObjectExpression(...args) { return (0, _builder.default)("ObjectExpression", ...args); } function ObjectMethod(...args) { return (0, _builder.default)("ObjectMethod", ...args); } function ObjectProperty(...args) { return (0, _builder.default)("ObjectProperty", ...args); } function RestElement(...args) { return (0, _builder.default)("RestElement", ...args); } function ReturnStatement(...args) { return (0, _builder.default)("ReturnStatement", ...args); } function SequenceExpression(...args) { return (0, _builder.default)("SequenceExpression", ...args); } function SwitchCase(...args) { return (0, _builder.default)("SwitchCase", ...args); } function SwitchStatement(...args) { return (0, _builder.default)("SwitchStatement", ...args); } function ThisExpression(...args) { return (0, _builder.default)("ThisExpression", ...args); } function ThrowStatement(...args) { return (0, _builder.default)("ThrowStatement", ...args); } function TryStatement(...args) { return (0, _builder.default)("TryStatement", ...args); } function UnaryExpression(...args) { return (0, _builder.default)("UnaryExpression", ...args); } function UpdateExpression(...args) { return (0, _builder.default)("UpdateExpression", ...args); } function VariableDeclaration(...args) { return (0, _builder.default)("VariableDeclaration", ...args); } function VariableDeclarator(...args) { return (0, _builder.default)("VariableDeclarator", ...args); } function WhileStatement(...args) { return (0, _builder.default)("WhileStatement", ...args); } function WithStatement(...args) { return (0, _builder.default)("WithStatement", ...args); } function AssignmentPattern(...args) { return (0, _builder.default)("AssignmentPattern", ...args); } function ArrayPattern(...args) { return (0, _builder.default)("ArrayPattern", ...args); } function ArrowFunctionExpression(...args) { return (0, _builder.default)("ArrowFunctionExpression", ...args); } function ClassBody(...args) { return (0, _builder.default)("ClassBody", ...args); } function ClassDeclaration(...args) { return (0, _builder.default)("ClassDeclaration", ...args); } function ClassExpression(...args) { return (0, _builder.default)("ClassExpression", ...args); } function ExportAllDeclaration(...args) { return (0, _builder.default)("ExportAllDeclaration", ...args); } function ExportDefaultDeclaration(...args) { return (0, _builder.default)("ExportDefaultDeclaration", ...args); } function ExportNamedDeclaration(...args) { return (0, _builder.default)("ExportNamedDeclaration", ...args); } function ExportSpecifier(...args) { return (0, _builder.default)("ExportSpecifier", ...args); } function ForOfStatement(...args) { return (0, _builder.default)("ForOfStatement", ...args); } function ImportDeclaration(...args) { return (0, _builder.default)("ImportDeclaration", ...args); } function ImportDefaultSpecifier(...args) { return (0, _builder.default)("ImportDefaultSpecifier", ...args); } function ImportNamespaceSpecifier(...args) { return (0, _builder.default)("ImportNamespaceSpecifier", ...args); } function ImportSpecifier(...args) { return (0, _builder.default)("ImportSpecifier", ...args); } function MetaProperty(...args) { return (0, _builder.default)("MetaProperty", ...args); } function ClassMethod(...args) { return (0, _builder.default)("ClassMethod", ...args); } function ObjectPattern(...args) { return (0, _builder.default)("ObjectPattern", ...args); } function SpreadElement(...args) { return (0, _builder.default)("SpreadElement", ...args); } function Super(...args) { return (0, _builder.default)("Super", ...args); } function TaggedTemplateExpression(...args) { return (0, _builder.default)("TaggedTemplateExpression", ...args); } function TemplateElement(...args) { return (0, _builder.default)("TemplateElement", ...args); } function TemplateLiteral(...args) { return (0, _builder.default)("TemplateLiteral", ...args); } function YieldExpression(...args) { return (0, _builder.default)("YieldExpression", ...args); } function AnyTypeAnnotation(...args) { return (0, _builder.default)("AnyTypeAnnotation", ...args); } function ArrayTypeAnnotation(...args) { return (0, _builder.default)("ArrayTypeAnnotation", ...args); } function BooleanTypeAnnotation(...args) { return (0, _builder.default)("BooleanTypeAnnotation", ...args); } function BooleanLiteralTypeAnnotation(...args) { return (0, _builder.default)("BooleanLiteralTypeAnnotation", ...args); } function NullLiteralTypeAnnotation(...args) { return (0, _builder.default)("NullLiteralTypeAnnotation", ...args); } function ClassImplements(...args) { return (0, _builder.default)("ClassImplements", ...args); } function DeclareClass(...args) { return (0, _builder.default)("DeclareClass", ...args); } function DeclareFunction(...args) { return (0, _builder.default)("DeclareFunction", ...args); } function DeclareInterface(...args) { return (0, _builder.default)("DeclareInterface", ...args); } function DeclareModule(...args) { return (0, _builder.default)("DeclareModule", ...args); } function DeclareModuleExports(...args) { return (0, _builder.default)("DeclareModuleExports", ...args); } function DeclareTypeAlias(...args) { return (0, _builder.default)("DeclareTypeAlias", ...args); } function DeclareOpaqueType(...args) { return (0, _builder.default)("DeclareOpaqueType", ...args); } function DeclareVariable(...args) { return (0, _builder.default)("DeclareVariable", ...args); } function DeclareExportDeclaration(...args) { return (0, _builder.default)("DeclareExportDeclaration", ...args); } function DeclareExportAllDeclaration(...args) { return (0, _builder.default)("DeclareExportAllDeclaration", ...args); } function DeclaredPredicate(...args) { return (0, _builder.default)("DeclaredPredicate", ...args); } function ExistsTypeAnnotation(...args) { return (0, _builder.default)("ExistsTypeAnnotation", ...args); } function FunctionTypeAnnotation(...args) { return (0, _builder.default)("FunctionTypeAnnotation", ...args); } function FunctionTypeParam(...args) { return (0, _builder.default)("FunctionTypeParam", ...args); } function GenericTypeAnnotation(...args) { return (0, _builder.default)("GenericTypeAnnotation", ...args); } function InferredPredicate(...args) { return (0, _builder.default)("InferredPredicate", ...args); } function InterfaceExtends(...args) { return (0, _builder.default)("InterfaceExtends", ...args); } function InterfaceDeclaration(...args) { return (0, _builder.default)("InterfaceDeclaration", ...args); } function InterfaceTypeAnnotation(...args) { return (0, _builder.default)("InterfaceTypeAnnotation", ...args); } function IntersectionTypeAnnotation(...args) { return (0, _builder.default)("IntersectionTypeAnnotation", ...args); } function MixedTypeAnnotation(...args) { return (0, _builder.default)("MixedTypeAnnotation", ...args); } function EmptyTypeAnnotation(...args) { return (0, _builder.default)("EmptyTypeAnnotation", ...args); } function NullableTypeAnnotation(...args) { return (0, _builder.default)("NullableTypeAnnotation", ...args); } function NumberLiteralTypeAnnotation(...args) { return (0, _builder.default)("NumberLiteralTypeAnnotation", ...args); } function NumberTypeAnnotation(...args) { return (0, _builder.default)("NumberTypeAnnotation", ...args); } function ObjectTypeAnnotation(...args) { return (0, _builder.default)("ObjectTypeAnnotation", ...args); } function ObjectTypeInternalSlot(...args) { return (0, _builder.default)("ObjectTypeInternalSlot", ...args); } function ObjectTypeCallProperty(...args) { return (0, _builder.default)("ObjectTypeCallProperty", ...args); } function ObjectTypeIndexer(...args) { return (0, _builder.default)("ObjectTypeIndexer", ...args); } function ObjectTypeProperty(...args) { return (0, _builder.default)("ObjectTypeProperty", ...args); } function ObjectTypeSpreadProperty(...args) { return (0, _builder.default)("ObjectTypeSpreadProperty", ...args); } function OpaqueType(...args) { return (0, _builder.default)("OpaqueType", ...args); } function QualifiedTypeIdentifier(...args) { return (0, _builder.default)("QualifiedTypeIdentifier", ...args); } function StringLiteralTypeAnnotation(...args) { return (0, _builder.default)("StringLiteralTypeAnnotation", ...args); } function StringTypeAnnotation(...args) { return (0, _builder.default)("StringTypeAnnotation", ...args); } function ThisTypeAnnotation(...args) { return (0, _builder.default)("ThisTypeAnnotation", ...args); } function TupleTypeAnnotation(...args) { return (0, _builder.default)("TupleTypeAnnotation", ...args); } function TypeofTypeAnnotation(...args) { return (0, _builder.default)("TypeofTypeAnnotation", ...args); } function TypeAlias(...args) { return (0, _builder.default)("TypeAlias", ...args); } function TypeAnnotation(...args) { return (0, _builder.default)("TypeAnnotation", ...args); } function TypeCastExpression(...args) { return (0, _builder.default)("TypeCastExpression", ...args); } function TypeParameter(...args) { return (0, _builder.default)("TypeParameter", ...args); } function TypeParameterDeclaration(...args) { return (0, _builder.default)("TypeParameterDeclaration", ...args); } function TypeParameterInstantiation(...args) { return (0, _builder.default)("TypeParameterInstantiation", ...args); } function UnionTypeAnnotation(...args) { return (0, _builder.default)("UnionTypeAnnotation", ...args); } function Variance(...args) { return (0, _builder.default)("Variance", ...args); } function VoidTypeAnnotation(...args) { return (0, _builder.default)("VoidTypeAnnotation", ...args); } function JSXAttribute(...args) { return (0, _builder.default)("JSXAttribute", ...args); } function JSXClosingElement(...args) { return (0, _builder.default)("JSXClosingElement", ...args); } function JSXElement(...args) { return (0, _builder.default)("JSXElement", ...args); } function JSXEmptyExpression(...args) { return (0, _builder.default)("JSXEmptyExpression", ...args); } function JSXExpressionContainer(...args) { return (0, _builder.default)("JSXExpressionContainer", ...args); } function JSXSpreadChild(...args) { return (0, _builder.default)("JSXSpreadChild", ...args); } function JSXIdentifier(...args) { return (0, _builder.default)("JSXIdentifier", ...args); } function JSXMemberExpression(...args) { return (0, _builder.default)("JSXMemberExpression", ...args); } function JSXNamespacedName(...args) { return (0, _builder.default)("JSXNamespacedName", ...args); } function JSXOpeningElement(...args) { return (0, _builder.default)("JSXOpeningElement", ...args); } function JSXSpreadAttribute(...args) { return (0, _builder.default)("JSXSpreadAttribute", ...args); } function JSXText(...args) { return (0, _builder.default)("JSXText", ...args); } function JSXFragment(...args) { return (0, _builder.default)("JSXFragment", ...args); } function JSXOpeningFragment(...args) { return (0, _builder.default)("JSXOpeningFragment", ...args); } function JSXClosingFragment(...args) { return (0, _builder.default)("JSXClosingFragment", ...args); } function Noop(...args) { return (0, _builder.default)("Noop", ...args); } function ParenthesizedExpression(...args) { return (0, _builder.default)("ParenthesizedExpression", ...args); } function AwaitExpression(...args) { return (0, _builder.default)("AwaitExpression", ...args); } function BindExpression(...args) { return (0, _builder.default)("BindExpression", ...args); } function ClassProperty(...args) { return (0, _builder.default)("ClassProperty", ...args); } function OptionalMemberExpression(...args) { return (0, _builder.default)("OptionalMemberExpression", ...args); } function OptionalCallExpression(...args) { return (0, _builder.default)("OptionalCallExpression", ...args); } function ClassPrivateProperty(...args) { return (0, _builder.default)("ClassPrivateProperty", ...args); } function Import(...args) { return (0, _builder.default)("Import", ...args); } function Decorator(...args) { return (0, _builder.default)("Decorator", ...args); } function DoExpression(...args) { return (0, _builder.default)("DoExpression", ...args); } function ExportDefaultSpecifier(...args) { return (0, _builder.default)("ExportDefaultSpecifier", ...args); } function ExportNamespaceSpecifier(...args) { return (0, _builder.default)("ExportNamespaceSpecifier", ...args); } function PrivateName(...args) { return (0, _builder.default)("PrivateName", ...args); } function BigIntLiteral(...args) { return (0, _builder.default)("BigIntLiteral", ...args); } function TSParameterProperty(...args) { return (0, _builder.default)("TSParameterProperty", ...args); } function TSDeclareFunction(...args) { return (0, _builder.default)("TSDeclareFunction", ...args); } function TSDeclareMethod(...args) { return (0, _builder.default)("TSDeclareMethod", ...args); } function TSQualifiedName(...args) { return (0, _builder.default)("TSQualifiedName", ...args); } function TSCallSignatureDeclaration(...args) { return (0, _builder.default)("TSCallSignatureDeclaration", ...args); } function TSConstructSignatureDeclaration(...args) { return (0, _builder.default)("TSConstructSignatureDeclaration", ...args); } function TSPropertySignature(...args) { return (0, _builder.default)("TSPropertySignature", ...args); } function TSMethodSignature(...args) { return (0, _builder.default)("TSMethodSignature", ...args); } function TSIndexSignature(...args) { return (0, _builder.default)("TSIndexSignature", ...args); } function TSAnyKeyword(...args) { return (0, _builder.default)("TSAnyKeyword", ...args); } function TSNumberKeyword(...args) { return (0, _builder.default)("TSNumberKeyword", ...args); } function TSObjectKeyword(...args) { return (0, _builder.default)("TSObjectKeyword", ...args); } function TSBooleanKeyword(...args) { return (0, _builder.default)("TSBooleanKeyword", ...args); } function TSStringKeyword(...args) { return (0, _builder.default)("TSStringKeyword", ...args); } function TSSymbolKeyword(...args) { return (0, _builder.default)("TSSymbolKeyword", ...args); } function TSVoidKeyword(...args) { return (0, _builder.default)("TSVoidKeyword", ...args); } function TSUndefinedKeyword(...args) { return (0, _builder.default)("TSUndefinedKeyword", ...args); } function TSNullKeyword(...args) { return (0, _builder.default)("TSNullKeyword", ...args); } function TSNeverKeyword(...args) { return (0, _builder.default)("TSNeverKeyword", ...args); } function TSThisType(...args) { return (0, _builder.default)("TSThisType", ...args); } function TSFunctionType(...args) { return (0, _builder.default)("TSFunctionType", ...args); } function TSConstructorType(...args) { return (0, _builder.default)("TSConstructorType", ...args); } function TSTypeReference(...args) { return (0, _builder.default)("TSTypeReference", ...args); } function TSTypePredicate(...args) { return (0, _builder.default)("TSTypePredicate", ...args); } function TSTypeQuery(...args) { return (0, _builder.default)("TSTypeQuery", ...args); } function TSTypeLiteral(...args) { return (0, _builder.default)("TSTypeLiteral", ...args); } function TSArrayType(...args) { return (0, _builder.default)("TSArrayType", ...args); } function TSTupleType(...args) { return (0, _builder.default)("TSTupleType", ...args); } function TSUnionType(...args) { return (0, _builder.default)("TSUnionType", ...args); } function TSIntersectionType(...args) { return (0, _builder.default)("TSIntersectionType", ...args); } function TSConditionalType(...args) { return (0, _builder.default)("TSConditionalType", ...args); } function TSInferType(...args) { return (0, _builder.default)("TSInferType", ...args); } function TSParenthesizedType(...args) { return (0, _builder.default)("TSParenthesizedType", ...args); } function TSTypeOperator(...args) { return (0, _builder.default)("TSTypeOperator", ...args); } function TSIndexedAccessType(...args) { return (0, _builder.default)("TSIndexedAccessType", ...args); } function TSMappedType(...args) { return (0, _builder.default)("TSMappedType", ...args); } function TSLiteralType(...args) { return (0, _builder.default)("TSLiteralType", ...args); } function TSExpressionWithTypeArguments(...args) { return (0, _builder.default)("TSExpressionWithTypeArguments", ...args); } function TSInterfaceDeclaration(...args) { return (0, _builder.default)("TSInterfaceDeclaration", ...args); } function TSInterfaceBody(...args) { return (0, _builder.default)("TSInterfaceBody", ...args); } function TSTypeAliasDeclaration(...args) { return (0, _builder.default)("TSTypeAliasDeclaration", ...args); } function TSAsExpression(...args) { return (0, _builder.default)("TSAsExpression", ...args); } function TSTypeAssertion(...args) { return (0, _builder.default)("TSTypeAssertion", ...args); } function TSEnumDeclaration(...args) { return (0, _builder.default)("TSEnumDeclaration", ...args); } function TSEnumMember(...args) { return (0, _builder.default)("TSEnumMember", ...args); } function TSModuleDeclaration(...args) { return (0, _builder.default)("TSModuleDeclaration", ...args); } function TSModuleBlock(...args) { return (0, _builder.default)("TSModuleBlock", ...args); } function TSImportEqualsDeclaration(...args) { return (0, _builder.default)("TSImportEqualsDeclaration", ...args); } function TSExternalModuleReference(...args) { return (0, _builder.default)("TSExternalModuleReference", ...args); } function TSNonNullExpression(...args) { return (0, _builder.default)("TSNonNullExpression", ...args); } function TSExportAssignment(...args) { return (0, _builder.default)("TSExportAssignment", ...args); } function TSNamespaceExportDeclaration(...args) { return (0, _builder.default)("TSNamespaceExportDeclaration", ...args); } function TSTypeAnnotation(...args) { return (0, _builder.default)("TSTypeAnnotation", ...args); } function TSTypeParameterInstantiation(...args) { return (0, _builder.default)("TSTypeParameterInstantiation", ...args); } function TSTypeParameterDeclaration(...args) { return (0, _builder.default)("TSTypeParameterDeclaration", ...args); } function TSTypeParameter(...args) { return (0, _builder.default)("TSTypeParameter", ...args); } function NumberLiteral(...args) { console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); return NumberLiteral("NumberLiteral", ...args); } function RegexLiteral(...args) { console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); return RegexLiteral("RegexLiteral", ...args); } function RestProperty(...args) { console.trace("The node type RestProperty has been renamed to RestElement"); return RestProperty("RestProperty", ...args); } function SpreadProperty(...args) { console.trace("The node type SpreadProperty has been renamed to SpreadElement"); return SpreadProperty("SpreadProperty", ...args); } /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__(461)('wks'); var uid = __webpack_require__(203); var Symbol = __webpack_require__(68).Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isValue = __webpack_require__(118); module.exports = function (value) { if (!isValue(value)) throw new TypeError("Cannot use null or undefined"); return value; }; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var list = __webpack_require__(40).list; module.exports = { /** * Throw special error, to tell beniary, * that this error is from Autoprefixer. */ error: function error(text) { var err = new Error(text); err.autoprefixer = true; throw err; }, /** * Return array, that doesn’t contain duplicates. */ uniq: function uniq(array) { var filtered = []; for (var _iterator = array, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var i = _ref; if (filtered.indexOf(i) === -1) { filtered.push(i); } } return filtered; }, /** * Return "-webkit-" on "-webkit- old" */ removeNote: function removeNote(string) { if (string.indexOf(' ') === -1) { return string; } return string.split(' ')[0]; }, /** * Escape RegExp symbols */ escapeRegexp: function escapeRegexp(string) { return string.replace(/[.?*+\^\$\[\]\\(){}|\-]/g, '\\$&'); }, /** * Return regexp to check, that CSS string contain word */ regexp: function regexp(word) { var escape = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; if (escape) { word = this.escapeRegexp(word); } return new RegExp('(^|[\\s,(])(' + word + '($|[\\s(,]))', 'gi'); }, /** * Change comma list */ editList: function editList(value, callback) { var origin = list.comma(value); var changed = callback(origin, []); if (origin === changed) { return value; } var join = value.match(/,\s*/); join = join ? join[0] : ', '; return changed.join(join); } }; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } var Prefixer = __webpack_require__(150); var OldValue = __webpack_require__(151); var utils = __webpack_require__(47); var vendor = __webpack_require__(40).vendor; var Value = function (_Prefixer) { _inherits(Value, _Prefixer); function Value() { _classCallCheck(this, Value); return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments)); } /** * Clone decl for each prefixed values */ Value.save = function save(prefixes, decl) { var _this2 = this; var prop = decl.prop; var result = []; var _loop = function _loop(prefix) { var value = decl._autoprefixerValues[prefix]; if (value === decl.value) { return 'continue'; } var item = void 0; var propPrefix = vendor.prefix(prop); if (propPrefix === '-pie-') { return 'continue'; } if (propPrefix === prefix) { item = decl.value = value; result.push(item); return 'continue'; } var prefixed = prefixes.prefixed(prop, prefix); var rule = decl.parent; if (!rule.every(function (i) { return i.prop !== prefixed; })) { result.push(item); return 'continue'; } var trimmed = value.replace(/\s+/, ' '); var already = rule.some(function (i) { return i.prop === decl.prop && i.value.replace(/\s+/, ' ') === trimmed; }); if (already) { result.push(item); return 'continue'; } var cloned = _this2.clone(decl, { value: value }); item = decl.parent.insertBefore(decl, cloned); result.push(item); }; for (var prefix in decl._autoprefixerValues) { var _ret = _loop(prefix); if (_ret === 'continue') continue; } return result; }; /** * Is declaration need to be prefixed */ Value.prototype.check = function check(decl) { var value = decl.value; if (value.indexOf(this.name) === -1) { return false; } return !!value.match(this.regexp()); }; /** * Lazy regexp loading */ Value.prototype.regexp = function regexp() { return this.regexpCache || (this.regexpCache = utils.regexp(this.name)); }; /** * Add prefix to values in string */ Value.prototype.replace = function replace(string, prefix) { return string.replace(this.regexp(), '$1' + prefix + '$2'); }; /** * Get value with comments if it was not changed */ Value.prototype.value = function value(decl) { if (decl.raws.value && decl.raws.value.value === decl.value) { return decl.raws.value.raw; } else { return decl.value; } }; /** * Save values with next prefixed token */ Value.prototype.add = function add(decl, prefix) { if (!decl._autoprefixerValues) { decl._autoprefixerValues = {}; } var value = decl._autoprefixerValues[prefix] || this.value(decl); var before = void 0; do { before = value; value = this.replace(value, prefix); if (value === false) return; } while (value !== before); decl._autoprefixerValues[prefix] = value; }; /** * Return function to fast find prefixed value */ Value.prototype.old = function old(prefix) { return new OldValue(this.name, prefix + this.name); }; return Value; }(Prefixer); module.exports = Value; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(59); var core = __webpack_require__(28); var ctx = __webpack_require__(121); var hide = __webpack_require__(85); var has = __webpack_require__(87); var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var IS_WRAP = type & $export.W; var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); var expProto = exports[PROTOTYPE]; var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; var key, own, out; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; if (own && has(exports, key)) continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function (C) { var F = function (a, b, c) { if (this instanceof C) { switch (arguments.length) { case 0: return new C(); case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if (IS_PROTO) { (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), /* 50 */ /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__(307)('wks'); var uid = __webpack_require__(217); var Symbol = __webpack_require__(59).Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MakeConstructor = MakeConstructor; exports.Construct = Construct; exports.SpeciesConstructor = SpeciesConstructor; exports.MakeClassConstructor = MakeClassConstructor; exports.ConstructorMethod = ConstructorMethod; exports.NonConstructorMethodDefinitions = NonConstructorMethodDefinitions; var _index = __webpack_require__(0); var _is = __webpack_require__(16); var _get = __webpack_require__(19); var _has = __webpack_require__(42); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // ECMA262 9.2.8 function MakeConstructor(realm, F, writablePrototype, prototype) { // 1. Assert: F is an ECMAScript function object. (0, _invariant2.default)(F instanceof _index.ECMAScriptSourceFunctionValue, "expected function value"); // 2. Assert: F has a [[Construct]] internal method. (0, _invariant2.default)(F.$Construct !== undefined, "expected construct internal method"); // 3. Assert: F is an extensible object that does not have a prototype own property. (0, _invariant2.default)(F.getExtensible(), "expected extensible object that doesn't have prototype own property"); // 4. If the writablePrototype argument was not provided, let writablePrototype be true. if (writablePrototype === null || writablePrototype === undefined) { writablePrototype = true; } // 5. If the prototype argument was not provided, then if (!prototype) { // a. Let prototype be ObjectCreate(%ObjectPrototype%). prototype = _singletons.Create.ObjectCreate(realm, realm.intrinsics.ObjectPrototype); prototype.originalConstructor = F; // b. Perform ! DefinePropertyOrThrow(prototype, "constructor", PropertyDescriptor{[[Value]]: F, [[Writable]]: writablePrototype, [[Enumerable]]: false, [[Configurable]]: true }). _singletons.Properties.DefinePropertyOrThrow(realm, prototype, "constructor", { value: F, writable: writablePrototype, enumerable: false, configurable: true }); } // 6. Perform ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor{[[Value]]: prototype, [[Writable]]: writablePrototype, [[Enumerable]]: false, [[Configurable]]: false}). _singletons.Properties.DefinePropertyOrThrow(realm, F, "prototype", { value: prototype, writable: writablePrototype, enumerable: false, configurable: false }); // 7. Return NormalCompletion(undefined). return realm.intrinsics.undefined; } // ECMA262 7.3.13 /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function Construct(realm, F, argumentsList, newTarget) { // If newTarget was not passed, let newTarget be F. if (!newTarget) newTarget = F; // If argumentsList was not passed, let argumentsList be a new empty List. if (!argumentsList) argumentsList = []; // Assert: IsConstructor(F) is true. (0, _invariant2.default)((0, _is.IsConstructor)(realm, F), "expected constructor"); // Assert: IsConstructor(newTarget) is true. (0, _invariant2.default)((0, _is.IsConstructor)(realm, newTarget), "expected constructor"); // Return ? F.[[Construct]](argumentsList, newTarget). (0, _invariant2.default)(F.$Construct !== undefined, "no construct method on realm value"); return F.$Construct(argumentsList, newTarget); } // ECMA262 7.3.20 function SpeciesConstructor(realm, O, defaultConstructor) { // 1. Assert: Type(O) is Object. (0, _invariant2.default)(O instanceof _index.ObjectValue, "Type(O) is Object"); // 2. Let C be ? Get(O, "constructor"). let C = (0, _get.Get)(realm, O, "constructor"); // 3. If C is undefined, return defaultConstructor. if (C instanceof _index.UndefinedValue) return defaultConstructor; // 4. If Type(C) is not Object, throw a TypeError exception. if (C.mightNotBeObject()) { if (C.mightBeObject()) C.throwIfNotConcrete(); throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(C) is not an object"); } (0, _invariant2.default)(C instanceof _index.ObjectValue || C instanceof _index.AbstractObjectValue); // 5. Let S be ? Get(C, @@species). let S = (0, _get.Get)(realm, C, realm.intrinsics.SymbolSpecies); // 6. If S is either undefined or null, return defaultConstructor. if ((0, _has.HasSomeCompatibleType)(S, _index.UndefinedValue, _index.NullValue)) return defaultConstructor; // 7. If IsConstructor(S) is true, return S. if ((0, _is.IsConstructor)(realm, S)) { (0, _invariant2.default)(S instanceof _index.ObjectValue); return S; } // 8. Throw a TypeError exception. throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Throw a TypeError exception"); } // ECMA 9.2.9 function MakeClassConstructor(realm, F) { // 1. Assert: F is an ECMAScript function object. (0, _invariant2.default)(F instanceof _index.ECMAScriptSourceFunctionValue, "expected function value"); // 2. Assert: F’s [[FunctionKind]] internal slot is "normal". (0, _invariant2.default)(F.$FunctionKind === "normal"); // 3. Set F’s [[FunctionKind]] internal slot to "classConstructor". F.$FunctionKind = "classConstructor"; // 4. Return NormalCompletion(undefined). return realm.intrinsics.undefined; } // ECMA 14.5.3 function ConstructorMethod(realm, ClassElementList) { let ClassElement; // ClassElementList : ClassElement if (ClassElementList.length === 1) { ClassElement = ClassElementList[0]; // 1. If ClassElement is the production ClassElement : ; , return empty. // It looks like Babel parses out ClassElements that are only ; // 2. If IsStatic of ClassElement is true, return empty. if ((0, _is.IsStatic)(ClassElement)) { return realm.intrinsics.empty; } // 3. If PropName of ClassElement is not "constructor", return empty. if (ClassElement.key.name !== "constructor") { return realm.intrinsics.empty; } // 4. Return ClassElement. return ClassElement; } else { // ClassElementList : ClassElementList ClassElement // 1. Let head be ConstructorMethod of ClassElementList. let head = ConstructorMethod(realm, ClassElementList.slice(0, -1)); // 2. If head is not empty, return head. if (!(head instanceof _index.EmptyValue)) { return head; } ClassElement = ClassElementList[ClassElementList.length - 1]; // 3. If ClassElement is the production ClassElement : ; , return empty. // It looks like Babel parses out ClassElements that are only ; // 4. If IsStatic of ClassElement is true, return empty. if ((0, _is.IsStatic)(ClassElement)) { return realm.intrinsics.empty; } // If PropName of ClassElement is not "constructor", return empty. if (ClassElement.key.name !== "constructor") { return realm.intrinsics.empty; } // Return ClassElement. return ClassElement; } } // ECMA 14.5.10 function NonConstructorMethodDefinitions(realm, ClassElementList) { let ClassElement; // ClassElementList : ClassElement if (ClassElementList.length === 1) { ClassElement = ClassElementList[0]; // If ClassElement is the production ClassElement : ; , return a new empty List. // If IsStatic of ClassElement is false and PropName of ClassElement is "constructor", return a new empty List. if (!(0, _is.IsStatic)(ClassElement) && ClassElement.key.name === "constructor") { return []; } // Return a List containing ClassElement. return [ClassElement]; } else { // ClassElementList : ClassElementList ClassElement ClassElement = ClassElementList[ClassElementList.length - 1]; // Let list be NonConstructorMethodDefinitions of ClassElementList. let list = NonConstructorMethodDefinitions(realm, ClassElementList.slice(0, -1)); // If ClassElement is the production ClassElement : ; , return list. // If IsStatic of ClassElement is false and PropName of ClassElement is "constructor", return list. if (!(0, _is.IsStatic)(ClassElement) && ClassElement.key.name === "constructor") { return list; } // Append ClassElement to the end of list. list.push(ClassElement); // Return list. return list; } } //# sourceMappingURL=construct.js.map /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = buildExpressionTemplate; var _babelTemplate = __webpack_require__(624); var _babelTemplate2 = _interopRequireDefault(_babelTemplate); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function buildExpressionTemplate(code) { let template; return preludeGenerator => obj => { if (template === undefined) template = (0, _babelTemplate2.default)(code); if (preludeGenerator !== undefined && code.includes("global")) obj = Object.assign({ global: preludeGenerator.memoizeReference("global") }, obj); let result = template(obj).expression; (0, _invariant2.default)(result !== undefined, "Code does not represent an expression: " + code); return result; }; } //# sourceMappingURL=builder.js.map /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SerializerStatistics = exports.ReactStatistics = exports.TimingStatistics = exports.BodyReference = undefined; exports.AreSameResidualBinding = AreSameResidualBinding; var _environment = __webpack_require__(12); var _index = __webpack_require__(0); var _abstract = __webpack_require__(29); var _realm = __webpack_require__(11); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // TODO: add type for additional functions. function AreSameResidualBinding(realm, x, y) { if (x.serializedValue === y.serializedValue) return true; if (x.value && x.value === y.value) return true; if (x.value instanceof _index.ConcreteValue && y.value instanceof _index.ConcreteValue) { return (0, _abstract.SameValue)(realm, x.value, y.value); } return false; } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ class BodyReference { constructor(body, index) { (0, _invariant2.default)(index >= 0); this.body = body; this.index = index; } isNotEarlierThan(other) { return this.body === other.body && this.index >= other.index; } } exports.BodyReference = BodyReference; class TimingStatistics { constructor() { this.totalTime = 0; this.globalCodeTime = 0; this.initializeMoreModulesTime = 0; this.deepTraversalTime = 0; this.referenceCountsTime = 0; this.serializePassTime = 0; } } exports.TimingStatistics = TimingStatistics; class ReactStatistics { constructor() { this.optimizedTrees = 0; this.inlinedComponents = 0; this.evaluatedRootNodes = []; this.componentsEvaluated = 0; } } exports.ReactStatistics = ReactStatistics; class SerializerStatistics { constructor() { this.objects = 0; this.objectProperties = 0; this.functions = 0; this.functionClones = 0; this.referentialized = 0; this.valueIds = 0; this.valuesInlined = 0; this.delayedValues = 0; this.acceleratedModules = 0; this.delayedModules = 0; } log() { console.log(`=== serialization statistics`); console.log(`${this.objects} objects with ${this.objectProperties} properties`); console.log(`${this.functions} functions plus ${this.functionClones} clones due to captured variables; ${this.referentialized} captured mutable variables`); console.log(`${this.valueIds} eager and ${this.delayedValues} delayed value ids generated, and ${this.valuesInlined} values inlined`); console.log(`${this.acceleratedModules} accelerated and ${this.delayedModules} delayed modules.`); } } exports.SerializerStatistics = SerializerStatistics; //# sourceMappingURL=types.js.map /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(352); /** 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')(); module.exports = root; /***/ }), /* 56 */ /***/ (function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "VISITOR_KEYS", { enumerable: true, get: function () { return _utils.VISITOR_KEYS; } }); Object.defineProperty(exports, "ALIAS_KEYS", { enumerable: true, get: function () { return _utils.ALIAS_KEYS; } }); Object.defineProperty(exports, "FLIPPED_ALIAS_KEYS", { enumerable: true, get: function () { return _utils.FLIPPED_ALIAS_KEYS; } }); Object.defineProperty(exports, "NODE_FIELDS", { enumerable: true, get: function () { return _utils.NODE_FIELDS; } }); Object.defineProperty(exports, "BUILDER_KEYS", { enumerable: true, get: function () { return _utils.BUILDER_KEYS; } }); Object.defineProperty(exports, "DEPRECATED_KEYS", { enumerable: true, get: function () { return _utils.DEPRECATED_KEYS; } }); exports.TYPES = void 0; function _toFastProperties() { const data = _interopRequireDefault(__webpack_require__(789)); _toFastProperties = function () { return data; }; return data; } __webpack_require__(249); __webpack_require__(252); __webpack_require__(792); __webpack_require__(793); __webpack_require__(794); __webpack_require__(795); __webpack_require__(796); var _utils = __webpack_require__(79); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (0, _toFastProperties().default)(_utils.VISITOR_KEYS); (0, _toFastProperties().default)(_utils.ALIAS_KEYS); (0, _toFastProperties().default)(_utils.FLIPPED_ALIAS_KEYS); (0, _toFastProperties().default)(_utils.NODE_FIELDS); (0, _toFastProperties().default)(_utils.BUILDER_KEYS); (0, _toFastProperties().default)(_utils.DEPRECATED_KEYS); const TYPES = Object.keys(_utils.VISITOR_KEYS).concat(Object.keys(_utils.FLIPPED_ALIAS_KEYS)).concat(Object.keys(_utils.DEPRECATED_KEYS)); exports.TYPES = TYPES; /***/ }), /* 58 */ /***/ (function(module, exports) { /*! * Chai - flag utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ /** * ### .flag(object, key, [value]) * * Get or set a flag value on an object. If a * value is provided it will be set, else it will * return the currently set value or `undefined` if * the value is not set. * * utils.flag(this, 'foo', 'bar'); // setter * utils.flag(this, 'foo'); // getter, returns `bar` * * @param {Object} object constructed Assertion * @param {String} key * @param {Mixed} value (optional) * @namespace Utils * @name flag * @api private */ module.exports = function flag(obj, key, value) { var flags = obj.__flags || (obj.__flags = Object.create(null)); if (arguments.length === 3) { flags[key] = value; } else { return flags[key]; } }; /***/ }), /* 59 */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.visitors = exports.Hub = exports.Scope = exports.NodePath = undefined; var _getIterator2 = __webpack_require__(21); var _getIterator3 = _interopRequireDefault(_getIterator2); var _path = __webpack_require__(103); Object.defineProperty(exports, "NodePath", { enumerable: true, get: function get() { return _interopRequireDefault(_path).default; } }); var _scope = __webpack_require__(323); Object.defineProperty(exports, "Scope", { enumerable: true, get: function get() { return _interopRequireDefault(_scope).default; } }); var _hub = __webpack_require__(622); Object.defineProperty(exports, "Hub", { enumerable: true, get: function get() { return _interopRequireDefault(_hub).default; } }); exports.default = traverse; var _context = __webpack_require__(1960); var _context2 = _interopRequireDefault(_context); var _visitors = __webpack_require__(1961); var visitors = _interopRequireWildcard(_visitors); var _babelMessages = __webpack_require__(223); var messages = _interopRequireWildcard(_babelMessages); var _includes = __webpack_require__(107); var _includes2 = _interopRequireDefault(_includes); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); var _cache = __webpack_require__(226); var cache = _interopRequireWildcard(_cache); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.visitors = visitors; function traverse(parent, opts, scope, state, parentPath) { if (!parent) return; if (!opts) opts = {}; if (!opts.noScope && !scope) { if (parent.type !== "Program" && parent.type !== "File") { throw new Error(messages.get("traverseNeedsParent", parent.type)); } } visitors.explode(opts); traverse.node(parent, opts, scope, state, parentPath); } traverse.visitors = visitors; traverse.verify = visitors.verify; traverse.explode = visitors.explode; traverse.NodePath = __webpack_require__(103); traverse.Scope = __webpack_require__(323); traverse.Hub = __webpack_require__(622); traverse.cheap = function (node, enter) { return t.traverseFast(node, enter); }; traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { var keys = t.VISITOR_KEYS[node.type]; if (!keys) return; var context = new _context2.default(scope, opts, state, parentPath); for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var key = _ref; if (skipKeys && skipKeys[key]) continue; if (context.visit(node, key)) return; } }; traverse.clearNode = function (node, opts) { t.removeProperties(node, opts); cache.path.delete(node); }; traverse.removeProperties = function (tree, opts) { t.traverseFast(tree, traverse.clearNode, opts); return tree; }; function hasBlacklistedType(path, state) { if (path.node.type === state.type) { state.has = true; path.stop(); } } traverse.hasType = function (tree, scope, type, blacklistTypes) { if ((0, _includes2.default)(blacklistTypes, tree.type)) return false; if (tree.type === type) return true; var state = { has: false, type: type }; traverse(tree, { blacklist: blacklistTypes, enter: hasBlacklistedType }, scope, state); return state.has; }; traverse.clearCache = function () { cache.clear(); }; traverse.clearCache.clearPath = cache.clearPath; traverse.clearCache.clearScope = cache.clearScope; traverse.copyCache = function (source, destination) { if (cache.path.has(source)) { cache.path.set(destination, cache.path.get(source)); } }; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Logger = undefined; var _realm = __webpack_require__(11); var _errors = __webpack_require__(6); var _index = __webpack_require__(5); var _completions = __webpack_require__(3); var _index2 = __webpack_require__(0); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class Logger { constructor(realm, internalDebug) { this.realm = realm; this._hasErrors = false; this.internalDebug = internalDebug; } // Wraps a query that might potentially execute user code. tryQuery(f, defaultValue) { let realm = this.realm; let context = new _realm.ExecutionContext(); context.isStrict = realm.isStrict; let env = realm.$GlobalEnv; context.lexicalEnvironment = env; context.variableEnvironment = env; context.realm = realm; realm.pushContext(context); // We use partial evaluation so that we can throw away any state mutations let oldErrorHandler = realm.errorHandler; realm.errorHandler = d => { if (d.severity === "Information" || d.severity === "Warning") return "Recover"; return "Fail"; }; try { let result; let effects = realm.evaluateForEffects(() => { try { result = f(); } catch (e) { if (e instanceof _completions.Completion) { result = defaultValue; } else if (e instanceof _errors.FatalError) { result = defaultValue; } else { throw e; } } return realm.intrinsics.undefined; }); (0, _invariant2.default)(effects[0] === realm.intrinsics.undefined); return result; } finally { realm.errorHandler = oldErrorHandler; realm.popContext(context); } } logCompletion(res) { let realm = this.realm; let value = res.value; if (this.internalDebug) console.error(`=== ${res.constructor.name} ===`); if (this.tryQuery(() => value instanceof _index2.ObjectValue && (0, _index.InstanceofOperator)(realm, value, realm.intrinsics.Error), false)) { let object = value; try { let err = new _errors.FatalError(this.tryQuery(() => _singletons.To.ToStringPartial(realm, (0, _index.Get)(realm, object, "message")), "(unknown message)")); err.stack = this.tryQuery(() => _singletons.To.ToStringPartial(realm, (0, _index.Get)(realm, object, "stack")), "(unknown stack)"); console.error(err.message); console.error(err.stack); if (this.internalDebug && res instanceof _completions.ThrowCompletion) console.error(res.nativeStack); } catch (err) { let message = object.properties.get("message"); console.error(message && message.descriptor && message.descriptor.value instanceof _index2.StringValue ? message.descriptor.value.value : "(no message available)"); console.error(err.stack); if (object.$ErrorData) { console.error(object.$ErrorData.contextStack); } } } else { try { value = _singletons.To.ToStringPartial(realm, value); } catch (err) { value = err.message; } console.error(value); if (this.internalDebug && res instanceof _completions.ThrowCompletion) console.error(res.nativeStack); } this._hasErrors = true; } logError(value, message) { this._log(value, message, "RecoverableError"); this._hasErrors = true; } logWarning(value, message) { this._log(value, message, "Warning"); } _log(value, message, severity) { let loc = value.expressionLocation; if (value.intrinsicName) { message = `${message}\nintrinsic name: ${value.intrinsicName}`; } let diagnostic = new _errors.CompilerDiagnostic(message, loc, "PP9000", severity); if (this.realm.handleError(diagnostic) === "Fail") throw new _errors.FatalError(); } hasErrors() { return this._hasErrors; } } exports.Logger = Logger; /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ //# sourceMappingURL=logger.js.map /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (realm) { return build("Error", realm, false); }; exports.describeLocation = describeLocation; exports.build = build; var _index = __webpack_require__(0); var _index2 = __webpack_require__(5); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function describeLocation(realm, callerFn, env, loc) { let locString = ""; let displayName = ""; if (callerFn) { if (callerFn instanceof _index.NativeFunctionValue) { locString = "native"; } let name = callerFn.$Get("name", callerFn); if (!name.mightBeUndefined()) displayName = _singletons.To.ToStringPartial(realm, name);else name.throwIfNotConcrete(); if (env && env.$NewTarget) displayName = `new ${displayName}`; } if (!locString) { if (loc) { locString = `${loc.start.line}:${loc.start.column + 1}`; if (loc.source) locString = `${loc.source}:${locString}`; } else { locString = (loc ? loc.source : undefined) || "unknown"; if (!displayName) return undefined; } } if (displayName) { return `at ${displayName} (${locString})`; } else { return `at ${locString}`; } } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function buildStack(realm, context) { (0, _invariant2.default)(context.$ErrorData); let stack = context.$ErrorData.contextStack; if (!stack) return realm.intrinsics.undefined; let lines = []; let header = ""; header += _singletons.To.ToStringPartial(realm, (0, _index2.Get)(realm, context, "name")); let msg = (0, _index2.Get)(realm, context, "message"); if (!msg.mightBeUndefined()) { msg = _singletons.To.ToStringPartial(realm, msg); if (msg) header += `: ${msg}`; } else { msg.throwIfNotConcrete(); } for (let executionContext of stack.reverse()) { let caller = executionContext.caller; let locString = describeLocation(realm, caller ? caller.function : undefined, caller ? caller.lexicalEnvironment : undefined, executionContext.loc); if (locString !== undefined) lines.push(locString); } return new _index.StringValue(realm, `${header}\n ${lines.join("\n ")}`); } function build(name, realm, inheritError = true) { let func = new _index.NativeFunctionValue(realm, name, name, 1, (context, [message], argLength, NewTarget) => { // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. let newTarget = NewTarget || func; // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%ErrorPrototype%", « [[ErrorData]] »). let O = _singletons.Create.OrdinaryCreateFromConstructor(realm, newTarget, `${name}Prototype`, { $ErrorData: undefined }); O.$ErrorData = { contextStack: realm.contextStack.slice(1), locationData: undefined }; // Build a text description of the stack. let stackDesc = { value: buildStack(realm, O), enumerable: false, configurable: true, writable: true }; _singletons.Properties.DefinePropertyOrThrow(realm, O, "stack", stackDesc); // 3. If message is not undefined, then if (!message.mightBeUndefined()) { // a. Let msg be ? ToString(message). let msg = message.getType() === _index.StringValue ? message : _singletons.To.ToStringValue(realm, message); // b. Let msgDesc be the PropertyDescriptor{[[Value]]: msg, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true}. let msgDesc = { value: msg, writable: true, enumerable: false, configurable: true }; // c. Perform ! DefinePropertyOrThrow(O, "message", msgDesc). _singletons.Properties.DefinePropertyOrThrow(realm, O, "message", msgDesc); } else { message.throwIfNotConcrete(); } // 4. Return O. return O; }); if (inheritError) { func.$Prototype = realm.intrinsics.Error; } return func; } //# sourceMappingURL=Error.js.map /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (realm) { let func = new _index.NativeFunctionValue(realm, "TypedArray", "TypedArray", 0, context => { // 1. Throw a TypeError exception. throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "TypedArray"); }); // ECMA262 22.2.2.1 func.defineNativeMethod("from", 1, (context, [source, mapfn, thisArg]) => { // 1. Let C be the this value. let C = context; // 2. If IsConstructor(C) is false, throw a TypeError exception. if ((0, _is.IsConstructor)(realm, C) === false) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsConstructor(C) is false"); } (0, _invariant2.default)(C instanceof _index.ObjectValue); let mapping; // 3. If mapfn was supplied and mapfn is not undefined, then if (mapfn !== undefined && !mapfn.mightBeUndefined()) { // a. If IsCallable(mapfn) is false, throw a TypeError exception. if ((0, _is.IsCallable)(realm, mapfn) === false) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsConstructor(C) is false"); } // b. Let mapping be true. mapping = true; } else { // 4. Else, let mapping be false. mapfn === undefined || mapfn.throwIfNotConcrete(); mapping = false; } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. let T = thisArg !== undefined ? thisArg : realm.intrinsics.undefined; // 6. Let usingIterator be ? GetMethod(source, @@iterator). let usingIterator = (0, _get.GetMethod)(realm, source, realm.intrinsics.SymbolIterator); // 7. If usingIterator is not undefined, then if (!(usingIterator instanceof _index.UndefinedValue)) { // a. Let values be ? IterableToList(source, usingIterator). let values = (0, _iterator.IterableToList)(realm, source, usingIterator); // b. Let len be the number of elements in values. let len = values.length; // c. Let targetObj be ? TypedArrayCreate(C, «len»). let targetObj = (0, _typedarray.TypedArrayCreate)(realm, C, [new _index.NumberValue(realm, len)]); // d. Let k be 0. let k = 0; // e. Repeat, while k < len while (k < len) { // i. Let Pk be ! ToString(k). let Pk = _singletons.To.ToString(realm, new _index.NumberValue(realm, k)); // ii. Let kValue be the first element of values and remove that element from values. let kValue = values.shift(); let mappedValue; // iii. If mapping is true, then if (mapping === true) { // 1. Let mappedValue be ? Call(mapfn, T, « kValue, k »). mappedValue = (0, _call.Call)(realm, mapfn, T, [kValue, new _index.NumberValue(realm, k)]); } else { // iv. Else, let mappedValue be kValue. mappedValue = kValue; } // v. Perform ? Set(targetObj, Pk, mappedValue, true). _singletons.Properties.Set(realm, targetObj, Pk, mappedValue, true); // vi. Increase k by 1. k = k + 1; } // f. Assert: values is now an empty List. (0, _invariant2.default)(values.length === 0, "values is not an empty List"); // g. Return targetObj. return targetObj; } // 8. NOTE: source is not an Iterable so assume it is already an array-like object. // 9. Let arrayLike be ! ToObject(source). let arrayLike = _singletons.To.ToObjectPartial(realm, source); // 10. Let len be ? ToLength(? Get(arrayLike, "length")). let len = _singletons.To.ToLength(realm, (0, _get.Get)(realm, arrayLike, "length")); // 11. Let targetObj be ? TypedArrayCreate(C, « len »). let targetObj = (0, _typedarray.TypedArrayCreate)(realm, C, [new _index.NumberValue(realm, len)]); // 12. Let k be 0. let k = 0; // 13. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = _singletons.To.ToString(realm, new _index.NumberValue(realm, k)); // b. Let kValue be ? Get(arrayLike, Pk). let kValue = (0, _get.Get)(realm, arrayLike, Pk); let mappedValue; // c. If mapping is true, then if (mapping === true) { // i. Let mappedValue be ? Call(mapfn, T, « kValue, k »). mappedValue = (0, _call.Call)(realm, mapfn, T, [kValue, new _index.NumberValue(realm, k)]); } else { // d. Else, let mappedValue be kValue. mappedValue = kValue; } // e. Perform ? Set(targetObj, Pk, mappedValue, true). _singletons.Properties.Set(realm, targetObj, Pk, mappedValue, true); // f. Increase k by 1. k = k + 1; } // 14. Return targetObj. return targetObj; }); // ECMA262 22.2.2.2 func.defineNativeMethod("of", 0, (context, items, argCount) => { // 1. Let len be the actual number of arguments passed to this function. let len = argCount; // 2. Let items be the List of arguments passed to this function. items; // 3. Let C be the this value. let C = context; // 4. If IsConstructor(C) is false, throw a TypeError exception. if ((0, _is.IsConstructor)(realm, C) === false) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsConstructor(C) is false"); } (0, _invariant2.default)(C instanceof _index.ObjectValue); // 5. Let newObj be ? TypedArrayCreate(C, « len »). let newObj = (0, _typedarray.TypedArrayCreate)(realm, C, [new _index.NumberValue(realm, len)]); // 6. Let k be 0. let k = 0; // 7. Repeat, while k < len while (k < len) { // a. Let kValue be items[k]. let kValue = items[k]; // b. Let Pk be ! ToString(k). let Pk = _singletons.To.ToString(realm, new _index.NumberValue(realm, k)); // c. Perform ? Set(newObj, Pk, kValue, true). _singletons.Properties.Set(realm, newObj, Pk, kValue, true); // d. Increase k by 1. k = k + 1; } // 8. Return newObj. return newObj; }); // ECMA262 22.2.2.4 func.defineNativeGetter(realm.intrinsics.SymbolSpecies, context => { // 1. Return the this value return context; }); return func; }; exports.build = build; var _types = __webpack_require__(322); var _index = __webpack_require__(0); var _typedarray = __webpack_require__(227); var _construct = __webpack_require__(52); var _get = __webpack_require__(19); var _singletons = __webpack_require__(2); var _iterator = __webpack_require__(100); var _is = __webpack_require__(16); var _call = __webpack_require__(30); var _arraybuffer = __webpack_require__(124); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // ECMA262 22.2 Table 50 /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function getConstructorName(type) { switch (type) { case "Float32": return "Float32Array"; case "Float64": return "Float64Array"; case "Int8": return "Int8Array"; case "Int16": return "Int16Array"; case "Int32": return "Int32Array"; case "Uint8": return "Uint8Array"; case "Uint16": return "Uint16Array"; case "Uint32": return "Uint32Array"; case "Uint8Clamped": return "Uint8ClampedArray"; default: (0, _invariant2.default)(false); } } function build(realm, type) { let func = new _index.NativeFunctionValue(realm, `${type}Array`, `${type}Array`, 3, (context, args, argCount, NewTarget) => { if (argCount === 0) { // ECMA262 22.2.4.1 // 1. If NewTarget is undefined, throw a TypeError exception. if (!NewTarget) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "NewTarget is undefined"); } // 2. Let constructorName be the String value of the Constructor Name value specified in Table 50 for this TypedArray constructor. let constructorName = getConstructorName(type); // 3. Return ? AllocateTypedArray(constructorName, NewTarget, "%TypedArrayPrototype%", 0). return (0, _typedarray.AllocateTypedArray)(realm, constructorName, NewTarget, `${type}ArrayPrototype`, 0); } else if (!(args[0] instanceof _index.ObjectValue)) { // ECMA262 22.2.4.2 let length = args[0].throwIfNotConcrete(); // 1. Assert: Type(length) is not Object. (0, _invariant2.default)(!(length instanceof _index.ObjectValue), "Type(length) is not Object"); // 2. If NewTarget is undefined, throw a TypeError exception. if (!NewTarget) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "NewTarget is undefined"); } // 3. Let elementLength be ? ToIndex(length). let elementLength = _singletons.To.ToIndexPartial(realm, length); // 4. Let constructorName be the String value of the Constructor Name value specified in Table 50 for this TypedArray constructor. let constructorName = getConstructorName(type); // 5. Return ? AllocateTypedArray(constructorName, NewTarget, "%TypedArrayPrototype%", elementLength). return (0, _typedarray.AllocateTypedArray)(realm, constructorName, NewTarget, `${type}ArrayPrototype`, elementLength); } else if ("$TypedArrayName" in args[0]) { // ECMA262 22.2.4.3 let typedArray = args[0].throwIfNotConcrete(); // 1. Assert: Type(typedArray) is Object and typedArray has a [[TypedArrayName]] internal slot. (0, _invariant2.default)(typedArray instanceof _index.ObjectValue && typeof typedArray.$TypedArrayName === "string"); // 2. If NewTarget is undefined, throw a TypeError exception. if (!NewTarget) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "NewTarget is undefined"); } // 3. Let constructorName be the String value of the Constructor Name value specified in Table 50 for this TypedArray constructor. let constructorName = getConstructorName(type); // 4. Let O be ? AllocateTypedArray(constructorName, NewTarget, "%TypedArrayPrototype%"). let O = (0, _typedarray.AllocateTypedArray)(realm, constructorName, NewTarget, `${type}ArrayPrototype`); // 5. Let srcArray be typedArray. let srcArray = typedArray; // 6. Let srcData be srcArray.[[ViewedArrayBuffer]]. let srcData = srcArray.$ViewedArrayBuffer; (0, _invariant2.default)(srcData); // 7. If IsDetachedBuffer(srcData) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, srcData) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(srcData) is true"); } // 8. Let constructorName be the String value of O.[[TypedArrayName]]. constructorName = O.$TypedArrayName; (0, _invariant2.default)(typeof constructorName === "string"); // 9. Let elementType be the String value of the Element Type value in Table 50 for constructorName. let elementType = _typedarray.ArrayElementType[constructorName]; // 10. Let elementLength be srcArray.[[ArrayLength]]. let elementLength = srcArray.$ArrayLength; (0, _invariant2.default)(typeof elementLength === "number"); // 11. Let srcName be the String value of srcArray.[[TypedArrayName]]. let srcName = srcArray.$TypedArrayName; (0, _invariant2.default)(typeof srcName === "string"); // 12. Let srcType be the String value of the Element Type value in Table 50 for srcName. let srcType = _typedarray.ArrayElementType[srcName]; // 13. Let srcElementSize be the Element Size value in Table 50 for srcName. let srcElementSize = _typedarray.ArrayElementSize[srcName]; // 14. Let srcByteOffset be srcArray.[[ByteOffset]]. let srcByteOffset = srcArray.$ByteOffset; (0, _invariant2.default)(typeof srcByteOffset === "number"); // 15. Let elementSize be the Element Size value in Table 50 for constructorName. let elementSize = _typedarray.ArrayElementSize[constructorName]; // 16. Let byteLength be elementSize × elementLength. let byteLength = elementSize * elementLength; let data; // 17. If SameValue(elementType, srcType) is true, then if (elementType === srcType) { // a. Let data be ? CloneArrayBuffer(srcData, srcByteOffset). data = (0, _arraybuffer.CloneArrayBuffer)(realm, srcData, srcByteOffset); } else { // 18. Else, // a. Let bufferConstructor be ? SpeciesConstructor(srcData, %ArrayBuffer%). let bufferConstructor = (0, _construct.SpeciesConstructor)(realm, srcData, realm.intrinsics.ArrayBuffer); // b. Let data be ? AllocateArrayBuffer(bufferConstructor, byteLength). data = (0, _arraybuffer.AllocateArrayBuffer)(realm, bufferConstructor, byteLength); // c. If IsDetachedBuffer(srcData) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, srcData) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(srcData) is true"); } // d. Let srcByteIndex be srcByteOffset. let srcByteIndex = srcByteOffset; // e. Let targetByteIndex be 0. let targetByteIndex = 0; // f. Let count be elementLength. let count = elementLength; // g. Repeat, while count > 0 while (count > 0) { // i. Let value be GetValueFromBuffer(srcData, srcByteIndex, srcType). let value = (0, _arraybuffer.GetValueFromBuffer)(realm, srcData, srcByteIndex, srcType); // ii. Perform SetValueInBuffer(data, targetByteIndex, elementType, value). (0, _arraybuffer.SetValueInBuffer)(realm, data, targetByteIndex, elementType, value.value); // iii. Set srcByteIndex to srcByteIndex + srcElementSize. srcByteIndex = srcByteIndex + srcElementSize; // iv. Set targetByteIndex to targetByteIndex + elementSize. targetByteIndex = targetByteIndex + elementSize; // v. Decrement count by 1. count -= 1; } } // 19. Set O.[[ViewedArrayBuffer]] to data. O.$ViewedArrayBuffer = data; // 20. Set O.[[ByteLength]] to byteLength. O.$ByteLength = byteLength; // 21. Set O.[[ByteOffset]] to 0. O.$ByteOffset = 0; // 22. Set O.[[ArrayLength]] to elementLength. O.$ArrayLength = elementLength; // 23. Return O. return O; } else if (!("$ArrayBufferData" in args[0]) && !("$TypedArrayName" in args[0])) { // ECMA262 22.2.4.4 let object = args[0].throwIfNotConcrete(); // 1. Assert: Type(object) is Object and object does not have either a [[TypedArrayName]] or an [[ArrayBufferData]] internal slot. (0, _invariant2.default)(object instanceof _index.ObjectValue && typeof object.$TypedArrayName && !object.$ArrayBufferData); // 2. If NewTarget is undefined, throw a TypeError exception. if (!NewTarget) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "NewTarget is undefined"); } // 3. Let constructorName be the String value of the Constructor Name value specified in Table 50 for this TypedArray constructor. let constructorName = getConstructorName(type); // 4. Let O be ? AllocateTypedArray(constructorName, NewTarget, "%TypedArrayPrototype%"). let O = (0, _typedarray.AllocateTypedArray)(realm, constructorName, NewTarget, `${type}ArrayPrototype`); // 5. Let usingIterator be ? GetMethod(object, @@iterator). let usingIterator = (0, _get.GetMethod)(realm, object, realm.intrinsics.SymbolIterator); // 6. If usingIterator is not undefined, then if (!(usingIterator instanceof _index.UndefinedValue)) { // a. Let values be ? IterableToList(object, usingIterator). let values = (0, _iterator.IterableToList)(realm, object, usingIterator); // b. Let len be the number of elements in values. let len = values.length; // c. Perform ? AllocateTypedArrayBuffer(O, len). (0, _typedarray.AllocateTypedArrayBuffer)(realm, O, len); // d. Let k be 0. let k = 0; // e. Repeat, while k < len while (k < len) { // i. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, _singletons.To.ToString(realm, new _index.NumberValue(realm, k))); // ii. Let kValue be the first element of values and remove that element from values. let kValue = values.shift(); // iii. Perform ? Set(O, Pk, kValue, true). _singletons.Properties.Set(realm, O, Pk, kValue, true); // iv. Increase k by 1. k = k + 1; } // f. Assert: values is now an empty List. (0, _invariant2.default)(values.length === 0); // g. Return O. return O; } // 7. NOTE: object is not an Iterable so assume it is already an array-like object. // 8. Let arrayLike be object. let arrayLike = object; // 9. Let len be ? ToLength(? Get(arrayLike, "length")). let len = _singletons.To.ToLength(realm, (0, _get.Get)(realm, arrayLike, "length")); // 10. Perform ? AllocateTypedArrayBuffer(O, len). (0, _typedarray.AllocateTypedArrayBuffer)(realm, O, len); // 11. Let k be 0. let k = 0; // 12. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, _singletons.To.ToString(realm, new _index.NumberValue(realm, k))); // b. Let kValue be ? Get(arrayLike, Pk). let kValue = (0, _get.Get)(realm, arrayLike, Pk); // c. Perform ? Set(O, Pk, kValue, true). _singletons.Properties.Set(realm, O, Pk, kValue, true); // d. Increase k by 1. k += 1; } // 13. Return O. return O; } else { // ECMA262 22.2.4.5 let buffer = args[0].throwIfNotConcrete(), byteOffset = args[1], length = args[2]; // 1. Assert: Type(buffer) is Object and buffer has an [[ArrayBufferData]] internal slot. (0, _invariant2.default)(buffer instanceof _index.ObjectValue && "$ArrayBufferData" in buffer); // 2. If NewTarget is undefined, throw a TypeError exception. if (!NewTarget) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "NewTarget is undefined"); } // 3. Let constructorName be the String value of the Constructor Name value specified in Table 50 for this TypedArray constructor. let constructorName = getConstructorName(type); // 4. Let O be ? AllocateTypedArray(constructorName, NewTarget, "%TypedArrayPrototype%"). let O = (0, _typedarray.AllocateTypedArray)(realm, constructorName, NewTarget, `${type}ArrayPrototype`); // 5. Let constructorName be the String value of O.[[TypedArrayName]]. constructorName = O.$TypedArrayName; (0, _invariant2.default)(constructorName); // 6. Let elementSize be the Number value of the Element Size value in Table 50 for constructorName. let elementSize = _typedarray.ArrayElementSize[constructorName]; // 7. Let offset be ? ToIndex(byteOffset). let offset = _singletons.To.ToIndexPartial(realm, byteOffset); // 8. If offset modulo elementSize ≠ 0, throw a RangeError exception. if (offset % elementSize !== 0) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "offset modulo elementSize ≠ 0"); } // 9. If IsDetachedBuffer(buffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, buffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(buffer) is true"); } // 10. Let bufferByteLength be buffer.[[ArrayBufferByteLength]]. let bufferByteLength = buffer.$ArrayBufferByteLength; (0, _invariant2.default)(typeof bufferByteLength === "number"); let newByteLength; // 11. If length is either not present or undefined, then if (!length || length instanceof _index.UndefinedValue) { // a. If bufferByteLength modulo elementSize ≠ 0, throw a RangeError exception. if (bufferByteLength % elementSize !== 0) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "bufferByteLength modulo elementSize ≠ 0"); } // b. Let newByteLength be bufferByteLength - offset. newByteLength = bufferByteLength - offset; // c. If newByteLength < 0, throw a RangeError exception. if (newByteLength < 0) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "newByteLength < 0"); } } else { // 12. Else, // a. Let newLength be ? ToIndex(length). let newLength = _singletons.To.ToIndexPartial(realm, length); // b. Let newByteLength be newLength × elementSize. newByteLength = newLength * elementSize; // c. If offset+newByteLength > bufferByteLength, throw a RangeError exception. if (offset + newByteLength > bufferByteLength) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "offset+newByteLength > bufferByteLength"); } } // 13. Set O.[[ViewedArrayBuffer]] to buffer. O.$ViewedArrayBuffer = buffer; // 14. Set O.[[ByteLength]] to newByteLength. O.$ByteLength = newByteLength; // 15. Set O.[[ByteOffset]] to offset. O.$ByteOffset = offset; // 16. Set O.[[ArrayLength]] to newByteLength / elementSize. O.$ArrayLength = newByteLength / elementSize; // 17. Return O. return O; } }); // ECMA262 22.2.5 func.$Prototype = realm.intrinsics.TypedArray; // ECMA262 22.2.5.1 func.defineNativeConstant("BYTES_PER_ELEMENT", new _index.NumberValue(realm, _types.ElementSize[type])); return func; } //# sourceMappingURL=TypedArray.js.map /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (realm, obj) { // ECMA262 22.2.3.1 obj.defineNativeGetter("buffer", context => { // 1. Let O be the this value. let O = context.throwIfNotConcrete(); // 2. If Type(O) is not Object, return undefined. if (!(O instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(O) is not Object"); } // 3. If O does not have a [[TypedArrayName]] internal slot, throw a TypeError exception. if (!("$TypedArrayName" in O)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "O does not have a [[TypedArrayName]] internal slot"); } // 4. Assert: O has a [[ViewedArrayBuffer]] internal slot. (0, _invariant2.default)(O.$ViewedArrayBuffer, "O has a [[ViewedArrayBuffer]]"); // 5. Let buffer be O.[[ViewedArrayBuffer]]. let buffer = O.$ViewedArrayBuffer; // 6. Return buffer. return buffer; }); // ECMA262 22.2.3.2 obj.defineNativeGetter("byteLength", context => { // 1. Let O be the this value. let O = context.throwIfNotConcrete(); // 2. If Type(O) is not Object, throw a TypeError exception. if (!(O instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(O) is not Object"); } // 3. If O does not have a [[TypedArrayName]] internal slot, throw a TypeError exception. if (!("$TypedArrayName" in O)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "O does not have a [[TypedArrayName]] internal slot"); } // 4. Assert: O has [[ViewedArrayBuffer]] and [[ArrayLength]] internal slots. (0, _invariant2.default)(O.$ViewedArrayBuffer, "O has a [[ViewedArrayBuffer]] internal slot"); // 5. Let buffer be O.[[ViewedArrayBuffer]]. let buffer = O.$ViewedArrayBuffer; (0, _invariant2.default)(buffer); // 6. If IsDetachedBuffer(buffer) is true, return 0. if ((0, _is.IsDetachedBuffer)(realm, buffer) === true) return realm.intrinsics.zero; // 7. Let size be O.[[ByteLength]]. let size = O.$ByteLength; (0, _invariant2.default)(typeof size === "number"); // 8. Return size. return new _index.NumberValue(realm, size); }); // ECMA262 22.2.3.3 obj.defineNativeGetter("byteOffset", context => { // 1. Let O be the this value. let O = context.throwIfNotConcrete(); // 2. If Type(O) is not Object, throw a TypeError exception. if (!(O instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(O) is not Object"); } // 3. If O does not have a [[TypedArrayName]] internal slot, throw a TypeError exception. if (!("$TypedArrayName" in O)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "O does not have a [[TypedArrayName]] internal slot"); } // 4. Assert: O has [[ViewedArrayBuffer]] and [[ArrayLength]] internal slots. (0, _invariant2.default)(O.$ViewedArrayBuffer, "O has a [[ViewedArrayBuffer]] internal slot"); // 5. Let buffer be O.[[ViewedArrayBuffer]]. let buffer = O.$ViewedArrayBuffer; (0, _invariant2.default)(buffer); // 6. If IsDetachedBuffer(buffer) is true, return 0. if ((0, _is.IsDetachedBuffer)(realm, buffer) === true) return realm.intrinsics.zero; // 7. Let offset be O.[[ByteOffset]]. let offset = O.$ByteOffset; (0, _invariant2.default)(typeof offset === "number"); // 8. Return offset. return new _index.NumberValue(realm, offset); }); // ECMA262 22.2.3.5 obj.defineNativeMethod("copyWithin", 2, (context, [target, start, end]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. Let relativeTarget be ? ToInteger(target). let relativeTarget = _singletons.To.ToInteger(realm, target); // 5. If relativeTarget < 0, let to be max((len + relativeTarget), 0); else let to be min(relativeTarget, len). let to = relativeTarget < 0 ? Math.max(len + relativeTarget, 0) : Math.min(relativeTarget, len); // 6. Let relativeStart be ? ToInteger(start). let relativeStart = _singletons.To.ToInteger(realm, start); // 7. If relativeStart < 0, let from be max((len + relativeStart), 0); else let from be min(relativeStart, len). let from = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); // 8. If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToInteger(end). let relativeEnd = !end || end instanceof _index.UndefinedValue ? len : _singletons.To.ToInteger(realm, end.throwIfNotConcrete()); // 9. If relativeEnd < 0, let final be max((len + relativeEnd), 0); else let final be min(relativeEnd, len). let final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // 10. Let count be min(final-from, len-to). let count = Math.min(final - from, len - to); let direction; // 11. If from 0 while (count > 0) { // a. Let fromKey be ! ToString(from). let fromKey = _singletons.To.ToString(realm, new _index.NumberValue(realm, from)); // b. Let toKey be ! ToString(to). let toKey = _singletons.To.ToString(realm, new _index.NumberValue(realm, to)); // c. Let fromPresent be ? HasProperty(O, fromKey). let fromPresent = (0, _has.HasProperty)(realm, O, fromKey); // d. If fromPresent is true, then if (fromPresent === true) { // i. Let fromVal be ? Get(O, fromKey). let fromVal = (0, _get.Get)(realm, O, fromKey); // ii. Perform ? Set(O, toKey, fromVal, true). _singletons.Properties.Set(realm, O, toKey, fromVal, true); } else { // e. Else fromPresent is false, // i. Perform ? DeletePropertyOrThrow(O, toKey). _singletons.Properties.DeletePropertyOrThrow(realm, O, toKey); } // f. Let from be from + direction. from = from + direction; // g. Let to be to + direction. to = to + direction; // h. Let count be count - 1. count = count - 1; } // 14. Return O. return O; }); // ECMA262 22.2.3.6 obj.defineNativeMethod("entries", 0, context => { // 1. Let O be the this value. let O = context; // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); (0, _invariant2.default)(O instanceof _index.ObjectValue); // 3. Return CreateArrayIterator(O, "key+value"). return _singletons.Create.CreateArrayIterator(realm, O, "key+value"); }); // ECMA262 22.2.3.7 obj.defineNativeMethod("every", 1, (context, [callbackfn, thisArg]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (!(0, _is.IsCallable)(realm, callbackfn)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. let T = thisArg || realm.intrinsics.undefined; // 6. Let k be 0. let k = 0; // 7. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, k + ""); // b. Let kPresent be ? HasProperty(O, Pk). let kPresent = (0, _has.HasProperty)(realm, O, Pk); // c. If kPresent is true, then if (kPresent) { // i. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, Pk); // ii. Let testResult be ToBoolean(? Call(callbackfn, T, « kValue, k, O »)). let testResult = _singletons.To.ToBooleanPartial(realm, (0, _call.Call)(realm, callbackfn, T, [kValue, new _index.NumberValue(realm, k), O])); // iii. If testResult is false, return false. if (!testResult) return realm.intrinsics.false; } // d. Increase k by 1. k++; } // 8. Return true. return realm.intrinsics.true; }); // ECMA262 22.2.3.8 obj.defineNativeMethod("fill", 1, (context, [value, start, end]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. Let relativeStart be ? ToInteger(start). let relativeStart = _singletons.To.ToInteger(realm, start || realm.intrinsics.undefined); // 5. If relativeStart < 0, let k be max((len + relativeStart), 0); else let k be min(relativeStart, len). let k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); // 6. If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToInteger(end). let relativeEnd = !end || end instanceof _index.UndefinedValue ? len : _singletons.To.ToInteger(realm, end.throwIfNotConcrete()); // 7. If relativeEnd < 0, let final be max((len + relativeEnd), 0); else let final be min(relativeEnd, len). let final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // 8. Repeat, while k < final while (k < final) { // a. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, k + ""); // b. Perform ? Set(O, Pk, value, true). _singletons.Properties.Set(realm, O, Pk, value, true); // c. Increase k by 1. k++; } // 9. Return O. return O; }); // ECMA262 22.2.3.9 obj.defineNativeMethod("filter", 1, (context, [callbackfn, thisArg]) => { // 1. Let O be the this value. let O = context; // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); (0, _invariant2.default)(O instanceof _index.ObjectValue); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if ((0, _is.IsCallable)(realm, callbackfn) === false) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsCallable(callbackfn) is false"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. let T = thisArg ? thisArg : realm.intrinsics.undefined; // 6. Let kept be a new empty List. let kept = []; // 7. Let k be 0. let k = 0; // 8. Let captured be 0. let captured = 0; // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = _singletons.To.ToString(realm, new _index.NumberValue(realm, k)); // b. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, Pk); // c. Let selected be ToBoolean(? Call(callbackfn, T, « kValue, k, O »)). let selected = _singletons.To.ToBooleanPartial(realm, (0, _call.Call)(realm, callbackfn, T, [kValue, new _index.NumberValue(realm, k), O])); // d. If selected is true, then if (selected === true) { // i. Append kValue to the end of kept. kept.push(kValue); // ii. Increase captured by 1. captured += 1; } // e. Increase k by 1. k += 1; } // 10. Let A be ? TypedArraySpeciesCreate(O, « captured »). let A = (0, _typedarray.TypedArraySpeciesCreate)(realm, O, [new _index.NumberValue(realm, captured)]); // 11. Let n be 0. let n = 0; // 12. For each element e of kept for (let e of kept) { // a. Perform ! Set(A, ! ToString(n), e, true). _singletons.Properties.Set(realm, A, new _index.StringValue(realm, _singletons.To.ToString(realm, new _index.NumberValue(realm, n))), e, true); // b. Increment n by 1. n = n + 1; } // 13. Return A. return A; }); // ECMA262 22.2.3.10 obj.defineNativeMethod("find", 1, (context, [predicate, thisArg]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If IsCallable(predicate) is false, throw a TypeError exception. if (!(0, _is.IsCallable)(realm, predicate)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. let T = thisArg || realm.intrinsics.undefined; // 6. Let k be 0. let k = 0; // 7. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, k + ""); // b. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, Pk); // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). let testResult = _singletons.To.ToBooleanPartial(realm, (0, _call.Call)(realm, predicate, T, [kValue, new _index.NumberValue(realm, k), O])); // d. If testResult is true, return kValue. if (testResult) return kValue; // e. Increase k by 1. k++; } // 8. Return undefined. return realm.intrinsics.undefined; }); // ECMA262 22.2.3.11 obj.defineNativeMethod("findIndex", 1, (context, [predicate, thisArg]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If IsCallable(predicate) is false, throw a TypeError exception. if ((0, _is.IsCallable)(realm, predicate) === false) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. let T = thisArg ? thisArg : realm.intrinsics.undefined; // 6. Let k be 0. let k = 0; // 7. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = _singletons.To.ToString(realm, new _index.NumberValue(realm, k)); // b. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, new _index.StringValue(realm, Pk)); // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). let testResult = _singletons.To.ToBooleanPartial(realm, (0, _call.Call)(realm, predicate, T, [kValue, new _index.NumberValue(realm, k), O])); // d. If testResult is true, return k. if (testResult === true) return new _index.NumberValue(realm, k); // e. Increase k by 1. k = k + 1; } // 8. Return -1. return new _index.NumberValue(realm, -1); }); // ECMA262 22.2.3.12 obj.defineNativeMethod("forEach", 1, (context, [callbackfn, thisArg]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (!(0, _is.IsCallable)(realm, callbackfn)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. let T = thisArg || realm.intrinsics.undefined; // 6. Let k be 0. let k = 0; // 7. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, k + ""); // b. Let kPresent be ? HasProperty(O, Pk). let kPresent = (0, _has.HasProperty)(realm, O, Pk); // c. If kPresent is true, then if (kPresent) { // i. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, Pk); // ii. Perform ? Call(callbackfn, T, « kValue, k, O »). (0, _call.Call)(realm, callbackfn, T, [kValue, new _index.NumberValue(realm, k), O]); } // d. Increase k by 1. k++; } // 8. Return undefined. return realm.intrinsics.undefined; }); // ECMA262 22.2.3.14 obj.defineNativeMethod("includes", 1, (context, [searchElement, fromIndex]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If len is 0, return false. if (len === 0) return realm.intrinsics.false; // 5. Let n be ? ToInteger(fromIndex). (If fromIndex is undefined, this step produces the value 0.) let n = _singletons.To.ToInteger(realm, fromIndex || realm.intrinsics.undefined); let k; // 6. If n ≥ 0, then if (n >= 0) { // a. Let k be n. k = n; } else { // 7. Else n < 0, // a. Let k be len + n. k = len + n; // b. If k < 0, let k be 0. if (k < 0) k = 0; } // 8. Repeat, while k < len while (k < len) { // a. Let elementK be the result of ? Get(O, ! ToString(k)). let elementK = (0, _get.Get)(realm, O, _singletons.To.ToString(realm, new _index.NumberValue(realm, k))); // b. If SameValueZero(searchElement, elementK) is true, return true. if ((0, _abstract.SameValueZeroPartial)(realm, searchElement, elementK) === true) return realm.intrinsics.true; // c. Increase k by 1. k = k + 1; } // 9. Return false. return realm.intrinsics.false; }); // ECMA262 22.2.3.14 obj.defineNativeMethod("indexOf", 1, (context, [searchElement, fromIndex]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If len is 0, return -1. if (len === 0) return new _index.NumberValue(realm, -1); // 5. Let n be ? ToInteger(fromIndex). (If fromIndex is undefined, this step produces the value 0.) let n = fromIndex ? _singletons.To.ToInteger(realm, fromIndex) : 0; // 6. If n ≥ len, return -1. if (n >= len) return new _index.NumberValue(realm, -1); // 7. If n ≥ 0, then let k; if (n >= 0) { // a. If n is -0, let k be +0; else let k be n. k = Object.is(n, -0) ? +0 : n; } else { // 8. Else n < 0, // a. Let k be len + n. k = len + n; // b. If k < 0, let k be 0. if (k < 0) k = 0; } // 9. Repeat, while k < len while (k < len) { // a. Let kPresent be ? HasProperty(O, ! ToString(k)). let kPresent = (0, _has.HasProperty)(realm, O, k + ""); // b. If kPresent is true, then if (kPresent === true) { // i. Let elementK be ? Get(O, ! ToString(k)). let elementK = (0, _get.Get)(realm, O, k + ""); // ii. Let same be the result of performing Strict Equality Comparison searchElement === elementK. let same = (0, _abstract.StrictEqualityComparisonPartial)(realm, searchElement, elementK); // iii. If same is true, return k. if (same) return new _index.NumberValue(realm, k); } // c. Increase k by 1. k++; } // 10. Return -1. return new _index.NumberValue(realm, -1); }); // ECMA262 22.2.3.15 obj.defineNativeMethod("join", 1, (context, [separator]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If separator is undefined, let separator be the single-element String ",". if (!separator || separator instanceof _index.UndefinedValue) separator = new _index.StringValue(realm, ","); // 5. Let sep be ? ToString(separator). let sep = _singletons.To.ToStringPartial(realm, separator); // 6. If len is zero, return the empty String. if (len === 0) return realm.intrinsics.emptyString; // 7. Let element0 be Get(O, "0"). let element0 = (0, _get.Get)(realm, O, "0"); // 8. If element0 is undefined or null, let R be the empty String; otherwise, let R be ? ToString(element0). let R; if ((0, _has.HasSomeCompatibleType)(element0, _index.UndefinedValue, _index.NullValue)) { R = ""; } else { R = _singletons.To.ToStringPartial(realm, element0); } // 9. Let k be 1. let k = 1; // 10. Repeat, while k < len while (k < len) { // a. Let S be the String value produced by concatenating R and sep. let S = R + sep; // b. Let element be ? Get(O, ! ToString(k)). let element = (0, _get.Get)(realm, O, new _index.StringValue(realm, k + "")); // c. If element is undefined or null, let next be the empty String; otherwise, let next be ? ToString(element). let next; if ((0, _has.HasSomeCompatibleType)(element, _index.UndefinedValue, _index.NullValue)) { next = ""; } else { next = _singletons.To.ToStringPartial(realm, element); } // d. Let R be a String value produced by concatenating S and next. R = S + next; // e. Increase k by 1. k++; } // 11. Return R. return new _index.StringValue(realm, R + ""); }); // ECMA262 22.2.3.16 obj.defineNativeMethod("keys", 0, context => { // 1. Let O be the this value. let O = context; // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); (0, _invariant2.default)(O instanceof _index.ObjectValue); // 3. Return CreateArrayIterator(O, "key"). return _singletons.Create.CreateArrayIterator(realm, O, "key"); }); // ECMA262 22.2.3.17 obj.defineNativeMethod("lastIndexOf", 1, (context, [searchElement, fromIndex]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If len is 0, return -1. if (len === 0) return new _index.NumberValue(realm, -1); // 5. If argument fromIndex was passed, let n be ? ToInteger(fromIndex); else let n be len-1. let n = fromIndex ? _singletons.To.ToInteger(realm, fromIndex) : len - 1; // 6. If n ≥ 0, then let k; if (n >= 0) { // a. If n is -0, let k be +0; else let k be min(n, len - 1). k = Object.is(n, -0) ? +0 : Math.min(n, len - 1); } else { // 7. Else n < 0, // a. Let k be len + n. k = len + n; } // 8. Repeat, while k ≥ 0 while (k >= 0) { // a. Let kPresent be ? HasProperty(O, ! ToString(k)). let kPresent = (0, _has.HasProperty)(realm, O, new _index.StringValue(realm, k + "")); // b. If kPresent is true, then if (kPresent) { // i. Let elementK be ? Get(O, ! ToString(k)). let elementK = (0, _get.Get)(realm, O, new _index.StringValue(realm, k + "")); // ii. Let same be the result of performing Strict Equality Comparison searchElement === elementK. let same = (0, _abstract.StrictEqualityComparisonPartial)(realm, searchElement, elementK); // iii. If same is true, return k. if (same) return new _index.NumberValue(realm, k); } // c. Decrease k by 1. k--; } // 9. Return -1. return new _index.NumberValue(realm, -1); }); // ECMA262 22.2.3.18 obj.defineNativeGetter("length", context => { // 1. Let O be the this value. let O = context.throwIfNotConcrete(); // 2. If Type(O) is not Object, throw a TypeError exception. if (!(O instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(O) is not Object"); } // 3. If O does not have a [[TypedArrayName]] internal slot, throw a TypeError exception. if (!("$TypedArrayName" in O)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "O does not have a [[TypedArrayName]] internal slot"); } // 4. Assert: O has [[ViewedArrayBuffer]] and [[ArrayLength]] internal slots. (0, _invariant2.default)(O.$ViewedArrayBuffer, "O has a [[ViewedArrayBuffer]] internal slot"); // 5. Let buffer be O.[[ViewedArrayBuffer]]. let buffer = O.$ViewedArrayBuffer; (0, _invariant2.default)(buffer); // 6. If IsDetachedBuffer(buffer) is true, return 0. if ((0, _is.IsDetachedBuffer)(realm, buffer) === true) return realm.intrinsics.zero; // 7. Let length be O.[[ArrayLength]]. let length = O.$ArrayLength; (0, _invariant2.default)(typeof length === "number"); // 8. Return length. return new _index.NumberValue(realm, length); }); // ECMA262 22.2.3.19 obj.defineNativeMethod("map", 1, (context, [callbackfn, thisArg]) => { // 1. Let O be the this value. let O = context; // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); (0, _invariant2.default)(O instanceof _index.ObjectValue); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if ((0, _is.IsCallable)(realm, callbackfn) === false) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsCallable(callbackfn) is false"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. let T = thisArg ? thisArg : realm.intrinsics.undefined; // 6. Let A be ? TypedArraySpeciesCreate(O, « len »). let A = (0, _typedarray.TypedArraySpeciesCreate)(realm, O, [new _index.NumberValue(realm, len)]); // 7. Let k be 0. let k = 0; // 8. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = _singletons.To.ToString(realm, new _index.NumberValue(realm, k)); // b. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, Pk); // c. Let mappedValue be ? Call(callbackfn, T, « kValue, k, O »). let mappedValue = (0, _call.Call)(realm, callbackfn, T, [kValue, new _index.NumberValue(realm, k), O]); // d. Perform ? Set(A, Pk, mappedValue, true). _singletons.Properties.Set(realm, A, Pk, mappedValue, true); // e. Increase k by 1. k = k + 1; } // 9. Return A. return A; }); // ECMA262 22.2.3.20 obj.defineNativeMethod("reduce", 1, (context, [callbackfn, initialValue]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (!(0, _is.IsCallable)(realm, callbackfn)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not a function"); } // 5. If len is 0 and initialValue is not present, throw a TypeError exception. if (len === 0 && !initialValue) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Array.prototype"); } // 6. Let k be 0. let k = 0; // 7. If initialValue is present, then let accumulator; if (initialValue) { // a. Set accumulator to initialValue. accumulator = initialValue; } else { // 8. Else initialValue is not present, // a. Let kPresent be false. let kPresent = false; // b. Repeat, while kPresent is false and k < len while (kPresent === false && k < len) { // i. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, k + ""); // ii. Let kPresent be ? HasProperty(O, Pk). kPresent = (0, _has.HasProperty)(realm, O, Pk); // iv. If kPresent is true, then if (kPresent) { // 1. Let accumulator be ? Get(O, Pk). accumulator = (0, _get.Get)(realm, O, Pk); } // v. Increase k by 1. k++; } // c. If kPresent is false, throw a TypeError exception. if (!kPresent) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "kPresent is false"); } (0, _invariant2.default)(accumulator); } // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, k + ""); // b. Let kPresent be ? HasProperty(O, Pk). let kPresent = (0, _has.HasProperty)(realm, O, Pk); // c. If kPresent is true, then if (kPresent) { // i. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, Pk); // ii. Let accumulator be ? Call(callbackfn, undefined, « accumulator, kValue, k, O »). accumulator = (0, _call.Call)(realm, callbackfn, realm.intrinsics.undefined, [accumulator, kValue, new _index.NumberValue(realm, k), O]); } // d. Increase k by 1. k++; } // 10. Return accumulator. return accumulator; }); // ECMA262 22.2.3.21 obj.defineNativeMethod("reduceRight", 1, (context, [callbackfn, initialValue]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (!(0, _is.IsCallable)(realm, callbackfn)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "not a function"); } // 5. If len is 0 and initialValue is not present, throw a TypeError exception. if (len === 0 && !initialValue) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Array.prototype"); } // 6. Let k be len-1. let k = len - 1; // 7. If initialValue is present, then let accumulator; if (initialValue) { // 1. Set accumulator to initialValue. accumulator = initialValue; } else { // 8. Else initialValue is not present, // a. Let kPresent be false. let kPresent = false; // b. Repeat, while kPresent is false and k ≥ 0 while (!kPresent && k >= 0) { // i. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, k + ""); // ii. Let kPresent be ? HasProperty(O, Pk). kPresent = (0, _has.HasProperty)(realm, O, Pk); // iii. If kPresent is true, then if (kPresent) { // 1. Let accumulator be ? Get(O, Pk). accumulator = (0, _get.Get)(realm, O, Pk); } // iv. Decrease k by 1. k--; } // c. If kPresent is false, throw a TypeError exception. if (!kPresent || !accumulator) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Array.prototype"); } } // 9. Repeat, while k ≥ 0 while (k >= 0) { // a. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, k + ""); // b. Let kPresent be ? HasProperty(O, Pk). let kPresent = (0, _has.HasProperty)(realm, O, Pk); // c. If kPresent is true, then if (kPresent) { // i. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, Pk); // ii. Let accumulator be ? Call(callbackfn, undefined, « accumulator, kValue, k, O »). accumulator = (0, _call.Call)(realm, callbackfn, realm.intrinsics.undefined, [accumulator, kValue, new _index.NumberValue(realm, k), O]); } // d. Decrease k by 1. k--; } // 10. Return accumulator. return accumulator; }); // ECMA262 22.2.3.21 obj.defineNativeMethod("reverse", 0, context => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. Let middle be floor(len/2). let middle = Math.floor(len / 2); // 5. Let lower be 0. let lower = 0; // 6. Repeat, while lower ≠ middle while (lower !== middle) { // a. Let upper be len - lower - 1. let upper = len - lower - 1; // b. Let upperP be ! ToString(upper). let upperP = new _index.StringValue(realm, upper + ""); // c. Let lowerP be ! ToString(lower). let lowerP = new _index.StringValue(realm, lower + ""); // d. Let lowerExists be ? HasProperty(O, lowerP). let lowerExists = (0, _has.HasProperty)(realm, O, lowerP); // e. If lowerExists is true, then let lowerValue; if (lowerExists) { // i. Let lowerValue be ? Get(O, lowerP). lowerValue = (0, _get.Get)(realm, O, lowerP); } // f. Let upperExists be ? HasProperty(O, upperP). let upperExists = (0, _has.HasProperty)(realm, O, upperP); // g. If upperExists is true, then let upperValue; if (upperExists) { // i. Let upperValue be ? Get(O, upperP). upperValue = (0, _get.Get)(realm, O, upperP); } // h. If lowerExists is true and upperExists is true, then if (lowerExists && upperExists) { (0, _invariant2.default)(lowerValue, "expected lower value to exist"); (0, _invariant2.default)(upperValue, "expected upper value to exist"); // i. Perform ? Set(O, lowerP, upperValue, true). _singletons.Properties.Set(realm, O, lowerP, upperValue, true); // ii. Perform ? Set(O, upperP, lowerValue, true). _singletons.Properties.Set(realm, O, upperP, lowerValue, true); } else if (!lowerExists && upperExists) { // i. Else if lowerExists is false and upperExists is true, then (0, _invariant2.default)(upperValue, "expected upper value to exist"); // i. Perform ? Set(O, lowerP, upperValue, true). _singletons.Properties.Set(realm, O, lowerP, upperValue, true); // ii. Perform ? DeletePropertyOrThrow(O, upperP). _singletons.Properties.DeletePropertyOrThrow(realm, O, upperP); } else if (lowerExists && !upperExists) { // j. Else if lowerExists is true and upperExists is false, then (0, _invariant2.default)(lowerValue, "expected lower value to exist"); // i. Perform ? DeletePropertyOrThrow(O, lowerP). _singletons.Properties.DeletePropertyOrThrow(realm, O, lowerP); // ii. Perform ? Set(O, upperP, lowerValue, true). _singletons.Properties.Set(realm, O, upperP, lowerValue, true); } else {} // k. Else both lowerExists and upperExists are false, // i. No action is required. // l. Increase lower by 1. lower++; } // 7. Return O. return O; }); // ECMA262 22.2.3.23 obj.defineNativeMethod("set", 1, (context, [overloaded, offset]) => { if (!overloaded.$TypedArrayName) { let array = overloaded; // 1. Assert: array is any ECMAScript language value other than an Object with a [[TypedArrayName]] internal slot. If it is such an Object, the definition in 22.2.3.23.2 applies. (0, _invariant2.default)(!(overloaded instanceof _index.ObjectValue && overloaded.$TypedArrayName)); // 2. Let target be the this value. let target = context.throwIfNotConcrete(); // 3. If Type(target) is not Object, throw a TypeError exception. if (!(target instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(target) is not Object"); } // 4. If target does not have a [[TypedArrayName]] internal slot, throw a TypeError exception. if (typeof target.$TypedArrayName !== "string") { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "target does not have a [[TypedArrayName]] internal slot"); } // 5. Assert: target has a [[ViewedArrayBuffer]] internal slot. (0, _invariant2.default)(target.$ViewedArrayBuffer, "target has a [[ViewedArrayBuffer]] internal slot"); // 6. Let targetOffset be ? ToInteger(offset). let targetOffset = _singletons.To.ToInteger(realm, offset || realm.intrinsics.undefined); // 7. If targetOffset < 0, throw a RangeError exception. if (targetOffset < 0) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "targetOffset < 0"); } // 8. Let targetBuffer be target.[[ViewedArrayBuffer]]. let targetBuffer = target.$ViewedArrayBuffer; (0, _invariant2.default)(targetBuffer instanceof _index.ObjectValue); // 9. If IsDetachedBuffer(targetBuffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, targetBuffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(targetBuffer) is true"); } // 10. Let targetLength be target.[[ArrayLength]]. let targetLength = target.$ArrayLength; (0, _invariant2.default)(typeof targetLength === "number"); // 11. Let targetName be the String value of target.[[TypedArrayName]]. let targetName = target.$TypedArrayName; (0, _invariant2.default)(typeof targetName === "string"); // 12. Let targetElementSize be the Number value of the Element Size value specified in Table 50 for targetName. let targetElementSize = _typedarray.ArrayElementSize[targetName]; // 13. Let targetType be the String value of the Element Type value in Table 50 for targetName. let targetType = _typedarray.ArrayElementType[targetName]; // 14. Let targetByteOffset be target.[[ByteOffset]]. let targetByteOffset = target.$ByteOffset; (0, _invariant2.default)(typeof targetByteOffset === "number"); // 15. Let src be ? ToObject(array). let src = _singletons.To.ToObjectPartial(realm, array); // 16. Let srcLength be ? ToLength(? Get(src, "length")). let srcLength = _singletons.To.ToLength(realm, (0, _get.Get)(realm, src, "length")); // 17. If srcLength + targetOffset > targetLength, throw a RangeError exception. if (srcLength + targetOffset > targetLength) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "srcLength + targetOffset > targetLength"); } // 18. Let targetByteIndex be targetOffset × targetElementSize + targetByteOffset. let targetByteIndex = targetOffset * targetElementSize + targetByteOffset; // 19. Let k be 0. let k = 0; // 20. Let limit be targetByteIndex + targetElementSize × srcLength. let limit = targetByteIndex + targetElementSize * srcLength; // 21. Repeat, while targetByteIndex < limit while (targetByteIndex < limit) { // a. Let Pk be ! ToString(k). let Pk = _singletons.To.ToString(realm, new _index.NumberValue(realm, k)); // b. Let kNumber be ? ToNumber(? Get(src, Pk)). let kNumber = _singletons.To.ToNumber(realm, (0, _get.Get)(realm, src, Pk)); // c. If IsDetachedBuffer(targetBuffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, targetBuffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(targetBuffer) is true"); } // d. Perform SetValueInBuffer(targetBuffer, targetByteIndex, targetType, kNumber). (0, _arraybuffer.SetValueInBuffer)(realm, targetBuffer, targetByteIndex, targetType, kNumber); // e. Set k to k + 1. k = k + 1; // f. Set targetByteIndex to targetByteIndex + targetElementSize. targetByteIndex = targetByteIndex + targetElementSize; } // 22. Return undefined. return realm.intrinsics.undefined; } else { let typedArray = overloaded; // 1. Assert: typedArray has a [[TypedArrayName]] internal slot. If it does not, the definition in 22.2.3.23.1 applies. (0, _invariant2.default)(typedArray instanceof _index.ObjectValue && typedArray.$TypedArrayName); // 2. Let target be the this value. let target = context.throwIfNotConcrete(); // 3. If Type(target) is not Object, throw a TypeError exception. if (!(target instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(target) is not Object"); } // 4. If target does not have a [[TypedArrayName]] internal slot, throw a TypeError exception. if (typeof target.$TypedArrayName !== "string") { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "target does not have a [[TypedArrayName]] internal slot"); } // 5. Assert: target has a [[ViewedArrayBuffer]] internal slot. (0, _invariant2.default)(target.$ViewedArrayBuffer); // 6. Let targetOffset be ? ToInteger(offset). let targetOffset = _singletons.To.ToInteger(realm, offset || realm.intrinsics.undefined); // 7. If targetOffset < 0, throw a RangeError exception. if (targetOffset < 0) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "targetOffset < 0"); } // 8. Let targetBuffer be target.[[ViewedArrayBuffer]]. let targetBuffer = target.$ViewedArrayBuffer; (0, _invariant2.default)(targetBuffer instanceof _index.ObjectValue); // 9. If IsDetachedBuffer(targetBuffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, targetBuffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(targetBuffer) is true"); } // 10. Let targetLength be target.[[ArrayLength]]. let targetLength = target.$ArrayLength; (0, _invariant2.default)(typeof targetLength === "number"); // 11. Let srcBuffer be typedArray.[[ViewedArrayBuffer]]. let srcBuffer = typedArray.$ViewedArrayBuffer; (0, _invariant2.default)(srcBuffer); // 12. If IsDetachedBuffer(srcBuffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, srcBuffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(srcBuffer) is true"); } // 13. Let targetName be the String value of target.[[TypedArrayName]]. let targetName = target.$TypedArrayName; (0, _invariant2.default)(typeof targetName === "string"); // 14. Let targetType be the String value of the Element Type value in Table 50 for targetName. let targetType = _typedarray.ArrayElementType[targetName]; // 15. Let targetElementSize be the Number value of the Element Size value specified in Table 50 for targetName. let targetElementSize = _typedarray.ArrayElementSize[targetName]; // 16. Let targetByteOffset be target.[[ByteOffset]]. let targetByteOffset = target.$ByteOffset; (0, _invariant2.default)(typeof targetByteOffset === "number"); // 17. Let srcName be the String value of typedArray.[[TypedArrayName]]. let srcName = typedArray.$TypedArrayName; (0, _invariant2.default)(typeof srcName === "string"); // 18. Let srcType be the String value of the Element Type value in Table 50 for srcName. let srcType = _typedarray.ArrayElementType[srcName]; // 19. Let srcElementSize be the Number value of the Element Size value specified in Table 50 for srcName. let srcElementSize = _typedarray.ArrayElementSize[srcName]; // 20. Let srcLength be typedArray.[[ArrayLength]]. let srcLength = typedArray.$ArrayLength; (0, _invariant2.default)(typeof srcLength === "number"); // 21. Let srcByteOffset be typedArray.[[ByteOffset]]. let srcByteOffset = typedArray.$ByteOffset; (0, _invariant2.default)(typeof srcByteOffset === "number"); // 22. If srcLength + targetOffset > targetLength, throw a RangeError exception. if (srcLength + targetOffset > targetLength) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "srcLength + targetOffset > targetLength"); } let srcByteIndex; // 23. If SameValue(srcBuffer, targetBuffer) is true, then if ((0, _abstract.SameValue)(realm, srcBuffer, targetBuffer) === true) { // a. Let srcBuffer be ? CloneArrayBuffer(targetBuffer, srcByteOffset, %ArrayBuffer%). srcBuffer = (0, _arraybuffer.CloneArrayBuffer)(realm, targetBuffer, srcByteOffset, realm.intrinsics.ArrayBuffer); // b. NOTE: %ArrayBuffer% is used to clone srcBuffer because is it known to not have any observable side-effects. // c. Let srcByteIndex be 0. srcByteIndex = 0; } else { // 24. Else, let srcByteIndex be srcByteOffset. srcByteIndex = srcByteOffset; } // 25. Let targetByteIndex be targetOffset × targetElementSize + targetByteOffset. let targetByteIndex = targetOffset * targetElementSize + targetByteOffset; // 26. Let limit be targetByteIndex + targetElementSize × srcLength. let limit = targetByteIndex + targetElementSize * srcLength; // 27. If SameValue(srcType, targetType) is true, then if (srcType === targetType) { // a. NOTE: If srcType and targetType are the same, the transfer must be performed in a manner that preserves the bit-level encoding of the source data. // b. Repeat, while targetByteIndex < limit while (targetByteIndex < limit) { // i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, "Uint8"). let value = (0, _arraybuffer.GetValueFromBuffer)(realm, srcBuffer, srcByteIndex, "Uint8"); // ii. Perform SetValueInBuffer(targetBuffer, targetByteIndex, "Uint8", value). (0, _arraybuffer.SetValueInBuffer)(realm, targetBuffer, targetByteIndex, "Uint8", value.value); // iii. Set srcByteIndex to srcByteIndex + 1. srcByteIndex += 1; // iv. Set targetByteIndex to targetByteIndex + 1. targetByteIndex += 1; } } else { // 28. Else, // a. Repeat, while targetByteIndex < limit while (targetByteIndex < limit) { // i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, srcType). let value = (0, _arraybuffer.GetValueFromBuffer)(realm, srcBuffer, srcByteIndex, srcType); // ii. Perform SetValueInBuffer(targetBuffer, targetByteIndex, targetType, value). (0, _arraybuffer.SetValueInBuffer)(realm, targetBuffer, targetByteIndex, targetType, value.value); // iii. Set srcByteIndex to srcByteIndex + srcElementSize. srcByteIndex = srcByteIndex + srcElementSize; // iv. Set targetByteIndex to targetByteIndex + targetElementSize. targetByteIndex = targetByteIndex + targetElementSize; } } // 29. Return undefined. return realm.intrinsics.undefined; } }); // ECMA262 22.2.3.24 obj.defineNativeMethod("slice", 2, (context, [start, end]) => { // 1. Let O be the this value. let O = context; // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); (0, _invariant2.default)(O instanceof _index.ObjectValue); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. Let relativeStart be ? ToInteger(start). let relativeStart = _singletons.To.ToInteger(realm, start); // 5. If relativeStart < 0, let k be max((len + relativeStart), 0); else let k be min(relativeStart, len). let k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); // 6. If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToInteger(end). let relativeEnd = !end || end instanceof _index.UndefinedValue ? len : _singletons.To.ToInteger(realm, end.throwIfNotConcrete()); // 7. If relativeEnd < 0, let final be max((len + relativeEnd), 0); else let final be min(relativeEnd, len). let final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // 8. Let count be max(final - k, 0). let count = Math.max(final - k, 0); // 9. Let A be ? TypedArraySpeciesCreate(O, « count »). let A = (0, _typedarray.TypedArraySpeciesCreate)(realm, O, [new _index.NumberValue(realm, count)]); // 10. Let srcName be the String value of O.[[TypedArrayName]]. let srcName = O.$TypedArrayName; (0, _invariant2.default)(typeof srcName === "string"); // 11. Let srcType be the String value of the Element Type value in Table 50 for srcName. let srcType = _typedarray.ArrayElementType[srcName]; // 12. Let targetName be the String value of A.[[TypedArrayName]]. let targetName = A.$TypedArrayName; (0, _invariant2.default)(typeof targetName === "string"); // 13. Let targetType be the String value of the Element Type value in Table 50 for targetName. let targetType = _typedarray.ArrayElementType[targetName]; // 14. If SameValue(srcType, targetType) is false, then if (srcType !== targetType) { // a. Let n be 0. let n = 0; // b. Repeat, while k < final while (k < final) { // i. Let Pk be ! ToString(k). let Pk = _singletons.To.ToString(realm, new _index.NumberValue(realm, k)); // ii. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, Pk); // iii. Perform ! Set(A, ! ToString(n), kValue). _singletons.Properties.Set(realm, A, _singletons.To.ToString(realm, new _index.NumberValue(realm, n)), kValue, true); // iv. Increase k by 1. k += 1; // v. Increase n by 1. n += 1; } } else if (count > 0) { // 15. Else if count > 0, then // a. Let srcBuffer be O.[[ViewedArrayBuffer]]. let srcBuffer = O.$ViewedArrayBuffer; (0, _invariant2.default)(srcBuffer); // b. If IsDetachedBuffer(srcBuffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, srcBuffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(srcBuffer) is true"); } // c. Let targetBuffer be A.[[ViewedArrayBuffer]]. let targetBuffer = A.$ViewedArrayBuffer; (0, _invariant2.default)(targetBuffer instanceof _index.ObjectValue); // d. Let elementSize be the Number value of the Element Size value specified in Table 50 for srcType. let elementSize = _types.ElementSize[srcType]; // e. NOTE: If srcType and targetType are the same, the transfer must be performed in a manner that preserves the bit-level encoding of the source data. // f. Let srcByteOffset be O.[[ByteOffset]]. let srcByteOffset = O.$ByteOffset; (0, _invariant2.default)(typeof srcByteOffset === "number"); // g. Let targetByteIndex be A.[[ByteOffset]]. let targetByteIndex = A.$ByteOffset; (0, _invariant2.default)(typeof targetByteIndex === "number"); // h. Let srcByteIndex be (k × elementSize) + srcByteOffset. let srcByteIndex = k * elementSize + srcByteOffset; // i. Let limit be targetByteIndex + count × elementSize. let limit = targetByteIndex + count * elementSize; // j. Repeat, while targetByteIndex < limit while (targetByteIndex < limit) { // i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, "Uint8"). let value = (0, _arraybuffer.GetValueFromBuffer)(realm, srcBuffer, srcByteIndex, "Uint8"); // ii. Perform SetValueInBuffer(targetBuffer, targetByteIndex, "Uint8", value). (0, _arraybuffer.SetValueInBuffer)(realm, targetBuffer, targetByteIndex, "Uint8", value.value); // iii. Increase srcByteIndex by 1. srcByteIndex += 1; // iv. Increase targetByteIndex by 1. targetByteIndex += 1; } } // 16. Return A. return A; }); // ECMA262 22.2.3.25 obj.defineNativeMethod("some", 1, (context, [callbackfn, thisArg]) => { // 1. Let O be ? ToObject(this value). let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(O). (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be O.[[ArrayLength]]. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (!(0, _is.IsCallable)(realm, callbackfn)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "callback passed to Array.prototype.some isn't callable"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. let T = thisArg || realm.intrinsics.undefined; // 6. Let k be 0. let k = 0; // 7. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). let Pk = new _index.StringValue(realm, k + ""); // b. Let kPresent be ? HasProperty(O, Pk). let kPresent = (0, _has.HasProperty)(realm, O, Pk); // c. If kPresent is true, then if (kPresent) { // i. Let kValue be ? Get(O, Pk). let kValue = (0, _get.Get)(realm, O, Pk); // ii. Let testResult be ToBoolean(? Call(callbackfn, T, « kValue, k, O »)). let testResult = _singletons.To.ToBooleanPartial(realm, (0, _call.Call)(realm, callbackfn, T, [kValue, new _index.NumberValue(realm, k), O])); // iii. If testResult is true, return true. if (testResult) return realm.intrinsics.true; } // d. Increase k by 1. k++; } // 8. Return false. return realm.intrinsics.false; }); // ECMA262 22.2.3.26 obj.defineNativeMethod("sort", 1, (context, [comparefn]) => { // 1. Let obj be the this value. let O = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Let buffer be ? ValidateTypedArray(obj). let buffer = (0, _typedarray.ValidateTypedArray)(realm, O); // 3. Let len be the value of obj's [[ArrayLength]] internal slot. let len = O.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 22.2.3.26 Runtime Semantics: SortCompare( x, y )# let SortCompare = (x, y) => { // 1. Assert: Both Type(x) and Type(y) is Number. (0, _invariant2.default)(x instanceof _index.NumberValue); (0, _invariant2.default)(y instanceof _index.NumberValue); // 2. If the argument comparefn is not undefined, then if (!comparefn.mightBeUndefined()) { // a. Let v be ? Call(comparefn, undefined, « x, y »). let v = (0, _call.Call)(realm, comparefn, realm.intrinsics.undefined, [x, y]); // b. If IsDetachedBuffer(buffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, buffer) === true) throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "array buffer has been detached"); // c. If v is NaN, return +0. if (v instanceof _index.NumberValue && isNaN(v.value)) return realm.intrinsics.zero; // d. Return v. return v; } comparefn.throwIfNotConcrete(); // If x and y are both NaN, return +0. // If x is NaN, return 1. if (isNaN(x.value)) { if (isNaN(y.value)) return realm.intrinsics.zero; return new _index.NumberValue(realm, 1); } // If y is NaN, return -1. if (isNaN(y.value)) return new _index.NumberValue(realm, -1); // If x < y, return -1. if (x.value < y.value) return new _index.NumberValue(realm, -1); // If x > y, return 1. if (x.value > y.value) return new _index.NumberValue(realm, +1); // If x is -0 and y is +0, return -1. if (Object.is(x.value, -0) && Object.is(y.value, +0)) return new _index.NumberValue(realm, -1); // If x is +0 and y is -0, return 1. if (Object.is(x.value, +0) && Object.is(y.value, -0)) return new _index.NumberValue(realm, 1); // Return +0. return realm.intrinsics.zero; }; //1. Perform an implementation-dependent sequence of calls to the [[Get]] and [[Set]] internal methods of obj, to the DeletePropertyOrThrow and HasOwnProperty abstract operation with obj as the first argument, and to SortCompare (described below), such that: // The property key argument for each call to [[Get]], [[Set]], HasOwnProperty, or DeletePropertyOrThrow is the string representation of a nonnegative integer less than len. // We leverage the underlying implementation sort by copying the element in a temp. array, sorting it, and // transfering back the value inside the our array. // We need to adapt the comparefn function to match the expected types let comparefn_ = (x, y) => { (0, _invariant2.default)(x instanceof _index.NumberValue, "Unexpected type"); (0, _invariant2.default)(y instanceof _index.NumberValue, "Unexpected type"); let result_ = SortCompare(x, y); let numb = _singletons.To.ToNumber(realm, result_); return numb; }; let arr = []; for (let j = 0; j < len; j++) { let val = (0, _typedarray.IntegerIndexedElementGet)(realm, O, j); arr[j] = val; } arr.sort(comparefn_); //Apply the permutation back to the original array. for (let j = 0; j < len; j++) { (0, _typedarray.IntegerIndexedElementSet)(realm, O, j, arr[j]); } // 2. Return obj; return context; }); // ECMA262 22.2.3.27 obj.defineNativeMethod("subarray", 2, (context, [begin, end]) => { // 1. Let O be the this value. let O = context.throwIfNotConcrete(); // 2. If Type(O) is not Object, throw a TypeError exception. if (!(O instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(O) is not Object"); } // 3. If O does not have a [[TypedArrayName]] internal slot, throw a TypeError exception. if (!("$TypedArrayName" in O)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "O does not have a [[TypedArrayName]] internal slot"); } // 4. Assert: O has a [[ViewedArrayBuffer]] internal slot. (0, _invariant2.default)(O.$ViewedArrayBuffer, "O has a [[ViewedArrayBuffer]] internal slot"); // 5. Let buffer be O.[[ViewedArrayBuffer]]. let buffer = O.$ViewedArrayBuffer; (0, _invariant2.default)(buffer); // 6. Let srcLength be O.[[ArrayLength]]. let srcLength = O.$ArrayLength; (0, _invariant2.default)(typeof srcLength === "number"); // 7. Let relativeBegin be ? ToInteger(begin). let relativeBegin = _singletons.To.ToInteger(realm, begin); // 8. If relativeBegin < 0, let beginIndex be max((srcLength + relativeBegin), 0); else let beginIndex be min(relativeBegin, srcLength). let beginIndex = relativeBegin < 0 ? Math.max(srcLength + relativeBegin, 0) : Math.min(relativeBegin, srcLength); // 9. If end is undefined, let relativeEnd be srcLength; else, let relativeEnd be ? ToInteger(end). let relativeEnd = !end || end instanceof _index.UndefinedValue ? srcLength : _singletons.To.ToInteger(realm, end.throwIfNotConcrete()); // 10. If relativeEnd < 0, let endIndex be max((srcLength + relativeEnd), 0); else let endIndex be min(relativeEnd, srcLength). let endIndex = relativeEnd < 0 ? Math.max(srcLength + relativeEnd, 0) : Math.min(relativeEnd, srcLength); // 11. Let newLength be max(endIndex - beginIndex, 0). let newLength = Math.max(endIndex - beginIndex, 0); // 12. Let constructorName be the String value of O.[[TypedArrayName]]. let constructorName = O.$TypedArrayName; (0, _invariant2.default)(typeof constructorName === "string"); // 13. Let elementSize be the Number value of the Element Size value specified in Table 50 for constructorName. let elementSize = _typedarray.ArrayElementSize[constructorName]; // 14. Let srcByteOffset be O.[[ByteOffset]]. let srcByteOffset = O.$ByteOffset; (0, _invariant2.default)(typeof srcByteOffset === "number"); // 15. Let beginByteOffset be srcByteOffset + beginIndex × elementSize. let beginByteOffset = srcByteOffset + beginIndex * elementSize; // 16. Let argumentsList be « buffer, beginByteOffset, newLength ». let argumentsList = [buffer, new _index.NumberValue(realm, beginByteOffset), new _index.NumberValue(realm, newLength)]; // 17. Return ? TypedArraySpeciesCreate(O, argumentsList). return (0, _typedarray.TypedArraySpeciesCreate)(realm, O, argumentsList); }); // ECMA262 22.2.3.28 obj.defineNativeMethod("toLocaleString", 0, context => { // 1. Let array be ? ToObject(this value). let array = _singletons.To.ToObject(realm, context.throwIfNotConcrete()); // 2. Perform ? ValidateTypedArray(array). (0, _typedarray.ValidateTypedArray)(realm, array); // 3. Let len be array.[[ArrayLength]]. let len = array.$ArrayLength; (0, _invariant2.default)(typeof len === "number"); // 4. Let separator be the String value for the list-separator String appropriate for the host environment's current locale (this is derived in an implementation-defined way). let separator = ","; // 5. If len is zero, return the empty String. if (len === 0) return realm.intrinsics.emptyString; // 6. Let firstElement be ? Get(array, "0"). let firstElement = (0, _get.Get)(realm, array, "0"); // 7. If firstElement is undefined or null, then let R; if ((0, _has.HasSomeCompatibleType)(firstElement, _index.UndefinedValue, _index.NullValue)) { // a. Let R be the empty String. R = ""; } else { // 8. Else, // a. Let R be ? ToString(? Invoke(firstElement, "toLocaleString")). R = _singletons.To.ToStringPartial(realm, (0, _call.Invoke)(realm, firstElement, "toLocaleString")); } // 9. Let k be 1. let k = 1; // 10. Repeat, while k < len while (k < len) { // a. Let S be a String value produced by concatenating R and separator. let S = R + separator; // b. Let nextElement be ? Get(array, ! ToString(k)). let nextElement = (0, _get.Get)(realm, array, new _index.StringValue(realm, k + "")); // c. If nextElement is undefined or null, then if ((0, _has.HasSomeCompatibleType)(nextElement, _index.UndefinedValue, _index.NullValue)) { // i. Let R be the empty String. R = ""; } else { // d. Else, // i. Let R be ? ToString(? Invoke(nextElement, "toLocaleString")). R = _singletons.To.ToStringPartial(realm, (0, _call.Invoke)(realm, nextElement, "toLocaleString")); } // e. Let R be a String value produced by concatenating S and R. R = S + R; // f. Increase k by 1. k++; } // 11. Return R. return new _index.StringValue(realm, R); }); // ECMA262 22.2.3.29 obj.defineNativeProperty("toString", realm.intrinsics.ArrayProto_toString); // ECMA262 22.2.3.30 obj.defineNativeProperty("values", realm.intrinsics.TypedArrayProto_values); // ECMA262 22.2.3.31 obj.defineNativeProperty(realm.intrinsics.SymbolIterator, realm.intrinsics.TypedArrayProto_values); // ECMA262 22.2.3.32 obj.defineNativeGetter(realm.intrinsics.SymbolToStringTag, context => { // 1. Let O be the this value. let O = context.throwIfNotConcrete(); // 2. If Type(O) is not Object, return undefined. if (!(O instanceof _index.ObjectValue)) return realm.intrinsics.undefined; // 3. If O does not have a [[TypedArrayName]] internal slot, return undefined. if (!("$TypedArrayName" in O)) return realm.intrinsics.undefined; // 4. Let name be O.[[TypedArrayName]]. let name = O.$TypedArrayName; // 5. Assert: name is a String value. (0, _invariant2.default)(typeof name === "string", "name is a String value"); // 6. Return name. return new _index.StringValue(realm, name); }); }; exports.build = build; var _types = __webpack_require__(322); var _index = __webpack_require__(0); var _call = __webpack_require__(30); var _get = __webpack_require__(19); var _has = __webpack_require__(42); var _is = __webpack_require__(16); var _typedarray = __webpack_require__(227); var _arraybuffer = __webpack_require__(124); var _abstract = __webpack_require__(29); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function build(realm, obj, type) { // ECMA262 22.2.6 obj.$Prototype = realm.intrinsics.TypedArrayPrototype; // ECMA262 22.2.6.1 obj.defineNativeConstant("BYTES_PER_ELEMENT", new _index.NumberValue(realm, _types.ElementSize[type])); } //# sourceMappingURL=TypedArrayPrototype.js.map /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var assert = __webpack_require__(43); var inherits = __webpack_require__(8); exports.inherits = inherits; function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg === 'string') { if (!enc) { for (var i = 0; i < msg.length; i++) { var c = msg.charCodeAt(i); var hi = c >> 8; var lo = c & 0xff; if (hi) res.push(hi, lo); else res.push(lo); } } else if (enc === 'hex') { msg = msg.replace(/[^a-z0-9]+/ig, ''); if (msg.length % 2 !== 0) msg = '0' + msg; for (i = 0; i < msg.length; i += 2) res.push(parseInt(msg[i] + msg[i + 1], 16)); } } else { for (i = 0; i < msg.length; i++) res[i] = msg[i] | 0; } return res; } exports.toArray = toArray; function toHex(msg) { var res = ''; for (var i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16)); return res; } exports.toHex = toHex; function htonl(w) { var res = (w >>> 24) | ((w >>> 8) & 0xff00) | ((w << 8) & 0xff0000) | ((w & 0xff) << 24); return res >>> 0; } exports.htonl = htonl; function toHex32(msg, endian) { var res = ''; for (var i = 0; i < msg.length; i++) { var w = msg[i]; if (endian === 'little') w = htonl(w); res += zero8(w.toString(16)); } return res; } exports.toHex32 = toHex32; function zero2(word) { if (word.length === 1) return '0' + word; else return word; } exports.zero2 = zero2; function zero8(word) { if (word.length === 7) return '0' + word; else if (word.length === 6) return '00' + word; else if (word.length === 5) return '000' + word; else if (word.length === 4) return '0000' + word; else if (word.length === 3) return '00000' + word; else if (word.length === 2) return '000000' + word; else if (word.length === 1) return '0000000' + word; else return word; } exports.zero8 = zero8; function join32(msg, start, end, endian) { var len = end - start; assert(len % 4 === 0); var res = new Array(len / 4); for (var i = 0, k = start; i < res.length; i++, k += 4) { var w; if (endian === 'big') w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; else w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; res[i] = w >>> 0; } return res; } exports.join32 = join32; function split32(msg, endian) { var res = new Array(msg.length * 4); for (var i = 0, k = 0; i < msg.length; i++, k += 4) { var m = msg[i]; if (endian === 'big') { res[k] = m >>> 24; res[k + 1] = (m >>> 16) & 0xff; res[k + 2] = (m >>> 8) & 0xff; res[k + 3] = m & 0xff; } else { res[k + 3] = m >>> 24; res[k + 2] = (m >>> 16) & 0xff; res[k + 1] = (m >>> 8) & 0xff; res[k] = m & 0xff; } } return res; } exports.split32 = split32; function rotr32(w, b) { return (w >>> b) | (w << (32 - b)); } exports.rotr32 = rotr32; function rotl32(w, b) { return (w << b) | (w >>> (32 - b)); } exports.rotl32 = rotl32; function sum32(a, b) { return (a + b) >>> 0; } exports.sum32 = sum32; function sum32_3(a, b, c) { return (a + b + c) >>> 0; } exports.sum32_3 = sum32_3; function sum32_4(a, b, c, d) { return (a + b + c + d) >>> 0; } exports.sum32_4 = sum32_4; function sum32_5(a, b, c, d, e) { return (a + b + c + d + e) >>> 0; } exports.sum32_5 = sum32_5; function sum64(buf, pos, ah, al) { var bh = buf[pos]; var bl = buf[pos + 1]; var lo = (al + bl) >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; buf[pos] = hi >>> 0; buf[pos + 1] = lo; } exports.sum64 = sum64; function sum64_hi(ah, al, bh, bl) { var lo = (al + bl) >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; return hi >>> 0; } exports.sum64_hi = sum64_hi; function sum64_lo(ah, al, bh, bl) { var lo = al + bl; return lo >>> 0; } exports.sum64_lo = sum64_lo; function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { var carry = 0; var lo = al; lo = (lo + bl) >>> 0; carry += lo < al ? 1 : 0; lo = (lo + cl) >>> 0; carry += lo < cl ? 1 : 0; lo = (lo + dl) >>> 0; carry += lo < dl ? 1 : 0; var hi = ah + bh + ch + dh + carry; return hi >>> 0; } exports.sum64_4_hi = sum64_4_hi; function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { var lo = al + bl + cl + dl; return lo >>> 0; } exports.sum64_4_lo = sum64_4_lo; function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var carry = 0; var lo = al; lo = (lo + bl) >>> 0; carry += lo < al ? 1 : 0; lo = (lo + cl) >>> 0; carry += lo < cl ? 1 : 0; lo = (lo + dl) >>> 0; carry += lo < dl ? 1 : 0; lo = (lo + el) >>> 0; carry += lo < el ? 1 : 0; var hi = ah + bh + ch + dh + eh + carry; return hi >>> 0; } exports.sum64_5_hi = sum64_5_hi; function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var lo = al + bl + cl + dl + el; return lo >>> 0; } exports.sum64_5_lo = sum64_5_lo; function rotr64_hi(ah, al, num) { var r = (al << (32 - num)) | (ah >>> num); return r >>> 0; } exports.rotr64_hi = rotr64_hi; function rotr64_lo(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } exports.rotr64_lo = rotr64_lo; function shr64_hi(ah, al, num) { return ah >>> num; } exports.shr64_hi = shr64_hi; function shr64_lo(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } exports.shr64_lo = shr64_lo; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = traverse; Object.defineProperty(exports, "NodePath", { enumerable: true, get: function () { return _path.default; } }); Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return _scope.default; } }); Object.defineProperty(exports, "Hub", { enumerable: true, get: function () { return _hub.default; } }); exports.visitors = void 0; var _context = _interopRequireDefault(__webpack_require__(723)); var visitors = _interopRequireWildcard(__webpack_require__(913)); exports.visitors = visitors; function _includes() { const data = _interopRequireDefault(__webpack_require__(107)); _includes = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(__webpack_require__(9)); t = function () { return data; }; return data; } var cache = _interopRequireWildcard(__webpack_require__(189)); var _path = _interopRequireDefault(__webpack_require__(105)); var _scope = _interopRequireDefault(__webpack_require__(388)); var _hub = _interopRequireDefault(__webpack_require__(914)); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function traverse(parent, opts, scope, state, parentPath) { if (!parent) return; if (!opts) opts = {}; if (!opts.noScope && !scope) { if (parent.type !== "Program" && parent.type !== "File") { throw new Error("You must pass a scope and parentPath unless traversing a Program/File. " + `Instead of that you tried to traverse a ${parent.type} node without ` + "passing scope and parentPath."); } } visitors.explode(opts); traverse.node(parent, opts, scope, state, parentPath); } traverse.visitors = visitors; traverse.verify = visitors.verify; traverse.explode = visitors.explode; traverse.cheap = function (node, enter) { return t().traverseFast(node, enter); }; traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { const keys = t().VISITOR_KEYS[node.type]; if (!keys) return; const context = new _context.default(scope, opts, state, parentPath); for (const key of keys) { if (skipKeys && skipKeys[key]) continue; if (context.visit(node, key)) return; } }; traverse.clearNode = function (node, opts) { t().removeProperties(node, opts); cache.path.delete(node); }; traverse.removeProperties = function (tree, opts) { t().traverseFast(tree, traverse.clearNode, opts); return tree; }; function hasBlacklistedType(path, state) { if (path.node.type === state.type) { state.has = true; path.stop(); } } traverse.hasType = function (tree, type, blacklistTypes) { if ((0, _includes().default)(blacklistTypes, tree.type)) return false; if (tree.type === type) return true; const state = { has: false, type: type }; traverse(tree, { noScope: true, blacklist: blacklistTypes, enter: hasBlacklistedType }, null, state); return state.has; }; traverse.cache = cache; /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { // This module was originally created so that Recast could add its own // custom types to the AST type system (in particular, the File type), but // those types are now incorporated into ast-types, so this module doesn't // have much to do anymore. Still, it might prove useful in the future. module.exports = __webpack_require__(1123); /***/ }), /* 68 */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__(1229)() ? Symbol : __webpack_require__(1230); /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function (fn) { if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); return fn; }; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(72); var IE8_DOM_DEFINE = __webpack_require__(591); var toPrimitive = __webpack_require__(301); var dP = Object.defineProperty; exports.f = __webpack_require__(73) ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(50); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(86)(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 74 */ /***/ (function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(106), getRawTag = __webpack_require__(740), objectToString = __webpack_require__(741); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.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 && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }), /* 76 */ /***/ (function(module, exports) { /** * 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'); } module.exports = isObject; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(356), baseKeys = __webpack_require__(763), isArrayLike = __webpack_require__(78); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } module.exports = keys; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(351), isLength = __webpack_require__(243); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } module.exports = isArrayLike; /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validate = validate; exports.typeIs = typeIs; exports.validateType = validateType; exports.validateOptional = validateOptional; exports.validateOptionalType = validateOptionalType; exports.arrayOf = arrayOf; exports.arrayOfType = arrayOfType; exports.validateArrayOfType = validateArrayOfType; exports.assertEach = assertEach; exports.assertOneOf = assertOneOf; exports.assertNodeType = assertNodeType; exports.assertNodeOrValueType = assertNodeOrValueType; exports.assertValueType = assertValueType; exports.chain = chain; exports.default = defineType; exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.FLIPPED_ALIAS_KEYS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = void 0; var _is = _interopRequireDefault(__webpack_require__(250)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const VISITOR_KEYS = {}; exports.VISITOR_KEYS = VISITOR_KEYS; const ALIAS_KEYS = {}; exports.ALIAS_KEYS = ALIAS_KEYS; const FLIPPED_ALIAS_KEYS = {}; exports.FLIPPED_ALIAS_KEYS = FLIPPED_ALIAS_KEYS; const NODE_FIELDS = {}; exports.NODE_FIELDS = NODE_FIELDS; const BUILDER_KEYS = {}; exports.BUILDER_KEYS = BUILDER_KEYS; const DEPRECATED_KEYS = {}; exports.DEPRECATED_KEYS = DEPRECATED_KEYS; function getType(val) { if (Array.isArray(val)) { return "array"; } else if (val === null) { return "null"; } else if (val === undefined) { return "undefined"; } else { return typeof val; } } function validate(validate) { return { validate }; } function typeIs(typeName) { return typeof typeName === "string" ? assertNodeType(typeName) : assertNodeType(...typeName); } function validateType(typeName) { return validate(typeIs(typeName)); } function validateOptional(validate) { return { validate, optional: true }; } function validateOptionalType(typeName) { return { validate: typeIs(typeName), optional: true }; } function arrayOf(elementType) { return chain(assertValueType("array"), assertEach(elementType)); } function arrayOfType(typeName) { return arrayOf(typeIs(typeName)); } function validateArrayOfType(typeName) { return validate(arrayOfType(typeName)); } function assertEach(callback) { function validator(node, key, val) { if (!Array.isArray(val)) return; for (let i = 0; i < val.length; i++) { callback(node, `${key}[${i}]`, val[i]); } } validator.each = callback; return validator; } function assertOneOf(...values) { function validate(node, key, val) { if (values.indexOf(val) < 0) { throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`); } } validate.oneOf = values; return validate; } function assertNodeType(...types) { function validate(node, key, val) { let valid = false; for (const type of types) { if ((0, _is.default)(type, val)) { valid = true; break; } } if (!valid) { throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} ` + `but instead got ${JSON.stringify(val && val.type)}`); } } validate.oneOfNodeTypes = types; return validate; } function assertNodeOrValueType(...types) { function validate(node, key, val) { let valid = false; for (const type of types) { if (getType(val) === type || (0, _is.default)(type, val)) { valid = true; break; } } if (!valid) { throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} ` + `but instead got ${JSON.stringify(val && val.type)}`); } } validate.oneOfNodeOrValueTypes = types; return validate; } function assertValueType(type) { function validate(node, key, val) { const valid = getType(val) === type; if (!valid) { throw new TypeError(`Property ${key} expected type of ${type} but got ${getType(val)}`); } } validate.type = type; return validate; } function chain(...fns) { function validate(...args) { for (const fn of fns) { fn(...args); } } validate.chainOf = fns; return validate; } function defineType(type, opts = {}) { const inherits = opts.inherits && store[opts.inherits] || {}; const fields = opts.fields || inherits.fields || {}; const visitor = opts.visitor || inherits.visitor || []; const aliases = opts.aliases || inherits.aliases || []; const builder = opts.builder || inherits.builder || opts.visitor || []; if (opts.deprecatedAlias) { DEPRECATED_KEYS[opts.deprecatedAlias] = type; } for (const key of visitor.concat(builder)) { fields[key] = fields[key] || {}; } for (const key in fields) { const field = fields[key]; if (builder.indexOf(key) === -1) { field.optional = true; } if (field.default === undefined) { field.default = null; } else if (!field.validate) { field.validate = assertValueType(getType(field.default)); } } VISITOR_KEYS[type] = opts.visitor = visitor; BUILDER_KEYS[type] = opts.builder = builder; NODE_FIELDS[type] = opts.fields = fields; ALIAS_KEYS[type] = opts.aliases = aliases; aliases.forEach(alias => { FLIPPED_ALIAS_KEYS[alias] = FLIPPED_ALIAS_KEYS[alias] || []; FLIPPED_ALIAS_KEYS[alias].push(type); }); store[type] = opts; } const store = {}; /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { module.exports = function (fork) { var exports = {}; var types = fork.use(__webpack_require__(32)); var Type = types.Type; var builtin = types.builtInTypes; var isNumber = builtin.number; // An example of constructing a new type with arbitrary constraints from // an existing type. exports.geq = function (than) { return new Type(function (value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than); }; // Default value-returning functions that may optionally be passed as a // third argument to Def.prototype.field. exports.defaults = { // Functions were used because (among other reasons) that's the most // elegant way to allow for the emptyArray one always to give a new // array instance. "null": function () { return null }, "emptyArray": function () { return [] }, "false": function () { return false }, "true": function () { return true }, "undefined": function () {} }; var naiveIsPrimitive = Type.or( builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined ); exports.isPrimitive = new Type(function (value) { if (value === null) return true; var type = typeof value; return !(type === "object" || type === "function"); }, naiveIsPrimitive.toString()); return exports; }; /***/ }), /* 81 */ /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @abstract BaseSyntax */ var BaseSyntax = /** * The constructor of BaseSyntax * * @param {String} type */ function BaseSyntax(type) { _classCallCheck(this, BaseSyntax); this.type = type; }; exports.default = BaseSyntax; module.exports = exports["default"]; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var assign = __webpack_require__(281) , normalizeOpts = __webpack_require__(488) , isCallable = __webpack_require__(1225) , contains = __webpack_require__(489) , d; d = module.exports = function (dscr, value/*, options*/) { var c, e, w, options, desc; if ((arguments.length < 2) || (typeof dscr !== 'string')) { options = value; value = dscr; dscr = null; } else { options = arguments[2]; } if (dscr == null) { c = w = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); w = contains.call(dscr, 'w'); } desc = { value: value, configurable: c, enumerable: e, writable: w }; return !options ? desc : assign(normalizeOpts(options), desc); }; d.gs = function (dscr, get, set/*, options*/) { var c, e, options, desc; if (typeof dscr !== 'string') { options = set; set = get; get = dscr; dscr = null; } else { options = arguments[3]; } if (get == null) { get = undefined; } else if (!isCallable(get)) { options = get; get = set = undefined; } else if (set == null) { set = undefined; } else if (!isCallable(set)) { options = set; set = undefined; } if (dscr == null) { c = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); } desc = { get: get, set: set, configurable: c, enumerable: e }; return !options ? desc : assign(normalizeOpts(options), desc); }; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _iterator = __webpack_require__(1814); var _iterator2 = _interopRequireDefault(_iterator); var _symbol = __webpack_require__(595); var _symbol2 = _interopRequireDefault(_symbol); var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : _typeof(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); }; /***/ }), /* 85 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(71); var createDesc = __webpack_require__(215); module.exports = __webpack_require__(73) ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /* 86 */ /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /* 87 */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = undefined; var _getIterator2 = __webpack_require__(21); var _getIterator3 = _interopRequireDefault(_getIterator2); var _stringify = __webpack_require__(158); var _stringify2 = _interopRequireDefault(_stringify); var _typeof2 = __webpack_require__(84); var _typeof3 = _interopRequireDefault(_typeof2); exports.assertEach = assertEach; exports.assertOneOf = assertOneOf; exports.assertNodeType = assertNodeType; exports.assertNodeOrValueType = assertNodeOrValueType; exports.assertValueType = assertValueType; exports.chain = chain; exports.default = defineType; var _index = __webpack_require__(4); var t = _interopRequireWildcard(_index); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var VISITOR_KEYS = exports.VISITOR_KEYS = {}; var ALIAS_KEYS = exports.ALIAS_KEYS = {}; var NODE_FIELDS = exports.NODE_FIELDS = {}; var BUILDER_KEYS = exports.BUILDER_KEYS = {}; var DEPRECATED_KEYS = exports.DEPRECATED_KEYS = {}; function getType(val) { if (Array.isArray(val)) { return "array"; } else if (val === null) { return "null"; } else if (val === undefined) { return "undefined"; } else { return typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val); } } function assertEach(callback) { function validator(node, key, val) { if (!Array.isArray(val)) return; for (var i = 0; i < val.length; i++) { callback(node, key + "[" + i + "]", val[i]); } } validator.each = callback; return validator; } function assertOneOf() { for (var _len = arguments.length, vals = Array(_len), _key = 0; _key < _len; _key++) { vals[_key] = arguments[_key]; } function validate(node, key, val) { if (vals.indexOf(val) < 0) { throw new TypeError("Property " + key + " expected value to be one of " + (0, _stringify2.default)(vals) + " but got " + (0, _stringify2.default)(val)); } } validate.oneOf = vals; return validate; } function assertNodeType() { for (var _len2 = arguments.length, types = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { types[_key2] = arguments[_key2]; } function validate(node, key, val) { var valid = false; for (var _iterator = types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var type = _ref; if (t.is(type, val)) { valid = true; break; } } if (!valid) { throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); } } validate.oneOfNodeTypes = types; return validate; } function assertNodeOrValueType() { for (var _len3 = arguments.length, types = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { types[_key3] = arguments[_key3]; } function validate(node, key, val) { var valid = false; for (var _iterator2 = types, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var type = _ref2; if (getType(val) === type || t.is(type, val)) { valid = true; break; } } if (!valid) { throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); } } validate.oneOfNodeOrValueTypes = types; return validate; } function assertValueType(type) { function validate(node, key, val) { var valid = getType(val) === type; if (!valid) { throw new TypeError("Property " + key + " expected type of " + type + " but got " + getType(val)); } } validate.type = type; return validate; } function chain() { for (var _len4 = arguments.length, fns = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { fns[_key4] = arguments[_key4]; } function validate() { for (var _iterator3 = fns, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { var _ref3; if (_isArray3) { if (_i3 >= _iterator3.length) break; _ref3 = _iterator3[_i3++]; } else { _i3 = _iterator3.next(); if (_i3.done) break; _ref3 = _i3.value; } var fn = _ref3; fn.apply(undefined, arguments); } } validate.chainOf = fns; return validate; } function defineType(type) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var inherits = opts.inherits && store[opts.inherits] || {}; opts.fields = opts.fields || inherits.fields || {}; opts.visitor = opts.visitor || inherits.visitor || []; opts.aliases = opts.aliases || inherits.aliases || []; opts.builder = opts.builder || inherits.builder || opts.visitor || []; if (opts.deprecatedAlias) { DEPRECATED_KEYS[opts.deprecatedAlias] = type; } for (var _iterator4 = opts.visitor.concat(opts.builder), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { var _ref4; if (_isArray4) { if (_i4 >= _iterator4.length) break; _ref4 = _iterator4[_i4++]; } else { _i4 = _iterator4.next(); if (_i4.done) break; _ref4 = _i4.value; } var _key5 = _ref4; opts.fields[_key5] = opts.fields[_key5] || {}; } for (var key in opts.fields) { var field = opts.fields[key]; if (opts.builder.indexOf(key) === -1) { field.optional = true; } if (field.default === undefined) { field.default = null; } else if (!field.validate) { field.validate = assertValueType(getType(field.default)); } } VISITOR_KEYS[type] = opts.visitor; BUILDER_KEYS[type] = opts.builder; NODE_FIELDS[type] = opts.fields; ALIAS_KEYS[type] = opts.aliases; store[type] = opts; } var store = {}; /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Modules = exports.ModuleTracer = undefined; var _environment = __webpack_require__(12); var _errors = __webpack_require__(6); var _realm = __webpack_require__(11); var _index = __webpack_require__(5); var _completions = __webpack_require__(3); var _singletons = __webpack_require__(2); var _index2 = __webpack_require__(0); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _logger = __webpack_require__(61); var _types = __webpack_require__(54); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function downgradeErrorsToWarnings(realm, f) { let savedHandler = realm.errorHandler; function handler(e) { e.severity = "Warning"; realm.errorHandler = savedHandler; try { return realm.handleError(e); } finally { realm.errorHandler = handler; } } realm.errorHandler = handler; try { return f(); } finally { realm.errorHandler = savedHandler; } } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ class ModuleTracer extends _realm.Tracer { constructor(modules, statistics, logModules) { super(); this.modules = modules; this.evaluateForEffectsNesting = 0; this.requireStack = []; this.requireSequence = []; this.logModules = logModules; this.uninitializedModuleIdsRequiredInEvaluateForEffects = new Set(); this.statistics = statistics; } // We can't say that a module has been initialized if it was initialized in a // evaluate for effects context until we know the effects are applied. log(message) { if (this.logModules) console.log(`[modules] ${this.requireStack.map(_ => " ").join("")}${message}`); } beginEvaluateForEffects(state) { if (state !== this) { this.log(">evaluate for effects"); this.evaluateForEffectsNesting++; this.requireStack.push(undefined); } } endEvaluateForEffects(state, effects) { if (state !== this) { let popped = this.requireStack.pop(); (0, _invariant2.default)(popped === undefined); this.evaluateForEffectsNesting--; this.log(" performCall(), this); } catch (e) { e; } acceleratedModuleIds = []; if (isTopLevelRequire && effects !== undefined && !(effects[0] instanceof _completions.AbruptCompletion)) { // We gathered all effects, but didn't apply them yet. // Let's check if there was any call to `require` in a // evaluate-for-effects context. If so, try to initialize // that module right now. Acceleration module initialization in this // way might not actually be desirable, but it works around // general prepack-limitations around joined abstract values involving // conditionals. Long term, Prepack needs to implement a notion of refinement // of conditional abstract values under the known path condition. // Example: // if (*) require(1); else require(2); // let x = require(1).X; // => // require(1); // require(2); // if (*) require(1); else require(2); // let x = require(1).X; for (let nestedModuleId of this.uninitializedModuleIdsRequiredInEvaluateForEffects) { let nestedEffects = this.modules.tryInitializeModule(nestedModuleId, `accelerated initialization of conditional module ${nestedModuleId} as it's required in an evaluate-for-effects context by module ${moduleIdValue}`); if (this.modules.accelerateUnsupportedRequires && nestedEffects !== undefined && nestedEffects[0] instanceof _index2.Value && this.modules.isModuleInitialized(nestedModuleId)) { acceleratedModuleIds.push(nestedModuleId); } } this.uninitializedModuleIdsRequiredInEvaluateForEffects.clear(); // Keep restarting for as long as we find additional modules to accelerate. if (acceleratedModuleIds.length > 0) { console.log(`restarting require(${moduleIdValue}) after accelerating conditional require calls for ${acceleratedModuleIds.join()}`); this.statistics.acceleratedModules += acceleratedModuleIds.length; } } } while (acceleratedModuleIds.length > 0); return effects; } // If a require fails, recover from it and delay the factory call until runtime // Also, only in this mode, consider "accelerating" require calls, see below. _callRequireAndDelayIfNeeded(moduleIdValue, performCall) { let realm = this.modules.realm; this.log(`>require(${moduleIdValue})`); let isTopLevelRequire = this.requireStack.length === 0; if (this.evaluateForEffectsNesting > 0) { if (isTopLevelRequire) { let diagnostic = new _errors.CompilerDiagnostic("Non-deterministically conditional top-level require not currently supported", realm.currentLocation, "PP0017", "FatalError"); realm.handleError(diagnostic); throw new _errors.FatalError(); } else if (!this.modules.isModuleInitialized(moduleIdValue)) // Nested require call: We record that this happened. Just so that // if we discover later this this require call needs to get delayed, // then we still know (some of) which modules it in turn required, // and then we'll later "accelerate" requiring them to preserve the // require ordering. See below for more details on acceleration. this.uninitializedModuleIdsRequiredInEvaluateForEffects.add(moduleIdValue); return undefined; } else { return downgradeErrorsToWarnings(realm, () => { let result; try { this.requireStack.push(moduleIdValue); let requireSequenceStart = this.requireSequence.length; this.requireSequence.push(moduleIdValue); const previousNumDelayedModules = this.statistics.delayedModules; let effects = this._callRequireAndAccelerate(isTopLevelRequire, moduleIdValue, performCall); if (effects === undefined || effects[0] instanceof _completions.AbruptCompletion) { console.log(`delaying require(${moduleIdValue})`); this.statistics.delayedModules = previousNumDelayedModules + 1; // So we are about to emit a delayed require(...) call. // However, before we do that, let's try to require all modules that we // know this delayed require call will require. // This way, we ensure that those modules will be fully initialized // before the require call executes. // TODO #690: More needs to be done to make the delayUnsupportedRequires // feature completely safe. Open issues are: // 1) Side-effects on the heap of delayed factory functions are not discovered or rejected. // 2) While we do process an appropriate list of transitively required modules here, // it's likely just a subset / prefix of all transivitely required modules, as // more modules would have been required if the Introspection exception had not been thrown. // To be correct, those modules would have to be prepacked here as well. // TODO #798: Watch out for an upcoming change to the __d module declaration where the statically known // list of dependencies will be announced, so we'll no longer have to guess. let nestedModulesIds = new Set(); for (let i = requireSequenceStart; i < this.requireSequence.length; i++) { let nestedModuleId = this.requireSequence[i]; if (nestedModulesIds.has(nestedModuleId)) continue; nestedModulesIds.add(nestedModuleId); this.modules.tryInitializeModule(nestedModuleId, `initialization of module ${nestedModuleId} as it's required by module ${moduleIdValue}`); } result = _index2.AbstractValue.createTemporalFromBuildFunction(realm, _index2.Value, [], ([]) => t.callExpression(t.identifier("require"), [t.valueToNode(moduleIdValue)])); } else { result = effects[0]; if (result instanceof _index2.Value) { realm.applyEffects(effects, `initialization of module ${moduleIdValue}`); this.modules.recordModuleInitialized(moduleIdValue, result); } else if (result instanceof _completions.PossiblyNormalCompletion) { let warning = new _errors.CompilerDiagnostic("Module import may fail with an exception", result.location, "PP0018", "Warning"); realm.handleError(warning); result = result.value; realm.applyEffects(effects, `initialization of module ${moduleIdValue}`); } else { (0, _invariant2.default)(false); } } } finally { let popped = this.requireStack.pop(); (0, _invariant2.default)(popped === moduleIdValue); this.log(` (0, _index.Get)(realm, value, "" + i), realm.intrinsics.undefined); dependencies.push(elementValue); } return dependencies; } } return undefined; } detourCall(F, thisArgument, argumentsList, newTarget, performCall) { if (F === this.modules.getRequire() && !this.modules.disallowDelayingRequiresOverride && argumentsList.length === 1) { // Here, we handle calls of the form // require(42) let moduleId = argumentsList[0]; let moduleIdValue; // Do some sanity checks and request require(...) calls with bad arguments if (moduleId instanceof _index2.NumberValue || moduleId instanceof _index2.StringValue) { moduleIdValue = moduleId.value; if (!this.modules.moduleIds.has(moduleIdValue) && this.modules.delayUnsupportedRequires) { this.modules.logger.logError(moduleId, "Module referenced by require call has not been defined."); } } else { if (this.modules.delayUnsupportedRequires) { this.modules.logger.logError(moduleId, "First argument to require function is not a number or string value."); } return undefined; } if (this.modules.delayUnsupportedRequires) return this._callRequireAndDelayIfNeeded(moduleIdValue, performCall);else return this._callRequireAndRecord(moduleIdValue, performCall); } else if (F === this.modules.getDefine()) { // Here, we handle calls of the form // __d(factoryFunction, moduleId, dependencyArray) if (this.evaluateForEffectsNesting !== 0) this.modules.logger.logError(F, "Defining a module in nested partial evaluation is not supported."); let factoryFunction = argumentsList[0]; if (factoryFunction instanceof _index2.FunctionValue) { let dependencies = this._tryExtractDependencies(argumentsList[2]); if (dependencies !== undefined) this.modules.factoryFunctionDependencies.set(factoryFunction, dependencies);else this.modules.logger.logError(argumentsList[2], "Third argument to define function is present but not a concrete array."); } else this.modules.logger.logError(factoryFunction, "First argument to define function is not a function value."); let moduleId = argumentsList[1]; if (moduleId instanceof _index2.NumberValue || moduleId instanceof _index2.StringValue) this.modules.moduleIds.add(moduleId.value);else this.modules.logger.logError(moduleId, "Second argument to define function is not a number or string value."); } return undefined; } } exports.ModuleTracer = ModuleTracer; class Modules { constructor(realm, logger, statistics, logModules, delayUnsupportedRequires, accelerateUnsupportedRequires) { this.realm = realm; this.logger = logger; this._require = realm.intrinsics.undefined; this._define = realm.intrinsics.undefined; this.factoryFunctionDependencies = new Map(); this.moduleIds = new Set(); this.initializedModules = new Map(); realm.tracers.push(this.moduleTracer = new ModuleTracer(this, statistics, logModules)); this.delayUnsupportedRequires = delayUnsupportedRequires; this.accelerateUnsupportedRequires = accelerateUnsupportedRequires; this.disallowDelayingRequiresOverride = false; } resolveInitializedModules() { this.initializedModules.clear(); let globalInitializedModulesMap = this._getGlobalProperty("__initializedModules"); (0, _invariant2.default)(globalInitializedModulesMap instanceof _index2.ObjectValue); for (let moduleId of globalInitializedModulesMap.properties.keys()) { let property = globalInitializedModulesMap.properties.get(moduleId); (0, _invariant2.default)(property); let moduleValue = property.descriptor && property.descriptor.value; if (moduleValue instanceof _index2.Value) this.initializedModules.set(moduleId, moduleValue); } } _getGlobalProperty(name) { if (this.active) return this.realm.intrinsics.undefined; this.active = true; try { let realm = this.realm; return this.logger.tryQuery(() => (0, _index.Get)(realm, realm.$GlobalObject, name), realm.intrinsics.undefined); } finally { this.active = false; } } getRequire() { if (!(this._require instanceof _index2.FunctionValue)) this._require = this._getGlobalProperty("require"); return this._require; } getDefine() { if (!(this._define instanceof _index2.FunctionValue)) this._define = this._getGlobalProperty("__d"); return this._define; } // Returns a function that checks if a call node represents a call to a // known require function, and if so, what module id that call indicates. // A known require function call is either of the form // ... require(42) ... // where require resolves to the global require function, or // factoryFunction(, require, , , dependencies) { // ... // ... require(dependencies[3]) ... // where factoryFunction and dependencies were announced as part of the // global code execution via a global module declaration call such as // global.__d(factoryFunction, , [0,2,4,6,8]) getGetModuleIdIfNodeIsRequireFunction(formalParameters, functions) { let realm = this.realm; let logger = this.logger; let modules = this; return (scope, node) => { // Are we calling a function that has a single name and a single argument? if (!t.isIdentifier(node.callee) || node.arguments.length !== 1) return undefined; let argument = node.arguments[0]; if (!argument) return undefined; if (!t.isNumericLiteral(argument) && !t.isStringLiteral(argument) && !t.isMemberExpression(argument)) return undefined; (0, _invariant2.default)(node.callee); let innerName = node.callee.name; let moduleId; // Helper function used to give up if we ever come up with different module ids for different functions let updateModuleId = newModuleId => { if (moduleId !== undefined && moduleId !== newModuleId) return false; moduleId = newModuleId; return true; }; // Helper function that retrieves module id from call argument, possibly chasing dependency array indirection const getModuleId = dependencies => { if (t.isMemberExpression(argument)) { if (dependencies !== undefined) { let memberExpression = argument; if (t.isIdentifier(memberExpression.object)) { let scopedBinding = scope.getBinding(memberExpression.object.name); if (scopedBinding && formalParameters[4] === scopedBinding.path.node) { if (t.isNumericLiteral(memberExpression.property)) { let dependencyIndex = memberExpression.property.value; if (Number.isInteger(dependencyIndex) && dependencyIndex >= 0 && dependencyIndex < dependencies.length) { let dependency = dependencies[dependencyIndex]; if (dependency instanceof _index2.NumberValue || dependency instanceof _index2.StringValue) return dependency.value; } } } } } } else { return argument.value; } }; // Let's consider each of the function instances (closures for the same code) for (let f of functions) { // 1. Let's check if we have a match for a factory function like // factoryFunction(, require, , , [dependencies]) // which is used with the Metro bundler let scopedBinding = scope.getBinding(innerName); if (scopedBinding) { let dependencies = modules.factoryFunctionDependencies.get(f); if (dependencies !== undefined && formalParameters[1] === scopedBinding.path.node) { (0, _invariant2.default)(scopedBinding.kind === "param"); let newModuleId = getModuleId(dependencies); if (newModuleId !== undefined && !updateModuleId(newModuleId)) return undefined; continue; } // The name binds to some local entity, but nothing we'd know what exactly it is return undefined; } // 2. Let's check if we can resolve the called function just by looking at the // function instance environment. // TODO: We should not do this if the current node is in a nested function! // We won't have a dependency map here, so this only works for literal arguments. if (!t.isNumericLiteral(argument) && !t.isStringLiteral(argument)) return undefined; let doesNotMatter = true; let reference = logger.tryQuery(() => _singletons.Environment.ResolveBinding(realm, innerName, doesNotMatter, f.$Environment), undefined); if (reference === undefined) { // We couldn't resolve as we came across some behavior that we cannot deal with abstractly return undefined; } if (_singletons.Environment.IsUnresolvableReference(realm, reference)) return undefined; let referencedBase = reference.base; let referencedName = reference.referencedName; if (typeof referencedName !== "string") return undefined; let value; if (reference.base instanceof _environment.GlobalEnvironmentRecord) { value = logger.tryQuery(() => (0, _index.Get)(realm, realm.$GlobalObject, innerName), realm.intrinsics.undefined); } else { (0, _invariant2.default)(referencedBase instanceof _environment.DeclarativeEnvironmentRecord); let binding = referencedBase.bindings[referencedName]; if (!binding.initialized) return undefined; value = binding.value; } if (value !== modules.getRequire()) return undefined; const newModuleId = getModuleId(); (0, _invariant2.default)(newModuleId !== undefined); if (!updateModuleId(newModuleId)) return undefined; } return moduleId; }; } recordModuleInitialized(moduleId, value) { this.realm.assignToGlobal(t.memberExpression(t.memberExpression(t.identifier("global"), t.identifier("__initializedModules")), t.identifier("" + moduleId)), value); } tryInitializeModule(moduleId, message) { let realm = this.realm; let previousDisallowDelayingRequiresOverride = this.disallowDelayingRequiresOverride; this.disallowDelayingRequiresOverride = true; return downgradeErrorsToWarnings(realm, () => { try { let node = t.callExpression(t.identifier("require"), [t.valueToNode(moduleId)]); let effects = realm.evaluateNodeForEffectsInGlobalEnv(node); realm.applyEffects(effects, message); return effects; } catch (err) { if (err instanceof _errors.FatalError) return undefined;else throw err; } finally { this.disallowDelayingRequiresOverride = previousDisallowDelayingRequiresOverride; } }); } initializeMoreModules() { // partially evaluate all factory methods by calling require let count = 0; for (let moduleId of this.moduleIds) { if (this.initializedModules.has(moduleId)) continue; let effects = this.tryInitializeModule(moduleId, `Speculative initialization of module ${moduleId}`); if (effects === undefined) continue; let result = effects[0]; if (!(result instanceof _index2.Value)) continue; // module might throw count++; this.initializedModules.set(moduleId, result); } if (count > 0) console.log(`=== speculatively initialized ${count} additional modules`); } isModuleInitialized(moduleId) { let realm = this.realm; let oldReadOnly = realm.setReadOnly(true); let oldDisallowDelayingRequiresOverride = this.disallowDelayingRequiresOverride; this.disallowDelayingRequiresOverride = true; try { let node = t.callExpression(t.identifier("require"), [t.valueToNode(moduleId)]); let [compl, generator, bindings, properties, createdObjects] = realm.evaluateNodeForEffectsInGlobalEnv(node); // for lint unused (0, _invariant2.default)(bindings); if (compl instanceof _completions.AbruptCompletion) return undefined; (0, _invariant2.default)(compl instanceof _index2.Value); if (!generator.empty() || compl instanceof _index2.ObjectValue && createdObjects.has(compl)) return undefined; // Check for escaping property assignments, if none escape, we got an existing object let escapes = false; for (let [binding] of properties) { let object = binding.object; (0, _invariant2.default)(object instanceof _index2.ObjectValue); if (!createdObjects.has(object)) escapes = true; } if (escapes) return undefined; return compl; } catch (err) { if (err instanceof _errors.FatalError) return undefined; throw err; } finally { realm.setReadOnly(oldReadOnly); this.disallowDelayingRequiresOverride = oldDisallowDelayingRequiresOverride; } } } exports.Modules = Modules; //# sourceMappingURL=modules.js.map /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = IsStrict; function IsStrict(node) { if (node.strict) return true; if (node.type !== "BlockStatement" && node.type !== "Program") return false; let directives = node.directives; if (!directives) return false; return directives.some(directive => { if (directive.type !== "Directive") { return false; } if (directive.value.type !== "DirectiveLiteral") { return false; } return directive.value.value === "use strict"; }); } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ //# sourceMappingURL=strict.js.map /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { var Buffer = __webpack_require__(15).Buffer var Transform = __webpack_require__(126).Transform var StringDecoder = __webpack_require__(333).StringDecoder var inherits = __webpack_require__(8) function CipherBase (hashMode) { Transform.call(this) this.hashMode = typeof hashMode === 'string' if (this.hashMode) { this[hashMode] = this._finalOrDigest } else { this.final = this._finalOrDigest } if (this._final) { this.__final = this._final this._final = null } this._decoder = null this._encoding = null } inherits(CipherBase, Transform) CipherBase.prototype.update = function (data, inputEnc, outputEnc) { if (typeof data === 'string') { data = Buffer.from(data, inputEnc) } var outData = this._update(data) if (this.hashMode) return this if (outputEnc) { outData = this._toString(outData, outputEnc) } return outData } CipherBase.prototype.setAutoPadding = function () {} CipherBase.prototype.getAuthTag = function () { throw new Error('trying to get auth tag in unsupported state') } CipherBase.prototype.setAuthTag = function () { throw new Error('trying to set auth tag in unsupported state') } CipherBase.prototype.setAAD = function () { throw new Error('trying to set aad in unsupported state') } CipherBase.prototype._transform = function (data, _, next) { var err try { if (this.hashMode) { this._update(data) } else { this.push(this._update(data)) } } catch (e) { err = e } finally { next(err) } } CipherBase.prototype._flush = function (done) { var err try { this.push(this.__final()) } catch (e) { err = e } done(err) } CipherBase.prototype._finalOrDigest = function (outputEnc) { var outData = this.__final() || Buffer.alloc(0) if (outputEnc) { outData = this._toString(outData, outputEnc, true) } return outData } CipherBase.prototype._toString = function (value, enc, fin) { if (!this._decoder) { this._decoder = new StringDecoder(enc) this._encoding = enc } if (this._encoding !== enc) throw new Error('can\'t switch encodings') var out = this._decoder.write(value) if (fin) { out += this._decoder.end() } return out } module.exports = CipherBase /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(739), getValue = __webpack_require__(744); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } module.exports = getNative; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = void 0; const STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; exports.STATEMENT_OR_BLOCK_KEYS = STATEMENT_OR_BLOCK_KEYS; const FLATTENABLE_KEYS = ["body", "expressions"]; exports.FLATTENABLE_KEYS = FLATTENABLE_KEYS; const FOR_INIT_KEYS = ["left", "init"]; exports.FOR_INIT_KEYS = FOR_INIT_KEYS; const COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; exports.COMMENT_KEYS = COMMENT_KEYS; const LOGICAL_OPERATORS = ["||", "&&", "??"]; exports.LOGICAL_OPERATORS = LOGICAL_OPERATORS; const UPDATE_OPERATORS = ["++", "--"]; exports.UPDATE_OPERATORS = UPDATE_OPERATORS; const BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; exports.BOOLEAN_NUMBER_BINARY_OPERATORS = BOOLEAN_NUMBER_BINARY_OPERATORS; const EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; exports.EQUALITY_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS; const COMPARISON_BINARY_OPERATORS = [...EQUALITY_BINARY_OPERATORS, "in", "instanceof"]; exports.COMPARISON_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS; const BOOLEAN_BINARY_OPERATORS = [...COMPARISON_BINARY_OPERATORS, ...BOOLEAN_NUMBER_BINARY_OPERATORS]; exports.BOOLEAN_BINARY_OPERATORS = BOOLEAN_BINARY_OPERATORS; const NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; exports.NUMBER_BINARY_OPERATORS = NUMBER_BINARY_OPERATORS; const BINARY_OPERATORS = ["+", ...NUMBER_BINARY_OPERATORS, ...BOOLEAN_BINARY_OPERATORS]; exports.BINARY_OPERATORS = BINARY_OPERATORS; const BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; exports.BOOLEAN_UNARY_OPERATORS = BOOLEAN_UNARY_OPERATORS; const NUMBER_UNARY_OPERATORS = ["+", "-", "~"]; exports.NUMBER_UNARY_OPERATORS = NUMBER_UNARY_OPERATORS; const STRING_UNARY_OPERATORS = ["typeof"]; exports.STRING_UNARY_OPERATORS = STRING_UNARY_OPERATORS; const UNARY_OPERATORS = ["void", "throw", ...BOOLEAN_UNARY_OPERATORS, ...NUMBER_UNARY_OPERATORS, ...STRING_UNARY_OPERATORS]; exports.UNARY_OPERATORS = UNARY_OPERATORS; const INHERIT_KEYS = { optional: ["typeAnnotation", "typeParameters", "returnType"], force: ["start", "loc", "end"] }; exports.INHERIT_KEYS = INHERIT_KEYS; const BLOCK_SCOPED_SYMBOL = Symbol.for("var used to be block scoped"); exports.BLOCK_SCOPED_SYMBOL = BLOCK_SCOPED_SYMBOL; const NOT_LOCAL_BINDING = Symbol.for("should not be considered a local binding"); exports.NOT_LOCAL_BINDING = NOT_LOCAL_BINDING; /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } module.exports = function evaluate(path, { tdz = false } = {}) { if (!tdz && !path.isReferencedIdentifier()) { return baseEvaluate(path); } if (path.isReferencedIdentifier()) { return evaluateIdentifier(path); } const state = { confident: true }; // prepare path.traverse({ Scope(scopePath) { scopePath.skip(); }, ReferencedIdentifier(idPath) { const binding = idPath.scope.getBinding(idPath.node.name); // don't deopt globals // let babel take care of it if (!binding) return; const evalResult = evaluateIdentifier(idPath); if (!evalResult.confident) { state.confident = evalResult.confident; state.deoptPath = evalResult.deoptPath; } } }); if (!state.confident) { return state; } return baseEvaluate(path); }; function baseEvaluate(path) { try { return path.evaluate(); } catch (e) { return { confident: false, error: e }; } } // Original Source: // https://github.com/babel/babel/blob/master/packages/babel-traverse/src/path/evaluation.js // modified for Babel-minify use function evaluateIdentifier(path) { if (!path.isReferencedIdentifier()) { throw new Error(`Expected ReferencedIdentifier. Got ${path.type}`); } const node = path.node; const binding = path.scope.getBinding(node.name); if (!binding) { const name = node.name; if (!name) { return deopt(path); } switch (name) { case "undefined": return { confident: true, value: undefined }; case "NaN": return { confident: true, value: NaN }; case "Infinity": return { confident: true, value: Infinity }; default: return deopt(path); } } if (binding.constantViolations.length > 0) { return deopt(binding.path); } // referenced in a different scope - deopt if (shouldDeoptBasedOnScope(binding, path)) { return deopt(path); } // let/var/const referenced before init // or "var" referenced in an outer scope const flowEvalResult = evaluateBasedOnControlFlow(binding, path); if (flowEvalResult.confident) { return flowEvalResult; } if (flowEvalResult.shouldDeopt) { return deopt(path); } return path.evaluate(); } // check if referenced in a different fn scope // we can't determine if this function is called sync or async // if the binding is in program scope // all it's references inside a different function should be deopted function shouldDeoptBasedOnScope(binding, refPath) { if (binding.scope.path.isProgram() && refPath.scope !== binding.scope) { return true; } return false; } function evaluateBasedOnControlFlow(binding, refPath) { if (binding.kind === "var") { // early-exit const declaration = binding.path.parentPath; /** * Handle when binding is created inside a parent block and * the corresponding parent is removed by other plugins * if (false) { var a } -> var a */ if (declaration.parentPath && declaration.parentPath.removed) { return { confident: true, value: void 0 }; } if (declaration.parentPath.isIfStatement() || declaration.parentPath.isLoop() || declaration.parentPath.isSwitchCase()) { return { shouldDeopt: true }; } const fnParent = (binding.path.scope.getFunctionParent() || binding.path.scope.getProgramParent()).path; let blockParent = binding.path.scope.getBlockParent().path; if (blockParent === fnParent && !fnParent.isProgram()) { blockParent = blockParent.get("body"); } // detect Usage Outside Init Scope const blockBody = blockParent.get("body"); if (Array.isArray(blockBody) && !blockBody.some(stmt => stmt.isAncestor(refPath))) { return { shouldDeopt: true }; } // Detect usage before init const stmts = fnParent.isProgram() ? fnParent.get("body") : fnParent.get("body").get("body"); const compareResult = compareBindingAndReference({ binding, refPath, stmts }); if (compareResult.reference && compareResult.binding) { if (compareResult.reference.scope === "current" && compareResult.reference.idx < compareResult.binding.idx) { return { confident: true, value: void 0 }; } } } else if (binding.kind === "let" || binding.kind === "const") { // binding.path is the declarator const declarator = binding.path; const declaration = declarator.parentPath; if (declaration.parentPath && (declaration.parentPath.isIfStatement() || declaration.parentPath.isLoop() || declaration.parentPath.isSwitchCase())) { return { shouldDeopt: true }; } let scopePath = declarator.scope.path; if (scopePath.isFunction() || scopePath.isCatchClause()) { scopePath = scopePath.get("body"); } // Detect Usage before Init let stmts = scopePath.get("body"); if (!Array.isArray(stmts)) { stmts = [stmts]; } const compareResult = compareBindingAndReference({ binding, refPath, stmts }); if (compareResult.reference && compareResult.binding) { if (compareResult.reference.scope === "current" && compareResult.reference.idx < compareResult.binding.idx) { throw new Error(`ReferenceError: Used ${refPath.node.name}: ` + `${binding.kind} binding before declaration`); } if (compareResult.reference.scope === "other") { return { shouldDeopt: true }; } } } return { confident: false, shouldDeopt: false }; } function compareBindingAndReference({ binding, refPath, stmts }) { const state = { binding: null, reference: null }; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = stmts.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { const _step$value = _slicedToArray(_step.value, 2), idx = _step$value[0], stmt = _step$value[1]; if (stmt.isAncestor(binding.path)) { state.binding = { idx }; } var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = binding.referencePaths[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { const ref = _step2.value; if (ref === refPath && stmt.isAncestor(ref)) { state.reference = { idx, scope: binding.path.scope === ref.scope ? "current" : "other" }; break; } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return != null) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return state; } function deopt(deoptPath) { return { confident: false, deoptPath }; } /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { /*! * chai * Copyright(c) 2011-2014 Jake Luer * MIT Licensed */ var used = []; /*! * Chai version */ exports.version = '4.1.2'; /*! * Assertion Error */ exports.AssertionError = __webpack_require__(436); /*! * Utils for plugins (not exported) */ var util = __webpack_require__(1063); /** * # .use(function) * * Provides a way to extend the internals of Chai. * * @param {Function} * @returns {this} for chaining * @api public */ exports.use = function (fn) { if (!~used.indexOf(fn)) { fn(exports, util); used.push(fn); } return exports; }; /*! * Utility Functions */ exports.util = util; /*! * Configuration */ var config = __webpack_require__(96); exports.config = config; /*! * Primary `Assertion` prototype */ var assertion = __webpack_require__(1080); exports.use(assertion); /*! * Core Assertions */ var core = __webpack_require__(1081); exports.use(core); /*! * Expect interface */ var expect = __webpack_require__(1082); exports.use(expect); /*! * Should interface */ var should = __webpack_require__(1083); exports.use(should); /*! * Assert interface */ var assert = __webpack_require__(1084); exports.use(assert); /***/ }), /* 96 */ /***/ (function(module, exports) { module.exports = { /** * ### config.includeStack * * User configurable property, influences whether stack trace * is included in Assertion error message. Default of false * suppresses stack trace in the error message. * * chai.config.includeStack = true; // enable stack on error * * @param {Boolean} * @api public */ includeStack: false, /** * ### config.showDiff * * User configurable property, influences whether or not * the `showDiff` flag should be included in the thrown * AssertionErrors. `false` will always be `false`; `true` * will be true when the assertion has requested a diff * be shown. * * @param {Boolean} * @api public */ showDiff: true, /** * ### config.truncateThreshold * * User configurable property, sets length threshold for actual and * expected values in assertion errors. If this threshold is exceeded, for * example for large data structures, the value is replaced with something * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. * * Set it to zero if you want to disable truncating altogether. * * This is especially userful when doing assertions on arrays: having this * set to a reasonable large value makes the failure messages readily * inspectable. * * chai.config.truncateThreshold = 0; // disable truncating * * @param {Number} * @api public */ truncateThreshold: 40, /** * ### config.useProxy * * User configurable property, defines if chai will use a Proxy to throw * an error when a non-existent property is read, which protects users * from typos when using property-based assertions. * * Set it to false if you want to disable this feature. * * chai.config.useProxy = false; // disable use of Proxy * * This feature is automatically disabled regardless of this config value * in environments that don't support proxies. * * @param {Boolean} * @api public */ useProxy: true, /** * ### config.proxyExcludedKeys * * User configurable property, defines which properties should be ignored * instead of throwing an error if they do not exist on the assertion. * This is only applied if the environment Chai is running in supports proxies and * if the `useProxy` configuration setting is enabled. * By default, `then` and `inspect` will not throw an error if they do not exist on the * assertion object because the `.inspect` property is read by `util.inspect` (for example, when * using `console.log` on the assertion object) and `.then` is necessary for promise type-checking. * * // By default these keys will not throw an error if they do not exist on the assertion object * chai.config.proxyExcludedKeys = ['then', 'inspect']; * * @param {Array} * @api public */ proxyExcludedKeys: ['then', 'inspect', 'toJSON'] }; /***/ }), /* 97 */ /***/ (function(module, exports) { /*! * Chai - transferFlags utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ /** * ### .transferFlags(assertion, object, includeAll = true) * * Transfer all the flags for `assertion` to `object`. If * `includeAll` is set to `false`, then the base Chai * assertion flags (namely `object`, `ssfi`, `lockSsfi`, * and `message`) will not be transferred. * * * var newAssertion = new Assertion(); * utils.transferFlags(assertion, newAssertion); * * var anotherAsseriton = new Assertion(myObj); * utils.transferFlags(assertion, anotherAssertion, false); * * @param {Assertion} assertion the assertion to transfer the flags from * @param {Object} object the object to transfer the flags to; usually a new assertion * @param {Boolean} includeAll * @namespace Utils * @name transferFlags * @api private */ module.exports = function transferFlags(assertion, object, includeAll) { var flags = assertion.__flags || (assertion.__flags = Object.create(null)); if (!object.__flags) { object.__flags = Object.create(null); } includeAll = arguments.length === 3 ? includeAll : true; for (var flag in flags) { if (includeAll || (flag !== 'object' && flag !== 'ssfi' && flag !== 'lockSsfi' && flag != 'message')) { object.__flags[flag] = flags[flag]; } } }; /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __webpack_require__(1116); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = __webpack_require__(1117); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(14), __webpack_require__(7))) /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(204)(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetIterator = GetIterator; exports.IteratorStep = IteratorStep; exports.IteratorValue = IteratorValue; exports.IteratorComplete = IteratorComplete; exports.IteratorNext = IteratorNext; exports.CreateListIterator = CreateListIterator; exports.CreateMapIterator = CreateMapIterator; exports.CreateSetIterator = CreateSetIterator; exports.IteratorClose = IteratorClose; exports.IterableToList = IterableToList; var _completions = __webpack_require__(3); var _index = __webpack_require__(0); var _index2 = __webpack_require__(5); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _abstract = __webpack_require__(29); var _singletons = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // ECMA262 7.4.1 /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function GetIterator(realm, obj = realm.intrinsics.undefined, method) { // 1. If method was not passed, then if (!method) { // a. Let method be ? GetMethod(obj, @@iterator). method = (0, _index2.GetMethod)(realm, obj, realm.intrinsics.SymbolIterator); } // 2. Let iterator be ? Call(method, obj). let iterator = (0, _index2.Call)(realm, method, obj); // 3. If Type(iterator) is not Object, throw a TypeError exception. if (!(iterator instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 4. Return iterator. return iterator; } // ECMA262 7.4.5 function IteratorStep(realm, iterator) { // 1. Let result be ? IteratorNext(iterator). let result = IteratorNext(realm, iterator); // 2. Let done be ? IteratorComplete(result). let done = IteratorComplete(realm, result); // 3. If done is true, return false. if (done) return false; // 4. Return result. return result; } // ECMA262 7.4.4 function IteratorValue(realm, iterResult) { // 1. Assert: Type(iterResult) is Object. (0, _invariant2.default)(iterResult instanceof _index.ObjectValue, "expected obj"); // 2. Return ? Get(iterResult, "value"). return (0, _index2.Get)(realm, iterResult, "value"); } // ECMA262 7.4.2 function IteratorComplete(realm, iterResult) { // 1. Assert: Type(iterResult) is Object. (0, _invariant2.default)(iterResult instanceof _index.ObjectValue, "expected obj"); // 2. Return ToBoolean(? Get(iterResult, "done")). return _singletons.To.ToBooleanPartial(realm, (0, _index2.Get)(realm, iterResult, "done")); } // ECMA262 7.4.2 function IteratorNext(realm, iterator, value) { // 1. If value was not passed, then let result; if (!value) { // a. Let result be ? Invoke(iterator, "next", « »). result = (0, _index2.Invoke)(realm, iterator, "next", []); } else { // 2. Else, // a. Let result be ? Invoke(iterator, "next", « value »). result = (0, _index2.Invoke)(realm, iterator, "next", [value]); } // 3. If Type(result) is not Object, throw a TypeError exception. if (!(result instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 4. Return result. return result; } // ECMA262 7.4.8 function CreateListIterator(realm, list) { // 1. Let iterator be ObjectCreate(%IteratorPrototype%, « [[IteratorNext]], [[IteratedList]], [[ListIteratorNextIndex]] »). let iterator = _singletons.Create.ObjectCreate(realm, realm.intrinsics.IteratorPrototype, { $IteratorNext: undefined, $IteratedList: undefined, $ListIteratorNextIndex: undefined }); // 2. Set iterator's [[IteratedList]] internal slot to list. iterator.$IteratedList = list; // 3. Set iterator's [[ListIteratorNextIndex]] internal slot to 0. iterator.$ListIteratorNextIndex = 0; // 4. Let next be a new built-in function object as defined in ListIterator next (7.4.8.1). let next = ListIterator_next(realm); // 5. Set iterator's [[IteratorNext]] internal slot to next. iterator.$IteratorNext = next; // 6. Perform CreateMethodProperty(iterator, "next", next). _singletons.Create.CreateMethodProperty(realm, iterator, new _index.StringValue(realm, "next"), next); // 7. Return iterator. return iterator; } // ECMA262 7.4.8.1 function ListIterator_next(realm) { let func = new _index.NativeFunctionValue(realm, undefined, "next", 0, context => { (0, _invariant2.default)(context instanceof _index.ObjectValue); // 1. Let O be the this value. let O = context; // 2. Let f be the active function object. let f = func; // 3. If O does not have a [[IteratorNext]] internal slot, throw a TypeError exception. if (!O.$IteratorNext) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "O does not have an [[IteratorNext]] internal slot"); } // 4. Let next be the value of the [[IteratorNext]] internal slot of O. let next = O.$IteratorNext; // 5. If SameValue(f, next) is false, throw a TypeError exception. if (!(0, _abstract.SameValue)(realm, f, next)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 6. If O does not have an [[IteratedList]] internal slot, throw a TypeError exception. if (!O.$IteratedList) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "O does not have an [[IteratedList]] internal slot"); } // 7. Let list be the value of the [[IteratedList]] internal slot of O. let list = O.$IteratedList; (0, _invariant2.default)(typeof O.$ListIteratorNextIndex === "number"); // 8. Let index be the value of the [[ListIteratorNextIndex]] internal slot of O. // Default to 0 for Flow. let index = O.$ListIteratorNextIndex; // 9. Let len be the number of elements of list. let len = list.length; // 10. If index ≥ len, then if (index >= len) { // a. Return CreateIterResultObject(undefined, true). return _singletons.Create.CreateIterResultObject(realm, realm.intrinsics.undefined, true); } // 11. Set the value of the [[ListIteratorNextIndex]] internal slot of O to index+1. O.$ListIteratorNextIndex = index + 1; // 12. Return CreateIterResultObject(list[index], false). return _singletons.Create.CreateIterResultObject(realm, list[index], false); }); return func; } // ECMA262 23.1.5.1 function CreateMapIterator(realm, map, kind) { // 1. If Type(map) is not Object, throw a TypeError exception. if (!(map instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 2. If map does not have a [[MapData]] internal slot, throw a TypeError exception. if (!map.$MapData) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 3. Let iterator be ObjectCreate(%MapIteratorPrototype%, « [[Map]], [[MapNextIndex]], [[MapIterationKind]] »). let iterator = _singletons.Create.ObjectCreate(realm, realm.intrinsics.MapIteratorPrototype, { $Map: undefined, $MapNextIndex: undefined, $MapIterationKind: undefined }); // 4. Set iterator's [[Map]] internal slot to map. iterator.$Map = map; // 5. Set iterator's [[MapNextIndex]] internal slot to 0. iterator.$MapNextIndex = new _index.NumberValue(realm, 0); // 6. Set iterator's [[MapIterationKind]] internal slot to kind. iterator.$MapIterationKind = kind; // 7. Return iterator. return iterator; } // ECMA262 23.2.5.1 function CreateSetIterator(realm, set, kind) { // 1. If Type(set) is not Object, throw a TypeError exception. if (!(set instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 2. If set does not have a [[SetData]] internal slot, throw a TypeError exception. if (!set.$SetData) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 3. Let iterator be ObjectCreate(%SetIteratorPrototype%, « [[IteratedSet]], [[SetNextIndex]], [[SetIterationKind]] »). let iterator = _singletons.Create.ObjectCreate(realm, realm.intrinsics.SetIteratorPrototype, { $IteratedSet: undefined, $SetNextIndex: undefined, $SetIterationKind: undefined }); // 4. Set iterator's [[IteratedSet]] internal slot to set. iterator.$IteratedSet = set; // 5. Set iterator's [[SetNextIndex]] internal slot to 0. iterator.$SetNextIndex = 0; // 6. Set iterator's [[SetIterationKind]] internal slot to kind. iterator.$SetIterationKind = kind; // 7. Return iterator. return iterator; } // ECMA262 7.4.6 function IteratorClose(realm, iterator, completion) { // 1. Assert: Type(iterator) is Object. (0, _invariant2.default)(iterator instanceof _index.ObjectValue, "expected object"); // 2. Assert: completion is a Completion Record. (0, _invariant2.default)(completion instanceof _completions.Completion, "expected completion record"); // 3. Let return be ? GetMethod(iterator, "return"). let ret = (0, _index2.GetMethod)(realm, iterator, "return"); // 4. If return is undefined, return Completion(completion). if (ret instanceof _index.UndefinedValue) return completion; // 5. Let innerResult be Call(return, iterator, « »). let innerResult; try { innerResult = (0, _index2.Call)(realm, ret.throwIfNotConcrete(), iterator, []); } catch (error) { if (error instanceof _completions.AbruptCompletion) { innerResult = error; } else { throw error; } } // 6. If completion.[[Type]] is throw, return Completion(completion). if (completion instanceof _completions.ThrowCompletion) return completion; // 7. If innerResult.[[Type]] is throw, return Completion(innerResult). if (innerResult instanceof _completions.ThrowCompletion) return innerResult; // 8. If Type(innerResult.[[Value]]) is not Object, throw a TypeError exception. if (!(innerResult instanceof _index.ObjectValue)) { return realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } // 9. Return Completion(completion). return completion; } // ECMA262 22.2.2.1.1 function IterableToList(realm, items, method) { // 1. Let iterator be ? GetIterator(items, method). let iterator = GetIterator(realm, items, method); // 2. Let values be a new empty List. let values = []; // 3. Let next be true. let next = true; // 4. Repeat, while next is not false while (next !== false) { // a. Let next be ? IteratorStep(iterator). next = IteratorStep(realm, iterator); // b. If next is not false, then if (next !== false) { // i. Let nextValue be ? IteratorValue(next). let nextValue = IteratorValue(realm, next); // ii. Append nextValue to the end of the List values. values.push(nextValue); } } // 5. Return values. return values; } //# sourceMappingURL=iterator.js.map /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = traverse; var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } // This is a variation of traverseFast from // https://github.com/babel/babel/blob/28ae47a174f67a8ae6f4527e0a66e88896814170/packages/babel-types/src/index.js // This version... // - takes a callback function that returns a boolean to indicate whether to short-circuit the traversal // - doesn't pass around or allocate an optional parameter value to the callback. /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function traverse(node, enter) { if (!node) return; let keys = t.VISITOR_KEYS[node.type]; if (!keys) return; let stop = enter(node); if (stop) return; for (let key of keys) { let subNode = node[key]; if (Array.isArray(subNode)) { for (let elementNode of subNode) { traverse(elementNode, enter); } } else { traverse(subNode, enter); } } } //# sourceMappingURL=traverse-fast.js.map /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (ast, strictCode, env, realm) { // evaluate left let lref = env.evaluate(ast.left, strictCode); let lval = _singletons.Environment.GetValue(realm, lref); // evaluate right let rref = env.evaluate(ast.right, strictCode); let rval = _singletons.Environment.GetValue(realm, rref); return computeBinary(realm, ast.operator, lval, rval, ast.left.loc, ast.right.loc, ast.loc); }; exports.getPureBinaryOperationResultType = getPureBinaryOperationResultType; exports.computeBinary = computeBinary; var _index = __webpack_require__(35); var _errors = __webpack_require__(6); var _index2 = __webpack_require__(0); var _completions = __webpack_require__(3); var _singletons = __webpack_require__(2); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } let unknownValueOfOrToString = "might be an object with an unknown valueOf or toString or Symbol.toPrimitive method"; // Returns result type if binary operation is pure (terminates, does not throw exception, does not read or write heap), otherwise undefined. /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function getPureBinaryOperationResultType(realm, op, lval, rval, lloc, rloc) { function reportErrorIfNotPure(purityTest, typeIfPure) { let leftPure = purityTest(realm, lval); let rightPure = purityTest(realm, rval); if (leftPure && rightPure) return typeIfPure; let loc = !leftPure ? lloc : rloc; let error = new _errors.CompilerDiagnostic(unknownValueOfOrToString, loc, "PP0002", "RecoverableError"); if (realm.handleError(error) === "Recover") { // Assume that an unknown value is actually a primitive or otherwise a well behaved object. return typeIfPure; } throw new _errors.FatalError(); } if (op === "+") { let ltype = _singletons.To.GetToPrimitivePureResultType(realm, lval); let rtype = _singletons.To.GetToPrimitivePureResultType(realm, rval); if (ltype === undefined || rtype === undefined) { let loc = ltype === undefined ? lloc : rloc; let error = new _errors.CompilerDiagnostic(unknownValueOfOrToString, loc, "PP0002", "RecoverableError"); if (realm.handleError(error) === "Recover") { // Assume that the unknown value is actually a primitive or otherwise a well behaved object. ltype = lval.getType(); rtype = rval.getType(); if (ltype === _index2.StringValue || rtype === _index2.StringValue) return _index2.StringValue; if (ltype === _index2.IntegralValue && rtype === _index2.IntegralValue) return _index2.IntegralValue; if ((ltype === _index2.NumberValue || ltype === _index2.IntegralValue) && (rtype === _index2.NumberValue || rtype === _index2.IntegralValue)) return _index2.NumberValue; return _index2.Value; } throw new _errors.FatalError(); } if (ltype === _index2.StringValue || rtype === _index2.StringValue) return _index2.StringValue; return _index2.NumberValue; } else if (op === "<" || op === ">" || op === ">=" || op === "<=") { return reportErrorIfNotPure(_singletons.To.IsToPrimitivePure.bind(_singletons.To), _index2.BooleanValue); } else if (op === "!=" || op === "==") { let ltype = lval.getType(); let rtype = rval.getType(); if (ltype === _index2.NullValue || ltype === _index2.UndefinedValue || rtype === _index2.NullValue || rtype === _index2.UndefinedValue) return _index2.BooleanValue; return reportErrorIfNotPure(_singletons.To.IsToPrimitivePure.bind(_singletons.To), _index2.BooleanValue); } else if (op === "===" || op === "!==") { return _index2.BooleanValue; } else if (op === ">>>" || op === "<<" || op === ">>" || op === "&" || op === "|" || op === "^" || op === "**" || op === "%" || op === "/" || op === "*" || op === "-") { return reportErrorIfNotPure(_singletons.To.IsToNumberPure.bind(_singletons.To), _index2.NumberValue); } else if (op === "in" || op === "instanceof") { if (rval.mightNotBeObject()) { let error = new _errors.CompilerDiagnostic(`might not be an object, hence the ${op} operator might throw a TypeError`, rloc, "PP0003", "RecoverableError"); if (realm.handleError(error) === "Recover") { // Assume that the object is actually a well behaved object. return _index2.BooleanValue; } throw new _errors.FatalError(); } if (!rval.mightNotBeObject()) { // Simple object won't throw here, aren't proxy objects or typed arrays and do not have @@hasInstance properties. if (rval.isSimpleObject()) return _index2.BooleanValue; } let error = new _errors.CompilerDiagnostic(`might be an object that behaves badly for the ${op} operator`, rloc, "PP0004", "RecoverableError"); if (realm.handleError(error) === "Recover") { // Assume that the object is actually a well behaved object. return _index2.BooleanValue; } throw new _errors.FatalError(); } (0, _invariant2.default)(false, "unimplemented " + op); } function computeBinary(realm, op, lval, rval, lloc, rloc, loc) { // partial evaluation shortcut for a particular pattern if (realm.useAbstractInterpretation && (op === "==" || op === "===" || op === "!=" || op === "!==")) { if (!lval.mightNotBeObject() && (rval instanceof _index2.NullValue || rval instanceof _index2.UndefinedValue) || (lval instanceof _index2.NullValue || lval instanceof _index2.UndefinedValue) && !rval.mightNotBeObject()) { return new _index2.BooleanValue(realm, op[0] !== "="); } } let resultType; const compute = () => { if (lval instanceof _index2.AbstractValue || rval instanceof _index2.AbstractValue) { // generate error if binary operation might throw or have side effects resultType = getPureBinaryOperationResultType(realm, op, lval, rval, lloc, rloc); return _index2.AbstractValue.createFromBinaryOp(realm, op, lval, rval, loc); } else { // ECMA262 12.10.3 // 5. If Type(rval) is not Object, throw a TypeError exception. if (op === "in" && !(rval instanceof _index2.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError); } (0, _invariant2.default)(lval instanceof _index2.ConcreteValue); (0, _invariant2.default)(rval instanceof _index2.ConcreteValue); const result = _index.ValuesDomain.computeBinary(realm, op, lval, rval); resultType = result.getType(); return result; } }; if (realm.isInPureScope()) { // If we're in pure mode we can recover even if this operation might not be pure. // To do that, we'll temporarily override the error handler. const previousErrorHandler = realm.errorHandler; let isPure = true; realm.errorHandler = diagnostic => { isPure = false; return "Recover"; }; let effects; try { effects = realm.evaluateForEffects(compute); } catch (x) { if (x instanceof _errors.FatalError) { isPure = false; } else { throw x; } } finally { realm.errorHandler = previousErrorHandler; } if (isPure && effects) { let completion = effects[0]; if (completion instanceof _completions.PossiblyNormalCompletion) { // in this case one of the branches may complete abruptly, which means that // not all control flow branches join into one flow at this point. // Consequently we have to continue tracking changes until the point where // all the branches come together into one. completion = realm.composeWithSavedCompletion(completion); } // Note that the effects of (non joining) abrupt branches are not included // in effects, but are tracked separately inside completion. realm.applyEffects(effects); // return or throw completion if (completion instanceof _completions.AbruptCompletion) throw completion; (0, _invariant2.default)(completion instanceof _index2.Value); return completion; } // If this ended up reporting an error, it might not be pure, so we'll leave it in // as a temporal operation with a known return type. // Some of these values may trigger side-effectful user code such as valueOf. // To be safe, we have to Havoc them. _singletons.Havoc.value(realm, lval, loc); if (op !== "in") { // The "in" operator have side-effects on its right val other than throw. _singletons.Havoc.value(realm, rval, loc); } return realm.evaluateWithPossibleThrowCompletion(() => _index2.AbstractValue.createTemporalFromBuildFunction(realm, resultType, [lval, rval], ([lnode, rnode]) => t.binaryExpression(op, lnode, rnode)), _index.TypesDomain.topVal, _index.ValuesDomain.topVal); } return compute(); } //# sourceMappingURL=BinaryExpression.js.map /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _getIterator2 = __webpack_require__(21); var _getIterator3 = _interopRequireDefault(_getIterator2); var _classCallCheck2 = __webpack_require__(41); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _virtualTypes = __webpack_require__(617); var virtualTypes = _interopRequireWildcard(_virtualTypes); var _debug2 = __webpack_require__(1918); var _debug3 = _interopRequireDefault(_debug2); var _invariant = __webpack_require__(387); var _invariant2 = _interopRequireDefault(_invariant); var _index = __webpack_require__(60); var _index2 = _interopRequireDefault(_index); var _assign = __webpack_require__(618); var _assign2 = _interopRequireDefault(_assign); var _scope = __webpack_require__(323); var _scope2 = _interopRequireDefault(_scope); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); var _cache = __webpack_require__(226); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _debug = (0, _debug3.default)("babel"); var NodePath = function () { function NodePath(hub, parent) { (0, _classCallCheck3.default)(this, NodePath); this.parent = parent; this.hub = hub; this.contexts = []; this.data = {}; this.shouldSkip = false; this.shouldStop = false; this.removed = false; this.state = null; this.opts = null; this.skipKeys = null; this.parentPath = null; this.context = null; this.container = null; this.listKey = null; this.inList = false; this.parentKey = null; this.key = null; this.node = null; this.scope = null; this.type = null; this.typeAnnotation = null; } NodePath.get = function get(_ref) { var hub = _ref.hub, parentPath = _ref.parentPath, parent = _ref.parent, container = _ref.container, listKey = _ref.listKey, key = _ref.key; if (!hub && parentPath) { hub = parentPath.hub; } (0, _invariant2.default)(parent, "To get a node path the parent needs to exist"); var targetNode = container[key]; var paths = _cache.path.get(parent) || []; if (!_cache.path.has(parent)) { _cache.path.set(parent, paths); } var path = void 0; for (var i = 0; i < paths.length; i++) { var pathCheck = paths[i]; if (pathCheck.node === targetNode) { path = pathCheck; break; } } if (!path) { path = new NodePath(hub, parent); paths.push(path); } path.setup(parentPath, container, listKey, key); return path; }; NodePath.prototype.getScope = function getScope(scope) { var ourScope = scope; if (this.isScope()) { ourScope = new _scope2.default(this, scope); } return ourScope; }; NodePath.prototype.setData = function setData(key, val) { return this.data[key] = val; }; NodePath.prototype.getData = function getData(key, def) { var val = this.data[key]; if (!val && def) val = this.data[key] = def; return val; }; NodePath.prototype.buildCodeFrameError = function buildCodeFrameError(msg) { var Error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SyntaxError; return this.hub.file.buildCodeFrameError(this.node, msg, Error); }; NodePath.prototype.traverse = function traverse(visitor, state) { (0, _index2.default)(this.node, visitor, this.scope, state, this); }; NodePath.prototype.mark = function mark(type, message) { this.hub.file.metadata.marked.push({ type: type, message: message, loc: this.node.loc }); }; NodePath.prototype.set = function set(key, node) { t.validate(this.node, key, node); this.node[key] = node; }; NodePath.prototype.getPathLocation = function getPathLocation() { var parts = []; var path = this; do { var key = path.key; if (path.inList) key = path.listKey + "[" + key + "]"; parts.unshift(key); } while (path = path.parentPath); return parts.join("."); }; NodePath.prototype.debug = function debug(buildMessage) { if (!_debug.enabled) return; _debug(this.getPathLocation() + " " + this.type + ": " + buildMessage()); }; return NodePath; }(); exports.default = NodePath; (0, _assign2.default)(NodePath.prototype, __webpack_require__(1938)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1939)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1942)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1950)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1951)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1952)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1953)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1954)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1956)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1958)); (0, _assign2.default)(NodePath.prototype, __webpack_require__(1959)); var _loop2 = function _loop2() { if (_isArray) { if (_i >= _iterator.length) return "break"; _ref2 = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) return "break"; _ref2 = _i.value; } var type = _ref2; var typeKey = "is" + type; NodePath.prototype[typeKey] = function (opts) { return t[typeKey](this.node, opts); }; NodePath.prototype["assert" + type] = function (opts) { if (!this[typeKey](opts)) { throw new TypeError("Expected node path of type " + type); } }; }; for (var _iterator = t.TYPES, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { var _ref2; var _ret2 = _loop2(); if (_ret2 === "break") break; } var _loop = function _loop(type) { if (type[0] === "_") return "continue"; if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type); var virtualType = virtualTypes[type]; NodePath.prototype["is" + type] = function (opts) { return virtualType.checkPath(this, opts); }; }; for (var type in virtualTypes) { var _ret = _loop(type); if (_ret === "continue") continue; } module.exports = exports["default"]; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. /**/ var pna = __webpack_require__(228); /**/ /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /**/ module.exports = Duplex; /**/ var util = __webpack_require__(169); util.inherits = __webpack_require__(8); /**/ var Readable = __webpack_require__(643); var Writable = __webpack_require__(332); util.inherits(Duplex, Readable); { // avoid scope creep, the keys array can then be collected var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. pna.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); pna.nextTick(cb, err); }; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var virtualTypes = _interopRequireWildcard(__webpack_require__(347)); function _debug() { const data = _interopRequireDefault(__webpack_require__(839)); _debug = function () { return data; }; return data; } function _invariant() { const data = _interopRequireDefault(__webpack_require__(387)); _invariant = function () { return data; }; return data; } var _index = _interopRequireDefault(__webpack_require__(66)); var _scope = _interopRequireDefault(__webpack_require__(388)); function t() { const data = _interopRequireWildcard(__webpack_require__(9)); t = function () { return data; }; return data; } var _cache = __webpack_require__(189); function _generator() { const data = _interopRequireDefault(__webpack_require__(258)); _generator = function () { return data; }; return data; } var NodePath_ancestry = _interopRequireWildcard(__webpack_require__(884)); var NodePath_inference = _interopRequireWildcard(__webpack_require__(885)); var NodePath_replacement = _interopRequireWildcard(__webpack_require__(888)); var NodePath_evaluation = _interopRequireWildcard(__webpack_require__(897)); var NodePath_conversion = _interopRequireWildcard(__webpack_require__(898)); var NodePath_introspection = _interopRequireWildcard(__webpack_require__(905)); var NodePath_context = _interopRequireWildcard(__webpack_require__(906)); var NodePath_removal = _interopRequireWildcard(__webpack_require__(907)); var NodePath_modification = _interopRequireWildcard(__webpack_require__(909)); var NodePath_family = _interopRequireWildcard(__webpack_require__(911)); var NodePath_comments = _interopRequireWildcard(__webpack_require__(912)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const debug = (0, _debug().default)("babel"); class NodePath { constructor(hub, parent) { this.parent = parent; this.hub = hub; this.contexts = []; this.data = {}; this.shouldSkip = false; this.shouldStop = false; this.removed = false; this.state = null; this.opts = null; this.skipKeys = null; this.parentPath = null; this.context = null; this.container = null; this.listKey = null; this.inList = false; this.parentKey = null; this.key = null; this.node = null; this.scope = null; this.type = null; this.typeAnnotation = null; } static get({ hub, parentPath, parent, container, listKey, key }) { if (!hub && parentPath) { hub = parentPath.hub; } (0, _invariant().default)(parent, "To get a node path the parent needs to exist"); const targetNode = container[key]; const paths = _cache.path.get(parent) || []; if (!_cache.path.has(parent)) { _cache.path.set(parent, paths); } let path; for (let i = 0; i < paths.length; i++) { const pathCheck = paths[i]; if (pathCheck.node === targetNode) { path = pathCheck; break; } } if (!path) { path = new NodePath(hub, parent); paths.push(path); } path.setup(parentPath, container, listKey, key); return path; } getScope(scope) { return this.isScope() ? new _scope.default(this) : scope; } setData(key, val) { return this.data[key] = val; } getData(key, def) { let val = this.data[key]; if (!val && def) val = this.data[key] = def; return val; } buildCodeFrameError(msg, Error = SyntaxError) { return this.hub.file.buildCodeFrameError(this.node, msg, Error); } traverse(visitor, state) { (0, _index.default)(this.node, visitor, this.scope, state, this); } set(key, node) { t().validate(this.node, key, node); this.node[key] = node; } getPathLocation() { const parts = []; let path = this; do { let key = path.key; if (path.inList) key = `${path.listKey}[${key}]`; parts.unshift(key); } while (path = path.parentPath); return parts.join("."); } debug(message) { if (!debug.enabled) return; debug(`${this.getPathLocation()} ${this.type}: ${message}`); } toString() { return (0, _generator().default)(this.node).code; } } exports.default = NodePath; Object.assign(NodePath.prototype, NodePath_ancestry, NodePath_inference, NodePath_replacement, NodePath_evaluation, NodePath_conversion, NodePath_introspection, NodePath_context, NodePath_removal, NodePath_modification, NodePath_family, NodePath_comments); for (const type of t().TYPES) { const typeKey = `is${type}`; const fn = t()[typeKey]; NodePath.prototype[typeKey] = function (opts) { return fn(this.node, opts); }; NodePath.prototype[`assert${type}`] = function (opts) { if (!fn(this.node, opts)) { throw new TypeError(`Expected node path of type ${type}`); } }; } for (const type in virtualTypes) { if (type[0] === "_") continue; if (t().TYPES.indexOf(type) < 0) t().TYPES.push(type); const virtualType = virtualTypes[type]; NodePath.prototype[`is${type}`] = function (opts) { return virtualType.checkPath(this, opts); }; } /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(55); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }), /* 107 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(374), isArrayLike = __webpack_require__(78), isString = __webpack_require__(841), toInteger = __webpack_require__(135), values = __webpack_require__(844); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } module.exports = includes; /***/ }), /* 108 */ /***/ (function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } /***/ }), /* 109 */ /***/ (function(module, exports, __webpack_require__) { /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = __webpack_require__(453).SourceMapGenerator; exports.SourceMapConsumer = __webpack_require__(1137).SourceMapConsumer; exports.SourceNode = __webpack_require__(1140).SourceNode; /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { var assert = __webpack_require__(36); var types = __webpack_require__(67); var getFieldValue = types.getFieldValue; var n = types.namedTypes; var sourceMap = __webpack_require__(109); var SourceMapConsumer = sourceMap.SourceMapConsumer; var SourceMapGenerator = sourceMap.SourceMapGenerator; var hasOwn = Object.prototype.hasOwnProperty; var util = exports; function getUnionOfKeys() { var result = {}; var argc = arguments.length; for (var i = 0; i < argc; ++i) { var keys = Object.keys(arguments[i]); var keyCount = keys.length; for (var j = 0; j < keyCount; ++j) { result[keys[j]] = true; } } return result; } util.getUnionOfKeys = getUnionOfKeys; function comparePos(pos1, pos2) { return (pos1.line - pos2.line) || (pos1.column - pos2.column); } util.comparePos = comparePos; function copyPos(pos) { return { line: pos.line, column: pos.column }; } util.copyPos = copyPos; util.composeSourceMaps = function(formerMap, latterMap) { if (formerMap) { if (!latterMap) { return formerMap; } } else { return latterMap || null; } var smcFormer = new SourceMapConsumer(formerMap); var smcLatter = new SourceMapConsumer(latterMap); var smg = new SourceMapGenerator({ file: latterMap.file, sourceRoot: latterMap.sourceRoot }); var sourcesToContents = {}; smcLatter.eachMapping(function(mapping) { var origPos = smcFormer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); var sourceName = origPos.source; if (sourceName === null) { return; } smg.addMapping({ source: sourceName, original: copyPos(origPos), generated: { line: mapping.generatedLine, column: mapping.generatedColumn }, name: mapping.name }); var sourceContent = smcFormer.sourceContentFor(sourceName); if (sourceContent && !hasOwn.call(sourcesToContents, sourceName)) { sourcesToContents[sourceName] = sourceContent; smg.setSourceContent(sourceName, sourceContent); } }); return smg.toJSON(); }; util.getTrueLoc = function(node, lines) { // It's possible that node is newly-created (not parsed by Esprima), // in which case it probably won't have a .loc property (or an // .original property for that matter). That's fine; we'll just // pretty-print it as usual. if (!node.loc) { return null; } var result = { start: node.loc.start, end: node.loc.end }; function include(node) { expandLoc(result, node.loc); } // If the node has any comments, their locations might contribute to // the true start/end positions of the node. if (node.comments) { node.comments.forEach(include); } // If the node is an export declaration and its .declaration has any // decorators, their locations might contribute to the true start/end // positions of the export declaration node. if (node.declaration && util.isExportDeclaration(node) && node.declaration.decorators) { node.declaration.decorators.forEach(include); } if (comparePos(result.start, result.end) < 0) { // Trim leading whitespace. result.start = copyPos(result.start); lines.skipSpaces(result.start, false, true); if (comparePos(result.start, result.end) < 0) { // Trim trailing whitespace, if the end location is not already the // same as the start location. result.end = copyPos(result.end); lines.skipSpaces(result.end, true, true); } } return result; }; function expandLoc(parentLoc, childLoc) { if (parentLoc && childLoc) { if (comparePos(childLoc.start, parentLoc.start) < 0) { parentLoc.start = childLoc.start; } if (comparePos(parentLoc.end, childLoc.end) < 0) { parentLoc.end = childLoc.end; } } } util.fixFaultyLocations = function(node, lines) { var loc = node.loc; if (loc) { if (loc.start.line < 1) { loc.start.line = 1; } if (loc.end.line < 1) { loc.end.line = 1; } } if (node.type === "File") { // Babylon returns File nodes whose .loc.{start,end} do not include // leading or trailing whitespace. loc.start = lines.firstPos(); loc.end = lines.lastPos(); } fixForLoopHead(node, lines); fixTemplateLiteral(node, lines); if (loc && node.decorators) { // Expand the .loc of the node responsible for printing the decorators // (here, the decorated node) so that it includes node.decorators. node.decorators.forEach(function (decorator) { expandLoc(loc, decorator.loc); }); } else if (node.declaration && util.isExportDeclaration(node)) { // Nullify .loc information for the child declaration so that we never // try to reprint it without also reprinting the export declaration. node.declaration.loc = null; // Expand the .loc of the node responsible for printing the decorators // (here, the export declaration) so that it includes node.decorators. var decorators = node.declaration.decorators; if (decorators) { decorators.forEach(function (decorator) { expandLoc(loc, decorator.loc); }); } } else if ((n.MethodDefinition && n.MethodDefinition.check(node)) || (n.Property.check(node) && (node.method || node.shorthand))) { // If the node is a MethodDefinition or a .method or .shorthand // Property, then the location information stored in // node.value.loc is very likely untrustworthy (just the {body} // part of a method, or nothing in the case of shorthand // properties), so we null out that information to prevent // accidental reuse of bogus source code during reprinting. node.value.loc = null; if (n.FunctionExpression.check(node.value)) { // FunctionExpression method values should be anonymous, // because their .id fields are ignored anyway. node.value.id = null; } } else if (node.type === "ObjectTypeProperty") { var loc = node.loc; var end = loc && loc.end; if (end) { end = copyPos(end); if (lines.prevPos(end) && lines.charAt(end) === ",") { // Some parsers accidentally include trailing commas in the // .loc.end information for ObjectTypeProperty nodes. if ((end = lines.skipSpaces(end, true, true))) { loc.end = end; } } } } }; function fixForLoopHead(node, lines) { if (node.type !== "ForStatement") { return; } function fix(child) { var loc = child && child.loc; var start = loc && loc.start; var end = loc && copyPos(loc.end); while (start && end && comparePos(start, end) < 0) { lines.prevPos(end); if (lines.charAt(end) === ";") { // Update child.loc.end to *exclude* the ';' character. loc.end.line = end.line; loc.end.column = end.column; } else { break; } } } fix(node.init); fix(node.test); fix(node.update); } function fixTemplateLiteral(node, lines) { if (node.type !== "TemplateLiteral") { return; } if (node.quasis.length === 0) { // If there are no quasi elements, then there is nothing to fix. return; } // First we need to exclude the opening ` from the .loc of the first // quasi element, in case the parser accidentally decided to include it. var afterLeftBackTickPos = copyPos(node.loc.start); assert.strictEqual(lines.charAt(afterLeftBackTickPos), "`"); assert.ok(lines.nextPos(afterLeftBackTickPos)); var firstQuasi = node.quasis[0]; if (comparePos(firstQuasi.loc.start, afterLeftBackTickPos) < 0) { firstQuasi.loc.start = afterLeftBackTickPos; } // Next we need to exclude the closing ` from the .loc of the last quasi // element, in case the parser accidentally decided to include it. var rightBackTickPos = copyPos(node.loc.end); assert.ok(lines.prevPos(rightBackTickPos)); assert.strictEqual(lines.charAt(rightBackTickPos), "`"); var lastQuasi = node.quasis[node.quasis.length - 1]; if (comparePos(rightBackTickPos, lastQuasi.loc.end) < 0) { lastQuasi.loc.end = rightBackTickPos; } // Now we need to exclude ${ and } characters from the .loc's of all // quasi elements, since some parsers accidentally include them. node.expressions.forEach(function (expr, i) { // Rewind from expr.loc.start over any whitespace and the ${ that // precedes the expression. The position of the $ should be the same // as the .loc.end of the preceding quasi element, but some parsers // accidentally include the ${ in the .loc of the quasi element. var dollarCurlyPos = lines.skipSpaces(expr.loc.start, true, false); if (lines.prevPos(dollarCurlyPos) && lines.charAt(dollarCurlyPos) === "{" && lines.prevPos(dollarCurlyPos) && lines.charAt(dollarCurlyPos) === "$") { var quasiBefore = node.quasis[i]; if (comparePos(dollarCurlyPos, quasiBefore.loc.end) < 0) { quasiBefore.loc.end = dollarCurlyPos; } } // Likewise, some parsers accidentally include the } that follows // the expression in the .loc of the following quasi element. var rightCurlyPos = lines.skipSpaces(expr.loc.end, false, false); if (lines.charAt(rightCurlyPos) === "}") { assert.ok(lines.nextPos(rightCurlyPos)); // Now rightCurlyPos is technically the position just after the }. var quasiAfter = node.quasis[i + 1]; if (comparePos(quasiAfter.loc.start, rightCurlyPos) < 0) { quasiAfter.loc.start = rightCurlyPos; } } }); } util.isExportDeclaration = function (node) { if (node) switch (node.type) { case "ExportDeclaration": case "ExportDefaultDeclaration": case "ExportDefaultSpecifier": case "DeclareExportDeclaration": case "ExportNamedDeclaration": case "ExportAllDeclaration": return true; } return false; }; util.getParentExportDeclaration = function (path) { var parentNode = path.getParentNode(); if (path.getName() === "declaration" && util.isExportDeclaration(parentNode)) { return parentNode; } return null; }; util.isTrailingCommaEnabled = function(options, context) { var trailingComma = options.trailingComma; if (typeof trailingComma === "object") { return !!trailingComma[context]; } return !!trailingComma; }; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(68); var hide = __webpack_require__(112); var has = __webpack_require__(115); var SRC = __webpack_require__(203)('src'); var TO_STRING = 'toString'; var $toString = Function[TO_STRING]; var TPL = ('' + $toString).split(TO_STRING); __webpack_require__(205).inspectSource = function (it) { return $toString.call(it); }; (module.exports = function (O, key, val, safe) { var isFunction = typeof val == 'function'; if (isFunction) has(val, 'name') || hide(val, 'name', key); if (O[key] === val) return; if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); if (O === global) { O[key] = val; } else if (!safe) { delete O[key]; hide(O, key, val); } else if (O[key]) { O[key] = val; } else { hide(O, key, val); } // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, TO_STRING, function toString() { return typeof this == 'function' && this[SRC] || $toString.call(this); }); /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(113); var createDesc = __webpack_require__(273); module.exports = __webpack_require__(99) ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(114); var IE8_DOM_DEFINE = __webpack_require__(462); var toPrimitive = __webpack_require__(464); var dP = Object.defineProperty; exports.f = __webpack_require__(99) ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(81); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /* 115 */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = multiReplaceStatement; var _copyComments = __webpack_require__(146); var _copyComments2 = _interopRequireDefault(_copyComments); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /** * Replaces `node` inside `parent` with any number of `replacements`. * * ESTraverse only allows replacing one node with a single other node. * This function overcomes this limitation, allowing to replace it with multiple nodes. * * NOTE: Only works for nodes that allow multiple elements in their body. * When node doesn't exist inside parent, does nothing. * * @param {Object} cfg * @param {Object} cfg.parent Parent node of the node to replace * @param {Object} cfg.node The node to replace * @param {Object[]} cfg.replacements Replacement nodes (can be empty array) * @param {Boolean} [cfg.preserveComments] True to copy over comments from * node to first replacement node */ function multiReplaceStatement(_ref) { var parent = _ref.parent, node = _ref.node, replacements = _ref.replacements, preserveComments = _ref.preserveComments; var body = getBody(parent); var index = body.indexOf(node); if (preserveComments && replacements[0]) { (0, _copyComments2.default)({ from: node, to: replacements[0] }); } if (index !== -1) { body.splice.apply(body, [index, 1].concat(_toConsumableArray(replacements))); } } function getBody(node) { switch (node.type) { case 'BlockStatement': case 'Program': return node.body; case 'SwitchCase': return node.consequent; default: throw 'Unsupported node type \'' + node.type + '\' in multiReplaceStatement()'; } } module.exports = exports['default']; /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isFunction = isFunction; exports.isFunctionExpression = isFunctionExpression; exports.isFunctionDeclaration = isFunctionDeclaration; /** * True when node is any kind of function. */ function isFunction(node) { return isFunctionDeclaration(node) || isFunctionExpression(node); } /** * True when node is (arrow) function expression. */ function isFunctionExpression(node) { return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; } /** * True when node is function declaration. */ function isFunctionDeclaration(node) { return node.type === 'FunctionDeclaration'; } /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _undefined = __webpack_require__(487)(); // Support ES3 engines module.exports = function (val) { return (val !== _undefined) && (val !== null); }; /***/ }), /* 119 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var cloneNode = function cloneNode(obj, parent) { if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object') { return obj; } var cloned = new obj.constructor(); for (var i in obj) { if (!obj.hasOwnProperty(i)) { continue; } var value = obj[i]; var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (i === 'parent' && type === 'object') { if (parent) { cloned[i] = parent; } } else if (value instanceof Array) { cloned[i] = value.map(function (j) { return cloneNode(j, cloned); }); } else { cloned[i] = cloneNode(value, cloned); } } return cloned; }; var _class = function () { function _class() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, _class); Object.assign(this, opts); this.spaces = this.spaces || {}; this.spaces.before = this.spaces.before || ''; this.spaces.after = this.spaces.after || ''; } _class.prototype.remove = function remove() { if (this.parent) { this.parent.removeChild(this); } this.parent = undefined; return this; }; _class.prototype.replaceWith = function replaceWith() { if (this.parent) { for (var index in arguments) { this.parent.insertBefore(this, arguments[index]); } this.remove(); } return this; }; _class.prototype.next = function next() { return this.parent.at(this.parent.index(this) + 1); }; _class.prototype.prev = function prev() { return this.parent.at(this.parent.index(this) - 1); }; _class.prototype.clone = function clone() { var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var cloned = cloneNode(this); for (var name in overrides) { cloned[name] = overrides[name]; } return cloned; }; _class.prototype.toString = function toString() { return [this.spaces.before, String(this.value), this.spaces.after].join(''); }; return _class; }(); exports.default = _class; module.exports = exports['default']; /***/ }), /* 120 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var browserslist = __webpack_require__(292); var utils = __webpack_require__(47); var Browsers = function () { /** * Return all prefixes for default browser data */ Browsers.prefixes = function prefixes() { if (this.prefixesCache) { return this.prefixesCache; } var data = __webpack_require__(214).agents; this.prefixesCache = []; for (var name in data) { this.prefixesCache.push('-' + data[name].prefix + '-'); } this.prefixesCache = utils.uniq(this.prefixesCache).sort(function (a, b) { return b.length - a.length; }); return this.prefixesCache; }; /** * Check is value contain any possibe prefix */ Browsers.withPrefix = function withPrefix(value) { if (!this.prefixesRegexp) { this.prefixesRegexp = new RegExp(this.prefixes().join('|')); } return this.prefixesRegexp.test(value); }; function Browsers(data, requirements, options, stats) { _classCallCheck(this, Browsers); this.data = data; this.options = options || {}; this.stats = stats; this.selected = this.parse(requirements); } /** * Return browsers selected by requirements */ Browsers.prototype.parse = function parse(requirements) { return browserslist(requirements, { stats: this.stats, path: this.options.from, env: this.options.env }); }; /** * Return prefix for selected browser */ Browsers.prototype.prefix = function prefix(browser) { var _browser$split = browser.split(' '), name = _browser$split[0], version = _browser$split[1]; var data = this.data[name]; var prefix = data.prefix_exceptions && data.prefix_exceptions[version]; if (!prefix) { prefix = data.prefix; } return '-' + prefix + '-'; }; /** * Is browser is selected by requirements */ Browsers.prototype.isSelected = function isSelected(browser) { return this.selected.indexOf(browser) !== -1; }; return Browsers; }(); module.exports = Browsers; /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(590); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(303); var defined = __webpack_require__(298); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(1842), __esModule: true }; /***/ }), /* 124 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CreateByteDataBlock = CreateByteDataBlock; exports.CopyDataBlockBytes = CopyDataBlockBytes; exports.AllocateArrayBuffer = AllocateArrayBuffer; exports.DetachArrayBuffer = DetachArrayBuffer; exports.GetViewValue = GetViewValue; exports.GetValueFromBuffer = GetValueFromBuffer; exports.SetViewValue = SetViewValue; exports.CloneArrayBuffer = CloneArrayBuffer; exports.SetValueInBuffer = SetValueInBuffer; var _index = __webpack_require__(0); var _construct = __webpack_require__(52); var _index2 = __webpack_require__(5); var _is = __webpack_require__(16); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _types = __webpack_require__(322); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // ECMA262 6.2.6.1 function CreateByteDataBlock(realm, size) { // 1. Assert: size≥0. (0, _invariant2.default)(size >= 0, "size >= 0"); // 2. Let db be a new Data Block value consisting of size bytes. If it is impossible to create such a Data Block, throw a RangeError exception. let db; try { db = new Uint8Array(size); } catch (e) { if (e instanceof RangeError) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "Invalid typed array length"); } else { throw e; } } // 3. Set all of the bytes of db to 0. for (let i = 0; i < size; ++i) { db[i] = 0; } // 4. Return db. return db; } // ECMA262 6.2.6.2 /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function CopyDataBlockBytes(realm, toBlock, toIndex, fromBlock, fromIndex, count) { // 1. Assert: fromBlock and toBlock are distinct Data Block values. (0, _invariant2.default)(toBlock instanceof Uint8Array && fromBlock instanceof Uint8Array && toBlock !== fromBlock); // 2. Assert: fromIndex, toIndex, and count are integer values ≥ 0. (0, _invariant2.default)(toIndex >= 0 && fromIndex >= 0 && count >= 0); // 3. Let fromSize be the number of bytes in fromBlock. let fromSize = fromBlock.length; // 4. Assert: fromIndex+count ≤ fromSize. (0, _invariant2.default)(fromIndex + count <= fromSize, "fromIndex+count ≤ fromSize"); // 5. Let toSize be the number of bytes in toBlock. let toSize = toBlock.length; // 6. Assert: toIndex+count ≤ toSize. (0, _invariant2.default)(toIndex + count <= toSize, "toIndex+count ≤ toSize"); // 7. Repeat, while count>0 while (count > 0) { // a. Set toBlock[toIndex] to the value of fromBlock[fromIndex]. toBlock[toIndex] = fromBlock[fromIndex]; // b. Increment toIndex and fromIndex each by 1. toIndex += 1; fromIndex += 1; // c. Decrement count by 1. count -= 1; } // 8. Return NormalCompletion(empty). return realm.intrinsics.empty; } // ECMA262 24.1.1.1 function AllocateArrayBuffer(realm, constructor, byteLength) { // 1. Let obj be ? OrdinaryCreateFromConstructor(constructor, "%ArrayBufferPrototype%", « [[ArrayBufferData]], [[ArrayBufferByteLength]] »). let obj = _singletons.Create.OrdinaryCreateFromConstructor(realm, constructor, "ArrayBufferPrototype", { $ArrayBufferData: undefined, $ArrayBufferByteLength: undefined }); // 2. Assert: byteLength is an integer value ≥ 0. (0, _invariant2.default)(typeof byteLength === "number" && byteLength >= 0, "byteLength is an integer value ≥ 0"); // 3. Let block be ? CreateByteDataBlock(byteLength). let block = CreateByteDataBlock(realm, byteLength); // 4. Set obj's [[ArrayBufferData]] internal slot to block. obj.$ArrayBufferData = block; // 5. Set obj's [[ArrayBufferByteLength]] internal slot to byteLength. obj.$ArrayBufferByteLength = byteLength; // 6. Return obj. return obj; } // ECMA262 24.1.1.3 function DetachArrayBuffer(realm, arrayBuffer) { // 1. Assert: Type(arrayBuffer) is Object and it has [[ArrayBufferData]] and [[ArrayBufferByteLength]] internal slots. (0, _invariant2.default)(arrayBuffer instanceof _index.ObjectValue && "$ArrayBufferData" in arrayBuffer && "$ArrayBufferByteLength" in arrayBuffer); // 2. Set arrayBuffer.[[ArrayBufferData]] to null. _singletons.Properties.ThrowIfInternalSlotNotWritable(realm, arrayBuffer, "$ArrayBufferData").$ArrayBufferData = null; // 3. Set arrayBuffer.[[ArrayBufferByteLength]] to 0. _singletons.Properties.ThrowIfInternalSlotNotWritable(realm, arrayBuffer, "$ArrayBufferByteLength").$ArrayBufferByteLength = 0; // 4. Return NormalCompletion(null). return realm.intrinsics.null; } // ECMA262 24.2.1.1 function GetViewValue(realm, view, requestIndex, isLittleEndian, type) { view = view.throwIfNotConcrete(); // 1. If Type(view) is not Object, throw a TypeError exception. if (!(view instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(view) is not Object"); } // 2. If view does not have a [[DataView]] internal slot, throw a TypeError exception. if (!("$DataView" in view)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "view does not have a [[DataView]] internal slot"); } // 3. Assert: view has a [[ViewedArrayBuffer]] internal slot. (0, _invariant2.default)(view.$ViewedArrayBuffer); // 4. Let getIndex be ? ToIndex(requestIndex). let getIndex = _singletons.To.ToIndexPartial(realm, requestIndex); // 5. Let littleEndian be ToBoolean(isLittleEndian). let littleEndian = _singletons.To.ToBooleanPartial(realm, isLittleEndian); // 6. Let buffer be view.[[ViewedArrayBuffer]]. let buffer = view.$ViewedArrayBuffer; (0, _invariant2.default)(buffer); // 7. If IsDetachedBuffer(buffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, buffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(buffer) is true"); } // 8. Let viewOffset be view.[[ByteOffset]]. let viewOffset = view.$ByteOffset; (0, _invariant2.default)(typeof viewOffset === "number"); // 9. Let viewSize be view.[[ByteLength]]. let viewSize = view.$ByteLength; (0, _invariant2.default)(typeof viewSize === "number"); // 10. Let elementSize be the Number value of the Element Size value specified in Table 50 for Element Type type. let elementSize = _types.ElementSize[type]; // 11. If getIndex + elementSize > viewSize, throw a RangeError exception. if (getIndex + elementSize > viewSize) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "getIndex + elementSize > viewSize"); } // 12. Let bufferIndex be getIndex + viewOffset. let bufferIndex = getIndex + viewOffset; // 13. Return GetValueFromBuffer(buffer, bufferIndex, type, littleEndian). return GetValueFromBuffer(realm, buffer, bufferIndex, type, littleEndian); } // ECMA262 24.1.1.5 function GetValueFromBuffer(realm, arrayBuffer, byteIndex, type, isLittleEndian) { // 1. Assert: IsDetachedBuffer(arrayBuffer) is false. (0, _invariant2.default)((0, _is.IsDetachedBuffer)(realm, arrayBuffer) === false); // 2. Assert: There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type. (0, _invariant2.default)(arrayBuffer.$ArrayBufferData instanceof Uint8Array && byteIndex + _types.ElementSize[type] <= arrayBuffer.$ArrayBufferData.length); // 3. Assert: byteIndex is an integer value ≥ 0. (0, _invariant2.default)(byteIndex >= 0); // 4. Let block be arrayBuffer.[[ArrayBufferData]]. let block = arrayBuffer.$ArrayBufferData; (0, _invariant2.default)(block instanceof Uint8Array); // 5. Let elementSize be the Number value of the Element Size value specified in Table 50 for Element Type type. let elementSize = _types.ElementSize[type]; // 6. Let rawValue be a List of elementSize containing, in order, the elementSize sequence of bytes starting with block[byteIndex]. let rawValue = new DataView(block.buffer, byteIndex, elementSize); // 7. If isLittleEndian is not present, set isLittleEndian to either true or false. The choice is implementation dependent and should be the alternative that is most efficient for the implementation. An implementation must use the same value each time this step is executed and the same value must be used for the corresponding step in the SetValueInBuffer abstract operation. if (isLittleEndian === undefined) isLittleEndian = true; // 8. If isLittleEndian is false, reverse the order of the elements of rawValue. // 9. If type is "Float32", then if (type === "Float32") { // a. Let value be the byte elements of rawValue concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2008 binary32 value. // b. If value is an IEEE 754-2008 binary32 NaN value, return the NaN Number value. // c. Return the Number value that corresponds to value. return new _index.NumberValue(realm, rawValue.getFloat32(0, isLittleEndian)); } // 10. If type is "Float64", then if (type === "Float64") { // a. Let value be the byte elements of rawValue concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2008 binary64 value. // b. If value is an IEEE 754-2008 binary64 NaN value, return the NaN Number value. // c. Return the Number value that corresponds to value. return new _index.NumberValue(realm, rawValue.getFloat64(0, isLittleEndian)); } let intValue; // 11. If the first code unit of type is "U", then if (type === "Uint8" || type === "Uint16" || type === "Uint32" || type === "Uint8Clamped") { // a. Let intValue be the byte elements of rawValue concatenated and interpreted as a bit string encoding of an unsigned little-endian binary number. if (elementSize === 1) { intValue = rawValue.getUint8(0); } else if (elementSize === 2) { intValue = rawValue.getUint16(0, isLittleEndian); } else { intValue = rawValue.getUint32(0, isLittleEndian); } } else { // 12. Else, // a. Let intValue be the byte elements of rawValue concatenated and interpreted as a bit string encoding of a binary little-endian 2's complement number of bit length elementSize × 8. if (elementSize === 1) { intValue = rawValue.getInt8(0); } else if (elementSize === 2) { intValue = rawValue.getInt16(0, isLittleEndian); } else { intValue = rawValue.getInt32(0, isLittleEndian); } } // 13. Return the Number value that corresponds to intValue. return new _index.NumberValue(realm, intValue); } // ECMA262 24.2.1.2 function SetViewValue(realm, view, requestIndex, isLittleEndian, type, value) { view = view.throwIfNotConcrete(); // 1. If Type(view) is not Object, throw a TypeError exception. if (!(view instanceof _index.ObjectValue)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "Type(view) is not Object"); } // 2. If view does not have a [[DataView]] internal slot, throw a TypeError exception. if (!("$DataView" in view)) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "view does not have a [[DataView]] internal slot"); } // 3. Assert: view has a [[ViewedArrayBuffer]] internal slot. (0, _invariant2.default)(view.$ViewedArrayBuffer); // 4. Let getIndex be ? ToIndex(requestIndex). let getIndex = _singletons.To.ToIndexPartial(realm, requestIndex); // 5. Let numberValue be ? ToNumber(value). let numberValue = _singletons.To.ToNumber(realm, value); // 6. Let littleEndian be ToBoolean(isLittleEndian). let littleEndian = _singletons.To.ToBooleanPartial(realm, isLittleEndian); // 7. Let buffer be view.[[ViewedArrayBuffer]]. let buffer = view.$ViewedArrayBuffer; (0, _invariant2.default)(buffer); // 8. If IsDetachedBuffer(buffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, buffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(buffer) is true"); } // 9. Let viewOffset be view.[[ByteOffset]]. let viewOffset = view.$ByteOffset; (0, _invariant2.default)(typeof viewOffset === "number"); // 10. Let viewSize be view.[[ByteLength]]. let viewSize = view.$ByteLength; (0, _invariant2.default)(typeof viewSize === "number"); // 11. Let elementSize be the Number value of the Element Size value specified in Table 50 for Element Type type. let elementSize = _types.ElementSize[type]; // 12. If getIndex + elementSize > viewSize, throw a RangeError exception. if (getIndex + elementSize > viewSize) { throw realm.createErrorThrowCompletion(realm.intrinsics.RangeError, "getIndex + elementSize > viewSize"); } // 13. Let bufferIndex be getIndex + viewOffset. let bufferIndex = getIndex + viewOffset; // 14. Return SetValueInBuffer(buffer, bufferIndex, type, numberValue, littleEndian). return SetValueInBuffer(realm, buffer, bufferIndex, type, numberValue, littleEndian); } // ECMA262 24.1.1.4 function CloneArrayBuffer(realm, srcBuffer, srcByteOffset, cloneConstructor) { // 1. Assert: Type(srcBuffer) is Object and it has an [[ArrayBufferData]] internal slot. (0, _invariant2.default)(srcBuffer instanceof _index.ObjectValue && srcBuffer.$ArrayBufferData); // 2. If cloneConstructor is not present, then if (cloneConstructor === undefined) { // a. Let cloneConstructor be ? SpeciesConstructor(srcBuffer, %ArrayBuffer%). cloneConstructor = (0, _construct.SpeciesConstructor)(realm, srcBuffer, realm.intrinsics.ArrayBuffer); // b. If IsDetachedBuffer(srcBuffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, srcBuffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(srcBuffer) is true"); } } // 3. Else, Assert: IsConstructor(cloneConstructor) is true. (0, _invariant2.default)((0, _index2.IsConstructor)(realm, cloneConstructor) === true, "IsConstructor(cloneConstructor) is true"); // 4. Let srcLength be the value of srcBuffer's [[ArrayBufferByteLength]] internal slot. let srcLength = srcBuffer.$ArrayBufferByteLength; (0, _invariant2.default)(typeof srcLength === "number"); // 5. Assert: srcByteOffset ≤ srcLength. (0, _invariant2.default)(srcByteOffset <= srcLength, "srcByteOffset ≤ srcLength"); // 6. Let cloneLength be srcLength - srcByteOffset. let cloneLength = srcLength - srcByteOffset; // 7. Let srcBlock be srcBuffer.[[ArrayBufferData]]. let srcBlock = srcBuffer.$ArrayBufferData; (0, _invariant2.default)(srcBlock); // 8. Let targetBuffer be ? AllocateArrayBuffer(cloneConstructor, srcLength). let targetBuffer = AllocateArrayBuffer(realm, cloneConstructor, srcLength); // 9. If IsDetachedBuffer(srcBuffer) is true, throw a TypeError exception. if ((0, _is.IsDetachedBuffer)(realm, srcBuffer) === true) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "IsDetachedBuffer(srcBuffer) is true"); } // 10. Let targetBlock be targetBuffer.[[ArrayBufferData]]. let targetBlock = targetBuffer.$ArrayBufferData; (0, _invariant2.default)(targetBlock); // 11. Perform CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, cloneLength). CopyDataBlockBytes(realm, targetBlock, 0, srcBlock, srcByteOffset, cloneLength); // 12. Return targetBuffer. return targetBuffer; } // ECMA262 24.1.1.6 function SetValueInBuffer(realm, arrayBuffer, byteIndex, type, value, isLittleEndian) { // 1. Assert: IsDetachedBuffer(arrayBuffer) is false. (0, _invariant2.default)((0, _is.IsDetachedBuffer)(realm, arrayBuffer) === false); // 2. Assert: There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type. (0, _invariant2.default)(arrayBuffer.$ArrayBufferData instanceof Uint8Array && byteIndex + _types.ElementSize[type] <= arrayBuffer.$ArrayBufferData.length); // 3. Assert: byteIndex is an integer value ≥ 0. (0, _invariant2.default)(byteIndex >= 0); // 4. Assert: Type(value) is Number. (0, _invariant2.default)(typeof value === "number"); // 5. Let block be arrayBuffer.[[ArrayBufferData]]. let block = _singletons.Properties.ThrowIfInternalSlotNotWritable(realm, arrayBuffer, "$ArrayBufferData").$ArrayBufferData; // 6. Assert: block is not undefined. (0, _invariant2.default)(block instanceof Uint8Array); // 7. If isLittleEndian is not present, set isLittleEndian to either true or false. The choice is implementation dependent and should be the alternative that is most efficient for the implementation. An implementation must use the same value each time this step is executed and the same value must be used for the corresponding step in the SetValueInBuffer abstract operation. if (isLittleEndian === undefined) isLittleEndian = true; let rawBytes = new Uint8Array(_types.ElementSize[type]); // 8. If type is "Float32", then if (type === "Float32") { // a. Set rawBytes to a List containing the 4 bytes that are the result of converting value to IEEE 754-2008 binary32 format using “Round to nearest, ties to even” rounding mode. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawValue may be set to any implementation chosen IEEE 754-2008 binary32 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishable NaN value. new DataView(rawBytes.buffer).setFloat32(0, value, isLittleEndian); } else if (type === "Float64") { // 9. Else if type is "Float64", then // a. Set rawBytes to a List containing the 8 bytes that are the IEEE 754-2008 binary64 format encoding of value. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawValue may be set to any implementation chosen IEEE 754-2008 binary64 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishable NaN value. new DataView(rawBytes.buffer).setFloat64(0, value, isLittleEndian); } else { // 10. Else, // a. Let n be the Number value of the Element Size specified in Table 50 for Element Type type. let n = _types.ElementSize[type]; // b. Let convOp be the abstract operation named in the Conversion Operation column in Table 50 for Element Type type. let convOp = _singletons.To.ElementConv[type]; // c. Let intValue be convOp(value). let intValue = convOp(realm, value); // d. If intValue ≥ 0, then if (intValue > 0) { // i. Let rawBytes be a List containing the n-byte binary encoding of intValue. If isLittleEndian is false, the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order. if (n === 1) { new DataView(rawBytes.buffer).setUint8(0, intValue); } else if (n === 2) { new DataView(rawBytes.buffer).setUint16(0, intValue, isLittleEndian); } else if (n === 4) { new DataView(rawBytes.buffer).setUint32(0, intValue, isLittleEndian); } else { (0, _invariant2.default)(false); } } else { // e. Else, // i. Let rawBytes be a List containing the n-byte binary 2's complement encoding of intValue. If isLittleEndian is false, the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order. if (n === 1) { new DataView(rawBytes.buffer).setInt8(0, intValue); } else if (n === 2) { new DataView(rawBytes.buffer).setInt16(0, intValue, isLittleEndian); } else if (n === 4) { new DataView(rawBytes.buffer).setInt32(0, intValue, isLittleEndian); } else { (0, _invariant2.default)(false); } } } // 11. Store the individual bytes of rawBytes into block, in order, starting at block[byteIndex]. for (let i = 0; i < rawBytes.length; ++i) { block[byteIndex + i] = rawBytes[i]; } // 12. Return NormalCompletion(undefined). return realm.intrinsics.undefined; } //# sourceMappingURL=arraybuffer.js.map /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.protoExpression = exports.constructorExpression = exports.emptyExpression = exports.nullExpression = exports.voidExpression = undefined; var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ const voidExpression = exports.voidExpression = t.unaryExpression("void", t.numericLiteral(0), true); const nullExpression = exports.nullExpression = t.nullLiteral(); const emptyExpression = exports.emptyExpression = t.identifier("__empty"); const constructorExpression = exports.constructorExpression = t.identifier("__constructor"); const protoExpression = exports.protoExpression = t.identifier("__proto__"); //# sourceMappingURL=internalizer.js.map /***/ }), /* 126 */ /***/ (function(module, exports, __webpack_require__) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = Stream; var EE = __webpack_require__(108).EventEmitter; var inherits = __webpack_require__(8); inherits(Stream, EE); Stream.Readable = __webpack_require__(331); Stream.Writable = __webpack_require__(2244); Stream.Duplex = __webpack_require__(2245); Stream.Transform = __webpack_require__(2246); Stream.PassThrough = __webpack_require__(2247); // Backwards-compat with node 0.4.x Stream.Stream = Stream; // old-style streams. Note that the pipe method (the only relevant // part of this class) is overridden in the Readable class. function Stream() { EE.call(this); } Stream.prototype.pipe = function(dest, options) { var source = this; function ondata(chunk) { if (dest.writable) { if (false === dest.write(chunk) && source.pause) { source.pause(); } } } source.on('data', ondata); function ondrain() { if (source.readable && source.resume) { source.resume(); } } dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once. if (!dest._isStdio && (!options || options.end !== false)) { source.on('end', onend); source.on('close', onclose); } var didOnEnd = false; function onend() { if (didOnEnd) return; didOnEnd = true; dest.end(); } function onclose() { if (didOnEnd) return; didOnEnd = true; if (typeof dest.destroy === 'function') dest.destroy(); } // don't leave dangling pipes when there are errors. function onerror(er) { cleanup(); if (EE.listenerCount(this, 'error') === 0) { throw er; // Unhandled stream error in pipe. } } source.on('error', onerror); dest.on('error', onerror); // remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata); dest.removeListener('drain', ondrain); source.removeListener('end', onend); source.removeListener('close', onclose); source.removeListener('error', onerror); dest.removeListener('error', onerror); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('close', cleanup); } source.on('end', cleanup); source.on('close', cleanup); dest.on('close', cleanup); dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C) return dest; }; /***/ }), /* 127 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global, process) { function oldBrowser () { throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') } var Buffer = __webpack_require__(15).Buffer var crypto = global.crypto || global.msCrypto if (crypto && crypto.getRandomValues) { module.exports = randomBytes } else { module.exports = oldBrowser } function randomBytes (size, cb) { // phantomjs needs to throw if (size > 65536) throw new Error('requested too many random bytes') // in case browserify isn't using the Uint8Array version var rawBytes = new global.Uint8Array(size) // This will not work in older browsers. // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues if (size > 0) { // getRandomValues fails on IE if size == 0 crypto.getRandomValues(rawBytes) } // XXX: phantomjs doesn't like a buffer being passed here var bytes = Buffer.from(rawBytes.buffer) if (typeof cb === 'function') { return process.nextTick(function () { cb(null, bytes) }) } return bytes } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(14), __webpack_require__(7))) /***/ }), /* 128 */ /***/ (function(module, exports, __webpack_require__) { var Buffer = __webpack_require__(15).Buffer // prototype class for hash functions function Hash (blockSize, finalSize) { this._block = Buffer.alloc(blockSize) this._finalSize = finalSize this._blockSize = blockSize this._len = 0 } Hash.prototype.update = function (data, enc) { if (typeof data === 'string') { enc = enc || 'utf8' data = Buffer.from(data, enc) } var block = this._block var blockSize = this._blockSize var length = data.length var accum = this._len for (var offset = 0; offset < length;) { var assigned = accum % blockSize var remainder = Math.min(length - offset, blockSize - assigned) for (var i = 0; i < remainder; i++) { block[assigned + i] = data[offset + i] } accum += remainder offset += remainder if ((accum % blockSize) === 0) { this._update(block) } } this._len += length return this } Hash.prototype.digest = function (enc) { var rem = this._len % this._blockSize this._block[rem] = 0x80 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize this._block.fill(0, rem + 1) if (rem >= this._finalSize) { this._update(this._block) this._block.fill(0) } var bits = this._len * 8 // uint32 if (bits <= 0xffffffff) { this._block.writeUInt32BE(bits, this._blockSize - 4) // uint64 } else { var lowBits = (bits & 0xffffffff) >>> 0 var highBits = (bits - lowBits) / 0x100000000 this._block.writeUInt32BE(highBits, this._blockSize - 8) this._block.writeUInt32BE(lowBits, this._blockSize - 4) } this._update(this._block) var hash = this._hash() return enc ? hash.toString(enc) : hash } Hash.prototype._update = function () { throw new Error('_update must be implemented by subclass') } module.exports = Hash /***/ }), /* 129 */ /***/ (function(module, exports) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }), /* 130 */ /***/ (function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(239), baseAssignValue = __webpack_require__(354); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; /***/ }), /* 131 */ /***/ (function(module, exports) { /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; /***/ }), /* 132 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isValidIdentifier; function _esutils() { const data = _interopRequireDefault(__webpack_require__(133)); _esutils = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isValidIdentifier(name) { if (typeof name !== "string" || _esutils().default.keyword.isReservedWordES6(name, true)) { return false; } else if (name === "await") { return false; } else { return _esutils().default.keyword.isIdentifierNameES6(name); } } /***/ }), /* 133 */ /***/ (function(module, exports, __webpack_require__) { /* Copyright (C) 2013 Yusuke Suzuki Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { 'use strict'; exports.ast = __webpack_require__(790); exports.code = __webpack_require__(365); exports.keyword = __webpack_require__(791); }()); /* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), /* 134 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cloneNode; var _definitions = __webpack_require__(57); const has = Function.call.bind(Object.prototype.hasOwnProperty); function cloneIfNode(obj, deep) { if (obj && typeof obj.type === "string" && obj.type !== "CommentLine" && obj.type !== "CommentBlock") { return cloneNode(obj, deep); } return obj; } function cloneIfNodeOrArray(obj, deep) { if (Array.isArray(obj)) { return obj.map(node => cloneIfNode(node, deep)); } return cloneIfNode(obj, deep); } function cloneNode(node, deep = true) { if (!node) return node; const { type } = node; const newNode = { type }; if (type === "Identifier") { newNode.name = node.name; } else if (!has(_definitions.NODE_FIELDS, type)) { throw new Error(`Unknown node type: "${type}"`); } else { for (const field of Object.keys(_definitions.NODE_FIELDS[type])) { if (has(node, field)) { newNode[field] = deep ? cloneIfNodeOrArray(node[field], true) : node[field]; } } } if (has(node, "loc")) { newNode.loc = node.loc; } if (has(node, "leadingComments")) { newNode.leadingComments = node.leadingComments; } if (has(node, "innerComments")) { newNode.innerComments = node.innerCmments; } if (has(node, "trailingComments")) { newNode.trailingComments = node.trailingComments; } if (has(node, "extra")) { newNode.extra = Object.assign({}, node.extra); } return newNode; } /***/ }), /* 135 */ /***/ (function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(842); /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } module.exports = toInteger; /***/ }), /* 136 */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(75), isObjectLike = __webpack_require__(56); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }), /* 137 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /***/ }), /* 138 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.loadOptions = loadOptions; Object.defineProperty(exports, "default", { enumerable: true, get: function () { return _full.default; } }); Object.defineProperty(exports, "loadPartialConfig", { enumerable: true, get: function () { return _partial.loadPartialConfig; } }); var _full = _interopRequireDefault(__webpack_require__(918)); var _partial = __webpack_require__(414); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function loadOptions(opts) { const config = (0, _full.default)(opts); return config ? config.options : null; } /***/ }), /* 139 */ /***/ (function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(974), baseMatchesProperty = __webpack_require__(982), identity = __webpack_require__(188), isArray = __webpack_require__(39), property = __webpack_require__(989); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }), /* 140 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /***/ }), /* 141 */ /***/ (function(module, exports, __webpack_require__) { module.exports = function (fork) { fork.use(__webpack_require__(450)); var types = fork.use(__webpack_require__(32)); var def = types.Type.def; var or = types.Type.or; var builtin = types.builtInTypes; var defaults = fork.use(__webpack_require__(80)).defaults; def("Function") .field("async", Boolean, defaults["false"]); def("SpreadProperty") .bases("Node") .build("argument") .field("argument", def("Expression")); def("ObjectExpression") .field("properties", [or(def("Property"), def("SpreadProperty"))]); def("SpreadPropertyPattern") .bases("Pattern") .build("argument") .field("argument", def("Pattern")); def("ObjectPattern") .field("properties", [or( def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern") )]); def("AwaitExpression") .bases("Expression") .build("argument", "all") .field("argument", or(def("Expression"), null)) .field("all", Boolean, defaults["false"]); }; /***/ }), /* 142 */ /***/ (function(module, exports, __webpack_require__) { var assert = __webpack_require__(36); var sourceMap = __webpack_require__(109); var normalizeOptions = __webpack_require__(272).normalize; var secretKey = __webpack_require__(456).makeUniqueKey(); var types = __webpack_require__(67); var isString = types.builtInTypes.string; var comparePos = __webpack_require__(110).comparePos; var Mapping = __webpack_require__(1141); // Goals: // 1. Minimize new string creation. // 2. Keep (de)identation O(lines) time. // 3. Permit negative indentations. // 4. Enforce immutability. // 5. No newline characters. var useSymbol = typeof Symbol === "function"; var secretKey = "recastLinesSecret"; if (useSymbol) { secretKey = Symbol.for(secretKey); } function getSecret(lines) { return lines[secretKey]; } function Lines(infos, sourceFileName) { assert.ok(this instanceof Lines); assert.ok(infos.length > 0); if (sourceFileName) { isString.assert(sourceFileName); } else { sourceFileName = null; } setSymbolOrKey(this, secretKey, { infos: infos, mappings: [], name: sourceFileName, cachedSourceMap: null }); this.length = infos.length; this.name = sourceFileName; if (sourceFileName) { getSecret(this).mappings.push(new Mapping(this, { start: this.firstPos(), end: this.lastPos() })); } } function setSymbolOrKey(obj, key, value) { if (useSymbol) { return obj[key] = value; } Object.defineProperty(obj, key, { value: value, enumerable: false, writable: false, configurable: true }); return value; } // Exposed for instanceof checks. The fromString function should be used // to create new Lines objects. exports.Lines = Lines; var Lp = Lines.prototype; function copyLineInfo(info) { return { line: info.line, indent: info.indent, locked: info.locked, sliceStart: info.sliceStart, sliceEnd: info.sliceEnd }; } var fromStringCache = {}; var hasOwn = fromStringCache.hasOwnProperty; var maxCacheKeyLen = 10; function countSpaces(spaces, tabWidth) { var count = 0; var len = spaces.length; for (var i = 0; i < len; ++i) { switch (spaces.charCodeAt(i)) { case 9: // '\t' assert.strictEqual(typeof tabWidth, "number"); assert.ok(tabWidth > 0); var next = Math.ceil(count / tabWidth) * tabWidth; if (next === count) { count += tabWidth; } else { count = next; } break; case 11: // '\v' case 12: // '\f' case 13: // '\r' case 0xfeff: // zero-width non-breaking space // These characters contribute nothing to indentation. break; case 32: // ' ' default: // Treat all other whitespace like ' '. count += 1; break; } } return count; } exports.countSpaces = countSpaces; var leadingSpaceExp = /^\s*/; // As specified here: http://www.ecma-international.org/ecma-262/6.0/#sec-line-terminators var lineTerminatorSeqExp = /\u000D\u000A|\u000D(?!\u000A)|\u000A|\u2028|\u2029/; /** * @param {Object} options - Options object that configures printing. */ function fromString(string, options) { if (string instanceof Lines) return string; string += ""; var tabWidth = options && options.tabWidth; var tabless = string.indexOf("\t") < 0; var locked = !! (options && options.locked); var cacheable = !options && tabless && (string.length <= maxCacheKeyLen); assert.ok(tabWidth || tabless, "No tab width specified but encountered tabs in string\n" + string); if (cacheable && hasOwn.call(fromStringCache, string)) return fromStringCache[string]; var lines = new Lines(string.split(lineTerminatorSeqExp).map(function(line) { var spaces = leadingSpaceExp.exec(line)[0]; return { line: line, indent: countSpaces(spaces, tabWidth), // Boolean indicating whether this line can be reindented. locked: locked, sliceStart: spaces.length, sliceEnd: line.length }; }), normalizeOptions(options).sourceFileName); if (cacheable) fromStringCache[string] = lines; return lines; } exports.fromString = fromString; function isOnlyWhitespace(string) { return !/\S/.test(string); } Lp.toString = function(options) { return this.sliceString(this.firstPos(), this.lastPos(), options); }; Lp.getSourceMap = function(sourceMapName, sourceRoot) { if (!sourceMapName) { // Although we could make up a name or generate an anonymous // source map, instead we assume that any consumer who does not // provide a name does not actually want a source map. return null; } var targetLines = this; function updateJSON(json) { json = json || {}; isString.assert(sourceMapName); json.file = sourceMapName; if (sourceRoot) { isString.assert(sourceRoot); json.sourceRoot = sourceRoot; } return json; } var secret = getSecret(targetLines); if (secret.cachedSourceMap) { // Since Lines objects are immutable, we can reuse any source map // that was previously generated. Nevertheless, we return a new // JSON object here to protect the cached source map from outside // modification. return updateJSON(secret.cachedSourceMap.toJSON()); } var smg = new sourceMap.SourceMapGenerator(updateJSON()); var sourcesToContents = {}; secret.mappings.forEach(function(mapping) { var sourceCursor = mapping.sourceLines.skipSpaces( mapping.sourceLoc.start ) || mapping.sourceLines.lastPos(); var targetCursor = targetLines.skipSpaces( mapping.targetLoc.start ) || targetLines.lastPos(); while (comparePos(sourceCursor, mapping.sourceLoc.end) < 0 && comparePos(targetCursor, mapping.targetLoc.end) < 0) { var sourceChar = mapping.sourceLines.charAt(sourceCursor); var targetChar = targetLines.charAt(targetCursor); assert.strictEqual(sourceChar, targetChar); var sourceName = mapping.sourceLines.name; // Add mappings one character at a time for maximum resolution. smg.addMapping({ source: sourceName, original: { line: sourceCursor.line, column: sourceCursor.column }, generated: { line: targetCursor.line, column: targetCursor.column } }); if (!hasOwn.call(sourcesToContents, sourceName)) { var sourceContent = mapping.sourceLines.toString(); smg.setSourceContent(sourceName, sourceContent); sourcesToContents[sourceName] = sourceContent; } targetLines.nextPos(targetCursor, true); mapping.sourceLines.nextPos(sourceCursor, true); } }); secret.cachedSourceMap = smg; return smg.toJSON(); }; Lp.bootstrapCharAt = function(pos) { assert.strictEqual(typeof pos, "object"); assert.strictEqual(typeof pos.line, "number"); assert.strictEqual(typeof pos.column, "number"); var line = pos.line, column = pos.column, strings = this.toString().split(lineTerminatorSeqExp), string = strings[line - 1]; if (typeof string === "undefined") return ""; if (column === string.length && line < strings.length) return "\n"; if (column >= string.length) return ""; return string.charAt(column); }; Lp.charAt = function(pos) { assert.strictEqual(typeof pos, "object"); assert.strictEqual(typeof pos.line, "number"); assert.strictEqual(typeof pos.column, "number"); var line = pos.line, column = pos.column, secret = getSecret(this), infos = secret.infos, info = infos[line - 1], c = column; if (typeof info === "undefined" || c < 0) return ""; var indent = this.getIndentAt(line); if (c < indent) return " "; c += info.sliceStart - indent; if (c === info.sliceEnd && line < this.length) return "\n"; if (c >= info.sliceEnd) return ""; return info.line.charAt(c); }; Lp.stripMargin = function(width, skipFirstLine) { if (width === 0) return this; assert.ok(width > 0, "negative margin: " + width); if (skipFirstLine && this.length === 1) return this; var secret = getSecret(this); var lines = new Lines(secret.infos.map(function(info, i) { if (info.line && (i > 0 || !skipFirstLine)) { info = copyLineInfo(info); info.indent = Math.max(0, info.indent - width); } return info; })); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { newMappings.push(mapping.indent(width, skipFirstLine, true)); }); } return lines; }; Lp.indent = function(by) { if (by === 0) return this; var secret = getSecret(this); var lines = new Lines(secret.infos.map(function(info) { if (info.line && ! info.locked) { info = copyLineInfo(info); info.indent += by; } return info })); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { newMappings.push(mapping.indent(by)); }); } return lines; }; Lp.indentTail = function(by) { if (by === 0) return this; if (this.length < 2) return this; var secret = getSecret(this); var lines = new Lines(secret.infos.map(function(info, i) { if (i > 0 && info.line && ! info.locked) { info = copyLineInfo(info); info.indent += by; } return info; })); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { newMappings.push(mapping.indent(by, true)); }); } return lines; }; Lp.lockIndentTail = function () { if (this.length < 2) { return this; } var infos = getSecret(this).infos; return new Lines(infos.map(function (info, i) { info = copyLineInfo(info); info.locked = i > 0; return info; })); }; Lp.getIndentAt = function(line) { assert.ok(line >= 1, "no line " + line + " (line numbers start from 1)"); var secret = getSecret(this), info = secret.infos[line - 1]; return Math.max(info.indent, 0); }; Lp.guessTabWidth = function() { var secret = getSecret(this); if (hasOwn.call(secret, "cachedTabWidth")) { return secret.cachedTabWidth; } var counts = []; // Sparse array. var lastIndent = 0; for (var line = 1, last = this.length; line <= last; ++line) { var info = secret.infos[line - 1]; var sliced = info.line.slice(info.sliceStart, info.sliceEnd); // Whitespace-only lines don't tell us much about the likely tab // width of this code. if (isOnlyWhitespace(sliced)) { continue; } var diff = Math.abs(info.indent - lastIndent); counts[diff] = ~~counts[diff] + 1; lastIndent = info.indent; } var maxCount = -1; var result = 2; for (var tabWidth = 1; tabWidth < counts.length; tabWidth += 1) { if (hasOwn.call(counts, tabWidth) && counts[tabWidth] > maxCount) { maxCount = counts[tabWidth]; result = tabWidth; } } return secret.cachedTabWidth = result; }; // Determine if the list of lines has a first line that starts with a // // or /* comment. If this is the case, the code may need to be wrapped in // parens to avoid ASI issues. Lp.startsWithComment = function () { var secret = getSecret(this); if (secret.infos.length === 0) { return false; } var firstLineInfo = secret.infos[0], sliceStart = firstLineInfo.sliceStart, sliceEnd = firstLineInfo.sliceEnd, firstLine = firstLineInfo.line.slice(sliceStart, sliceEnd).trim(); return firstLine.length === 0 || firstLine.slice(0, 2) === "//" || firstLine.slice(0, 2) === "/*"; }; Lp.isOnlyWhitespace = function() { return isOnlyWhitespace(this.toString()); }; Lp.isPrecededOnlyByWhitespace = function(pos) { var secret = getSecret(this); var info = secret.infos[pos.line - 1]; var indent = Math.max(info.indent, 0); var diff = pos.column - indent; if (diff <= 0) { // If pos.column does not exceed the indentation amount, then // there must be only whitespace before it. return true; } var start = info.sliceStart; var end = Math.min(start + diff, info.sliceEnd); var prefix = info.line.slice(start, end); return isOnlyWhitespace(prefix); }; Lp.getLineLength = function(line) { var secret = getSecret(this), info = secret.infos[line - 1]; return this.getIndentAt(line) + info.sliceEnd - info.sliceStart; }; Lp.nextPos = function(pos, skipSpaces) { var l = Math.max(pos.line, 0), c = Math.max(pos.column, 0); if (c < this.getLineLength(l)) { pos.column += 1; return skipSpaces ? !!this.skipSpaces(pos, false, true) : true; } if (l < this.length) { pos.line += 1; pos.column = 0; return skipSpaces ? !!this.skipSpaces(pos, false, true) : true; } return false; }; Lp.prevPos = function(pos, skipSpaces) { var l = pos.line, c = pos.column; if (c < 1) { l -= 1; if (l < 1) return false; c = this.getLineLength(l); } else { c = Math.min(c - 1, this.getLineLength(l)); } pos.line = l; pos.column = c; return skipSpaces ? !!this.skipSpaces(pos, true, true) : true; }; Lp.firstPos = function() { // Trivial, but provided for completeness. return { line: 1, column: 0 }; }; Lp.lastPos = function() { return { line: this.length, column: this.getLineLength(this.length) }; }; Lp.skipSpaces = function(pos, backward, modifyInPlace) { if (pos) { pos = modifyInPlace ? pos : { line: pos.line, column: pos.column }; } else if (backward) { pos = this.lastPos(); } else { pos = this.firstPos(); } if (backward) { while (this.prevPos(pos)) { if (!isOnlyWhitespace(this.charAt(pos)) && this.nextPos(pos)) { return pos; } } return null; } else { while (isOnlyWhitespace(this.charAt(pos))) { if (!this.nextPos(pos)) { return null; } } return pos; } }; Lp.trimLeft = function() { var pos = this.skipSpaces(this.firstPos(), false, true); return pos ? this.slice(pos) : emptyLines; }; Lp.trimRight = function() { var pos = this.skipSpaces(this.lastPos(), true, true); return pos ? this.slice(this.firstPos(), pos) : emptyLines; }; Lp.trim = function() { var start = this.skipSpaces(this.firstPos(), false, true); if (start === null) return emptyLines; var end = this.skipSpaces(this.lastPos(), true, true); assert.notStrictEqual(end, null); return this.slice(start, end); }; Lp.eachPos = function(callback, startPos, skipSpaces) { var pos = this.firstPos(); if (startPos) { pos.line = startPos.line, pos.column = startPos.column } if (skipSpaces && !this.skipSpaces(pos, false, true)) { return; // Encountered nothing but spaces. } do callback.call(this, pos); while (this.nextPos(pos, skipSpaces)); }; Lp.bootstrapSlice = function(start, end) { var strings = this.toString().split( lineTerminatorSeqExp ).slice( start.line - 1, end.line ); strings.push(strings.pop().slice(0, end.column)); strings[0] = strings[0].slice(start.column); return fromString(strings.join("\n")); }; Lp.slice = function(start, end) { if (!end) { if (!start) { // The client seems to want a copy of this Lines object, but // Lines objects are immutable, so it's perfectly adequate to // return the same object. return this; } // Slice to the end if no end position was provided. end = this.lastPos(); } var secret = getSecret(this); var sliced = secret.infos.slice(start.line - 1, end.line); if (start.line === end.line) { sliced[0] = sliceInfo(sliced[0], start.column, end.column); } else { assert.ok(start.line < end.line); sliced[0] = sliceInfo(sliced[0], start.column); sliced.push(sliceInfo(sliced.pop(), 0, end.column)); } var lines = new Lines(sliced); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { var sliced = mapping.slice(this, start, end); if (sliced) { newMappings.push(sliced); } }, this); } return lines; }; function sliceInfo(info, startCol, endCol) { var sliceStart = info.sliceStart; var sliceEnd = info.sliceEnd; var indent = Math.max(info.indent, 0); var lineLength = indent + sliceEnd - sliceStart; if (typeof endCol === "undefined") { endCol = lineLength; } startCol = Math.max(startCol, 0); endCol = Math.min(endCol, lineLength); endCol = Math.max(endCol, startCol); if (endCol < indent) { indent = endCol; sliceEnd = sliceStart; } else { sliceEnd -= lineLength - endCol; } lineLength = endCol; lineLength -= startCol; if (startCol < indent) { indent -= startCol; } else { startCol -= indent; indent = 0; sliceStart += startCol; } assert.ok(indent >= 0); assert.ok(sliceStart <= sliceEnd); assert.strictEqual(lineLength, indent + sliceEnd - sliceStart); if (info.indent === indent && info.sliceStart === sliceStart && info.sliceEnd === sliceEnd) { return info; } return { line: info.line, indent: indent, // A destructive slice always unlocks indentation. locked: false, sliceStart: sliceStart, sliceEnd: sliceEnd }; } Lp.bootstrapSliceString = function(start, end, options) { return this.slice(start, end).toString(options); }; Lp.sliceString = function(start, end, options) { if (!end) { if (!start) { // The client seems to want a copy of this Lines object, but // Lines objects are immutable, so it's perfectly adequate to // return the same object. return this; } // Slice to the end if no end position was provided. end = this.lastPos(); } options = normalizeOptions(options); var infos = getSecret(this).infos; var parts = []; var tabWidth = options.tabWidth; for (var line = start.line; line <= end.line; ++line) { var info = infos[line - 1]; if (line === start.line) { if (line === end.line) { info = sliceInfo(info, start.column, end.column); } else { info = sliceInfo(info, start.column); } } else if (line === end.line) { info = sliceInfo(info, 0, end.column); } var indent = Math.max(info.indent, 0); var before = info.line.slice(0, info.sliceStart); if (options.reuseWhitespace && isOnlyWhitespace(before) && countSpaces(before, options.tabWidth) === indent) { // Reuse original spaces if the indentation is correct. parts.push(info.line.slice(0, info.sliceEnd)); continue; } var tabs = 0; var spaces = indent; if (options.useTabs) { tabs = Math.floor(indent / tabWidth); spaces -= tabs * tabWidth; } var result = ""; if (tabs > 0) { result += new Array(tabs + 1).join("\t"); } if (spaces > 0) { result += new Array(spaces + 1).join(" "); } result += info.line.slice(info.sliceStart, info.sliceEnd); parts.push(result); } return parts.join(options.lineTerminator); }; Lp.isEmpty = function() { return this.length < 2 && this.getLineLength(1) < 1; }; Lp.join = function(elements) { var separator = this; var separatorSecret = getSecret(separator); var infos = []; var mappings = []; var prevInfo; function appendSecret(secret) { if (secret === null) return; if (prevInfo) { var info = secret.infos[0]; var indent = new Array(info.indent + 1).join(" "); var prevLine = infos.length; var prevColumn = Math.max(prevInfo.indent, 0) + prevInfo.sliceEnd - prevInfo.sliceStart; prevInfo.line = prevInfo.line.slice( 0, prevInfo.sliceEnd) + indent + info.line.slice( info.sliceStart, info.sliceEnd); // If any part of a line is indentation-locked, the whole line // will be indentation-locked. prevInfo.locked = prevInfo.locked || info.locked; prevInfo.sliceEnd = prevInfo.line.length; if (secret.mappings.length > 0) { secret.mappings.forEach(function(mapping) { mappings.push(mapping.add(prevLine, prevColumn)); }); } } else if (secret.mappings.length > 0) { mappings.push.apply(mappings, secret.mappings); } secret.infos.forEach(function(info, i) { if (!prevInfo || i > 0) { prevInfo = copyLineInfo(info); infos.push(prevInfo); } }); } function appendWithSeparator(secret, i) { if (i > 0) appendSecret(separatorSecret); appendSecret(secret); } elements.map(function(elem) { var lines = fromString(elem); if (lines.isEmpty()) return null; return getSecret(lines); }).forEach(separator.isEmpty() ? appendSecret : appendWithSeparator); if (infos.length < 1) return emptyLines; var lines = new Lines(infos); getSecret(lines).mappings = mappings; return lines; }; exports.concat = function(elements) { return emptyLines.join(elements); }; Lp.concat = function(other) { var args = arguments, list = [this]; list.push.apply(list, args); assert.strictEqual(list.length, args.length + 1); return emptyLines.join(list); }; // The emptyLines object needs to be created all the way down here so that // Lines.prototype will be fully populated. var emptyLines = fromString(""); /***/ }), /* 143 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || urlRegexp.test(aPath); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 === null) { return 1; // aStr2 !== null } if (aStr2 === null) { return -1; // aStr1 !== null } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /** * Strip any JSON XSSI avoidance prefix from the string (as documented * in the source maps specification), and then parse the string as * JSON. */ function parseSourceMapInput(str) { return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); } exports.parseSourceMapInput = parseSourceMapInput; /** * Compute the URL of a source given the the source root, the source's * URL, and the source map's URL. */ function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { sourceURL = sourceURL || ''; if (sourceRoot) { // This follows what Chrome does. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { sourceRoot += '/'; } // The spec says: // Line 4: An optional source root, useful for relocating source // files on a server or removing repeated values in the // “sources” entry. This value is prepended to the individual // entries in the “source” field. sourceURL = sourceRoot + sourceURL; } // Historically, SourceMapConsumer did not take the sourceMapURL as // a parameter. This mode is still somewhat supported, which is why // this code block is conditional. However, it's preferable to pass // the source map URL to SourceMapConsumer, so that this function // can implement the source URL resolution algorithm as outlined in // the spec. This block is basically the equivalent of: // new URL(sourceURL, sourceMapURL).toString() // ... except it avoids using URL, which wasn't available in the // older releases of node still supported by this library. // // The spec says: // If the sources are not absolute URLs after prepending of the // “sourceRoot”, the sources are resolved relative to the // SourceMap (like resolving script src in a html document). if (sourceMapURL) { var parsed = urlParse(sourceMapURL); if (!parsed) { throw new Error("sourceMapURL could not be parsed"); } if (parsed.path) { // Strip the last path component, but keep the "/". var index = parsed.path.lastIndexOf('/'); if (index >= 0) { parsed.path = parsed.path.substring(0, index + 1); } } sourceURL = join(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); } exports.computeSourceURL = computeSourceURL; /***/ }), /* 144 */ /***/ (function(module, exports) { module.exports = {}; /***/ }), /* 145 */ /***/ (function(module, exports, __webpack_require__) { /* Copyright (C) 2012-2013 Yusuke Suzuki Copyright (C) 2012 Ariya Hidayat Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*jslint vars:false, bitwise:true*/ /*jshint indent:4*/ /*global exports:true*/ (function clone(exports) { 'use strict'; var Syntax, isArray, VisitorOption, VisitorKeys, objectCreate, objectKeys, BREAK, SKIP, REMOVE; function ignoreJSHintError() { } isArray = Array.isArray; if (!isArray) { isArray = function isArray(array) { return Object.prototype.toString.call(array) === '[object Array]'; }; } function deepCopy(obj) { var ret = {}, key, val; for (key in obj) { if (obj.hasOwnProperty(key)) { val = obj[key]; if (typeof val === 'object' && val !== null) { ret[key] = deepCopy(val); } else { ret[key] = val; } } } return ret; } function shallowCopy(obj) { var ret = {}, key; for (key in obj) { if (obj.hasOwnProperty(key)) { ret[key] = obj[key]; } } return ret; } ignoreJSHintError(shallowCopy); // based on LLVM libc++ upper_bound / lower_bound // MIT License function upperBound(array, func) { var diff, len, i, current; len = array.length; i = 0; while (len) { diff = len >>> 1; current = i + diff; if (func(array[current])) { len = diff; } else { i = current + 1; len -= diff + 1; } } return i; } function lowerBound(array, func) { var diff, len, i, current; len = array.length; i = 0; while (len) { diff = len >>> 1; current = i + diff; if (func(array[current])) { i = current + 1; len -= diff + 1; } else { len = diff; } } return i; } ignoreJSHintError(lowerBound); objectCreate = Object.create || (function () { function F() { } return function (o) { F.prototype = o; return new F(); }; })(); objectKeys = Object.keys || function (o) { var keys = [], key; for (key in o) { keys.push(key); } return keys; }; function extend(to, from) { var keys = objectKeys(from), key, i, len; for (i = 0, len = keys.length; i < len; i += 1) { key = keys[i]; to[key] = from[key]; } return to; } Syntax = { AssignmentExpression: 'AssignmentExpression', AssignmentPattern: 'AssignmentPattern', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrowFunctionExpression: 'ArrowFunctionExpression', AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DirectiveStatement: 'DirectiveStatement', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportAllDeclaration: 'ExportAllDeclaration', ExportDefaultDeclaration: 'ExportDefaultDeclaration', ExportNamedDeclaration: 'ExportNamedDeclaration', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MetaProperty: 'MetaProperty', MethodDefinition: 'MethodDefinition', ModuleSpecifier: 'ModuleSpecifier', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', Program: 'Program', Property: 'Property', RestElement: 'RestElement', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', Super: 'Super', SwitchStatement: 'SwitchStatement', SwitchCase: 'SwitchCase', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', YieldExpression: 'YieldExpression' }; VisitorKeys = { AssignmentExpression: ['left', 'right'], AssignmentPattern: ['left', 'right'], ArrayExpression: ['elements'], ArrayPattern: ['elements'], ArrowFunctionExpression: ['params', 'body'], AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. BlockStatement: ['body'], BinaryExpression: ['left', 'right'], BreakStatement: ['label'], CallExpression: ['callee', 'arguments'], CatchClause: ['param', 'body'], ClassBody: ['body'], ClassDeclaration: ['id', 'superClass', 'body'], ClassExpression: ['id', 'superClass', 'body'], ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. ConditionalExpression: ['test', 'consequent', 'alternate'], ContinueStatement: ['label'], DebuggerStatement: [], DirectiveStatement: [], DoWhileStatement: ['body', 'test'], EmptyStatement: [], ExportAllDeclaration: ['source'], ExportDefaultDeclaration: ['declaration'], ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], ExportSpecifier: ['exported', 'local'], ExpressionStatement: ['expression'], ForStatement: ['init', 'test', 'update', 'body'], ForInStatement: ['left', 'right', 'body'], ForOfStatement: ['left', 'right', 'body'], FunctionDeclaration: ['id', 'params', 'body'], FunctionExpression: ['id', 'params', 'body'], GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. Identifier: [], IfStatement: ['test', 'consequent', 'alternate'], ImportDeclaration: ['specifiers', 'source'], ImportDefaultSpecifier: ['local'], ImportNamespaceSpecifier: ['local'], ImportSpecifier: ['imported', 'local'], Literal: [], LabeledStatement: ['label', 'body'], LogicalExpression: ['left', 'right'], MemberExpression: ['object', 'property'], MetaProperty: ['meta', 'property'], MethodDefinition: ['key', 'value'], ModuleSpecifier: [], NewExpression: ['callee', 'arguments'], ObjectExpression: ['properties'], ObjectPattern: ['properties'], Program: ['body'], Property: ['key', 'value'], RestElement: [ 'argument' ], ReturnStatement: ['argument'], SequenceExpression: ['expressions'], SpreadElement: ['argument'], Super: [], SwitchStatement: ['discriminant', 'cases'], SwitchCase: ['test', 'consequent'], TaggedTemplateExpression: ['tag', 'quasi'], TemplateElement: [], TemplateLiteral: ['quasis', 'expressions'], ThisExpression: [], ThrowStatement: ['argument'], TryStatement: ['block', 'handler', 'finalizer'], UnaryExpression: ['argument'], UpdateExpression: ['argument'], VariableDeclaration: ['declarations'], VariableDeclarator: ['id', 'init'], WhileStatement: ['test', 'body'], WithStatement: ['object', 'body'], YieldExpression: ['argument'] }; // unique id BREAK = {}; SKIP = {}; REMOVE = {}; VisitorOption = { Break: BREAK, Skip: SKIP, Remove: REMOVE }; function Reference(parent, key) { this.parent = parent; this.key = key; } Reference.prototype.replace = function replace(node) { this.parent[this.key] = node; }; Reference.prototype.remove = function remove() { if (isArray(this.parent)) { this.parent.splice(this.key, 1); return true; } else { this.replace(null); return false; } }; function Element(node, path, wrap, ref) { this.node = node; this.path = path; this.wrap = wrap; this.ref = ref; } function Controller() { } // API: // return property path array from root to current node Controller.prototype.path = function path() { var i, iz, j, jz, result, element; function addToPath(result, path) { if (isArray(path)) { for (j = 0, jz = path.length; j < jz; ++j) { result.push(path[j]); } } else { result.push(path); } } // root node if (!this.__current.path) { return null; } // first node is sentinel, second node is root element result = []; for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { element = this.__leavelist[i]; addToPath(result, element.path); } addToPath(result, this.__current.path); return result; }; // API: // return type of current node Controller.prototype.type = function () { var node = this.current(); return node.type || this.__current.wrap; }; // API: // return array of parent elements Controller.prototype.parents = function parents() { var i, iz, result; // first node is sentinel result = []; for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { result.push(this.__leavelist[i].node); } return result; }; // API: // return current node Controller.prototype.current = function current() { return this.__current.node; }; Controller.prototype.__execute = function __execute(callback, element) { var previous, result; result = undefined; previous = this.__current; this.__current = element; this.__state = null; if (callback) { result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); } this.__current = previous; return result; }; // API: // notify control skip / break Controller.prototype.notify = function notify(flag) { this.__state = flag; }; // API: // skip child nodes of current node Controller.prototype.skip = function () { this.notify(SKIP); }; // API: // break traversals Controller.prototype['break'] = function () { this.notify(BREAK); }; // API: // remove node Controller.prototype.remove = function () { this.notify(REMOVE); }; Controller.prototype.__initialize = function(root, visitor) { this.visitor = visitor; this.root = root; this.__worklist = []; this.__leavelist = []; this.__current = null; this.__state = null; this.__fallback = null; if (visitor.fallback === 'iteration') { this.__fallback = objectKeys; } else if (typeof visitor.fallback === 'function') { this.__fallback = visitor.fallback; } this.__keys = VisitorKeys; if (visitor.keys) { this.__keys = extend(objectCreate(this.__keys), visitor.keys); } }; function isNode(node) { if (node == null) { return false; } return typeof node === 'object' && typeof node.type === 'string'; } function isProperty(nodeType, key) { return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; } Controller.prototype.traverse = function traverse(root, visitor) { var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel; this.__initialize(root, visitor); sentinel = {}; // reference worklist = this.__worklist; leavelist = this.__leavelist; // initialize worklist.push(new Element(root, null, null, null)); leavelist.push(new Element(null, null, null, null)); while (worklist.length) { element = worklist.pop(); if (element === sentinel) { element = leavelist.pop(); ret = this.__execute(visitor.leave, element); if (this.__state === BREAK || ret === BREAK) { return; } continue; } if (element.node) { ret = this.__execute(visitor.enter, element); if (this.__state === BREAK || ret === BREAK) { return; } worklist.push(sentinel); leavelist.push(element); if (this.__state === SKIP || ret === SKIP) { continue; } node = element.node; nodeType = node.type || element.wrap; candidates = this.__keys[nodeType]; if (!candidates) { if (this.__fallback) { candidates = this.__fallback(node); } else { throw new Error('Unknown node type ' + nodeType + '.'); } } current = candidates.length; while ((current -= 1) >= 0) { key = candidates[current]; candidate = node[key]; if (!candidate) { continue; } if (isArray(candidate)) { current2 = candidate.length; while ((current2 -= 1) >= 0) { if (!candidate[current2]) { continue; } if (isProperty(nodeType, candidates[current])) { element = new Element(candidate[current2], [key, current2], 'Property', null); } else if (isNode(candidate[current2])) { element = new Element(candidate[current2], [key, current2], null, null); } else { continue; } worklist.push(element); } } else if (isNode(candidate)) { worklist.push(new Element(candidate, key, null, null)); } } } } }; Controller.prototype.replace = function replace(root, visitor) { var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key; function removeElem(element) { var i, key, nextElem, parent; if (element.ref.remove()) { // When the reference is an element of an array. key = element.ref.key; parent = element.ref.parent; // If removed from array, then decrease following items' keys. i = worklist.length; while (i--) { nextElem = worklist[i]; if (nextElem.ref && nextElem.ref.parent === parent) { if (nextElem.ref.key < key) { break; } --nextElem.ref.key; } } } } this.__initialize(root, visitor); sentinel = {}; // reference worklist = this.__worklist; leavelist = this.__leavelist; // initialize outer = { root: root }; element = new Element(root, null, null, new Reference(outer, 'root')); worklist.push(element); leavelist.push(element); while (worklist.length) { element = worklist.pop(); if (element === sentinel) { element = leavelist.pop(); target = this.__execute(visitor.leave, element); // node may be replaced with null, // so distinguish between undefined and null in this place if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { // replace element.ref.replace(target); } if (this.__state === REMOVE || target === REMOVE) { removeElem(element); } if (this.__state === BREAK || target === BREAK) { return outer.root; } continue; } target = this.__execute(visitor.enter, element); // node may be replaced with null, // so distinguish between undefined and null in this place if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { // replace element.ref.replace(target); element.node = target; } if (this.__state === REMOVE || target === REMOVE) { removeElem(element); element.node = null; } if (this.__state === BREAK || target === BREAK) { return outer.root; } // node may be null node = element.node; if (!node) { continue; } worklist.push(sentinel); leavelist.push(element); if (this.__state === SKIP || target === SKIP) { continue; } nodeType = node.type || element.wrap; candidates = this.__keys[nodeType]; if (!candidates) { if (this.__fallback) { candidates = this.__fallback(node); } else { throw new Error('Unknown node type ' + nodeType + '.'); } } current = candidates.length; while ((current -= 1) >= 0) { key = candidates[current]; candidate = node[key]; if (!candidate) { continue; } if (isArray(candidate)) { current2 = candidate.length; while ((current2 -= 1) >= 0) { if (!candidate[current2]) { continue; } if (isProperty(nodeType, candidates[current])) { element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); } else if (isNode(candidate[current2])) { element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); } else { continue; } worklist.push(element); } } else if (isNode(candidate)) { worklist.push(new Element(candidate, key, null, new Reference(node, key))); } } } return outer.root; }; function traverse(root, visitor) { var controller = new Controller(); return controller.traverse(root, visitor); } function replace(root, visitor) { var controller = new Controller(); return controller.replace(root, visitor); } function extendCommentRange(comment, tokens) { var target; target = upperBound(tokens, function search(token) { return token.range[0] > comment.range[0]; }); comment.extendedRange = [comment.range[0], comment.range[1]]; if (target !== tokens.length) { comment.extendedRange[1] = tokens[target].range[0]; } target -= 1; if (target >= 0) { comment.extendedRange[0] = tokens[target].range[1]; } return comment; } function attachComments(tree, providedComments, tokens) { // At first, we should calculate extended comment ranges. var comments = [], comment, len, i, cursor; if (!tree.range) { throw new Error('attachComments needs range information'); } // tokens array is empty, we attach comments to tree as 'leadingComments' if (!tokens.length) { if (providedComments.length) { for (i = 0, len = providedComments.length; i < len; i += 1) { comment = deepCopy(providedComments[i]); comment.extendedRange = [0, tree.range[0]]; comments.push(comment); } tree.leadingComments = comments; } return tree; } for (i = 0, len = providedComments.length; i < len; i += 1) { comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); } // This is based on John Freeman's implementation. cursor = 0; traverse(tree, { enter: function (node) { var comment; while (cursor < comments.length) { comment = comments[cursor]; if (comment.extendedRange[1] > node.range[0]) { break; } if (comment.extendedRange[1] === node.range[0]) { if (!node.leadingComments) { node.leadingComments = []; } node.leadingComments.push(comment); comments.splice(cursor, 1); } else { cursor += 1; } } // already out of owned node if (cursor === comments.length) { return VisitorOption.Break; } if (comments[cursor].extendedRange[0] > node.range[1]) { return VisitorOption.Skip; } } }); cursor = 0; traverse(tree, { leave: function (node) { var comment; while (cursor < comments.length) { comment = comments[cursor]; if (node.range[1] < comment.extendedRange[0]) { break; } if (node.range[1] === comment.extendedRange[0]) { if (!node.trailingComments) { node.trailingComments = []; } node.trailingComments.push(comment); comments.splice(cursor, 1); } else { cursor += 1; } } // already out of owned node if (cursor === comments.length) { return VisitorOption.Break; } if (comments[cursor].extendedRange[0] > node.range[1]) { return VisitorOption.Skip; } } }); return tree; } exports.version = __webpack_require__(1179).version; exports.Syntax = Syntax; exports.traverse = traverse; exports.replace = replace; exports.attachComments = attachComments; exports.VisitorKeys = VisitorKeys; exports.VisitorOption = VisitorOption; exports.Controller = Controller; exports.cloneEnvironment = function () { return clone({}); }; return exports; }(exports)); /* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), /* 146 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = copyComments; /** * Appends comments of one node to comments of another. * * - Modifies `to` node with added comments. * - Does nothing when there are no comments to copy * (ensuring we don't modify the `to` node when not needed). * * @param {Object} from Node to copy comments from * @param {Object} to Node to copy comments to */ function copyComments(_ref) { var from = _ref.from, to = _ref.to; if (from.comments && from.comments.length > 0) { to.comments = (to.comments || []).concat(from.comments || []); } } module.exports = exports["default"]; /***/ }), /* 147 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isEqualAst; var _fp = __webpack_require__(22); var metaDataFields = { comments: true, loc: true, start: true, end: true }; /** * True when two AST nodes are structurally equal. * When comparing objects it ignores the meta-data fields for * comments and source-code position. * @param {Object} a * @param {Object} b * @return {Boolean} */ function isEqualAst(a, b) { return (0, _fp.isEqualWith)(function (aValue, bValue, key) { return metaDataFields[key]; }, a, b); } module.exports = exports['default']; /***/ }), /* 148 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__(484)() ? Object.setPrototypeOf : __webpack_require__(485); /***/ }), /* 149 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _node = __webpack_require__(119); var _node2 = _interopRequireDefault(_node); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Namespace = function (_Node) { _inherits(Namespace, _Node); function Namespace() { _classCallCheck(this, Namespace); return _possibleConstructorReturn(this, _Node.apply(this, arguments)); } Namespace.prototype.qualifiedName = function qualifiedName(value) { if (this.namespace) { return this.namespaceString + '|' + value; } else { return value; } }; Namespace.prototype.toString = function toString() { return [this.spaces.before, this.qualifiedName(this.value), this.spaces.after].join(''); }; _createClass(Namespace, [{ key: 'namespace', get: function get() { return this._namespace; }, set: function set(namespace) { this._namespace = namespace; if (this.raws) { delete this.raws.namespace; } } }, { key: 'ns', get: function get() { return this._namespace; }, set: function set(namespace) { this._namespace = namespace; if (this.raws) { delete this.raws.namespace; } } }, { key: 'namespaceString', get: function get() { if (this.namespace) { var ns = this.raws && this.raws.namespace || this.namespace; if (ns === true) { return ''; } else { return ns; } } else { return ''; } } }]); return Namespace; }(_node2.default); exports.default = Namespace; ; module.exports = exports['default']; /***/ }), /* 150 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Browsers = __webpack_require__(120); var utils = __webpack_require__(47); var vendor = __webpack_require__(40).vendor; /** * Recursivly clone objects */ function _clone(obj, parent) { var cloned = new obj.constructor(); for (var _iterator = Object.keys(obj || {}), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var i = _ref; var value = obj[i]; if (i === 'parent' && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') { if (parent) { cloned[i] = parent; } } else if (i === 'source' || i === null) { cloned[i] = value; } else if (value instanceof Array) { cloned[i] = value.map(function (x) { return _clone(x, cloned); }); } else if (i !== '_autoprefixerPrefix' && i !== '_autoprefixerValues') { if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) { value = _clone(value, cloned); } cloned[i] = value; } } return cloned; } var Prefixer = function () { /** * Add hack to selected names */ Prefixer.hack = function hack(klass) { var _this = this; if (!this.hacks) { this.hacks = {}; } return klass.names.map(function (name) { _this.hacks[name] = klass; return _this.hacks[name]; }); }; /** * Load hacks for some names */ Prefixer.load = function load(name, prefixes, all) { var Klass = this.hacks && this.hacks[name]; if (Klass) { return new Klass(name, prefixes, all); } else { return new this(name, prefixes, all); } }; /** * Clone node and clean autprefixer custom caches */ Prefixer.clone = function clone(node, overrides) { var cloned = _clone(node); for (var name in overrides) { cloned[name] = overrides[name]; } return cloned; }; function Prefixer(name, prefixes, all) { _classCallCheck(this, Prefixer); this.name = name; this.prefixes = prefixes; this.all = all; } /** * Find prefix in node parents */ Prefixer.prototype.parentPrefix = function parentPrefix(node) { var prefix = void 0; if (typeof node._autoprefixerPrefix !== 'undefined') { prefix = node._autoprefixerPrefix; } else if (node.type === 'decl' && node.prop[0] === '-') { prefix = vendor.prefix(node.prop); } else if (node.type === 'root') { prefix = false; } else if (node.type === 'rule' && node.selector.indexOf(':-') !== -1 && /:(-\w+-)/.test(node.selector)) { prefix = node.selector.match(/:(-\w+-)/)[1]; } else if (node.type === 'atrule' && node.name[0] === '-') { prefix = vendor.prefix(node.name); } else { prefix = this.parentPrefix(node.parent); } if (Browsers.prefixes().indexOf(prefix) === -1) { prefix = false; } node._autoprefixerPrefix = prefix; return node._autoprefixerPrefix; }; /** * Clone node with prefixes */ Prefixer.prototype.process = function process(node, result) { if (!this.check(node)) { return undefined; } var parent = this.parentPrefix(node); var prefixes = this.prefixes.filter(function (prefix) { return !parent || parent === utils.removeNote(prefix); }); var added = []; for (var _iterator2 = prefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var prefix = _ref2; if (this.add(node, prefix, added.concat([prefix]), result)) { added.push(prefix); } } return added; }; /** * Shortcut for Prefixer.clone */ Prefixer.prototype.clone = function clone(node, overrides) { return Prefixer.clone(node, overrides); }; return Prefixer; }(); module.exports = Prefixer; /***/ }), /* 151 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var utils = __webpack_require__(47); var OldValue = function () { function OldValue(unprefixed, prefixed, string, regexp) { _classCallCheck(this, OldValue); this.unprefixed = unprefixed; this.prefixed = prefixed; this.string = string || prefixed; this.regexp = regexp || utils.regexp(prefixed); } /** * Check, that value contain old value */ OldValue.prototype.check = function check(value) { if (value.indexOf(this.string) !== -1) { return !!value.match(this.regexp); } return false; }; return OldValue; }(); module.exports = OldValue; /***/ }), /* 152 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var parser = __webpack_require__(294); function convert(value) { if (value && value.length === 2 && value[0] === 'span' && parseInt(value[1], 10) > 0) { return [false, parseInt(value[1], 10)]; } if (value && value.length === 1 && parseInt(value[0], 10) > 0) { return [parseInt(value[0], 10), false]; } return [false, false]; } function translate(values, startIndex, endIndex) { var startValue = values[startIndex]; var endValue = values[endIndex]; if (!startValue) { return [false, false]; } var _convert = convert(startValue), start = _convert[0], spanStart = _convert[1]; var _convert2 = convert(endValue), end = _convert2[0], spanEnd = _convert2[1]; if (start && !endValue) { return [start, false]; } if (spanStart && end) { return [end - spanStart, spanStart]; } if (start && spanEnd) { return [start, spanEnd]; } if (start && end) { return [start, end - start]; } return [false, false]; } function parse(decl) { var node = parser(decl.value); var values = []; var current = 0; values[current] = []; for (var _iterator = node.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var i = _ref; if (i.type === 'div') { current += 1; values[current] = []; } else if (i.type === 'word') { values[current].push(i.value); } } return values; } function insertDecl(decl, prop, value) { if (value && !decl.parent.some(function (i) { return i.prop === '-ms-' + prop; })) { decl.cloneBefore({ prop: '-ms-' + prop, value: value.toString() }); } } // Transform repeat function transformRepeat(_ref2) { var nodes = _ref2.nodes; var repeat = nodes.reduce(function (result, node) { if (node.type === 'div' && node.value === ',') { result.key = 'function'; } else { result[result.key].push(parser.stringify(node)); } return result; }, { key: 'count', function: [], count: [] }); return '(' + repeat.function.join('') + ')[' + repeat.count.join('') + ']'; } function changeRepeat(value) { var result = parser(value).nodes.map(function (i) { if (i.type === 'function' && i.value === 'repeat') { return { type: 'word', value: transformRepeat(i) }; } return i; }); return parser.stringify(result); } // Parse grid-template-areas var DOTS = /^\.+$/; function track(start, end) { return { start: start, end: end, span: end - start }; } function getColumns(line) { return line.trim().split(/\s+/g); } function parseGridAreas(rows) { return rows.reduce(function (areas, line, rowIndex) { if (line.trim() === '') return areas; getColumns(line).forEach(function (area, columnIndex) { if (DOTS.test(area)) return; if (typeof areas[area] === 'undefined') { areas[area] = { column: track(columnIndex + 1, columnIndex + 2), row: track(rowIndex + 1, rowIndex + 2) }; } else { var _areas$area = areas[area], column = _areas$area.column, row = _areas$area.row; column.start = Math.min(column.start, columnIndex + 1); column.end = Math.max(column.end, columnIndex + 2); column.span = column.end - column.start; row.start = Math.min(row.start, rowIndex + 1); row.end = Math.max(row.end, rowIndex + 2); row.span = row.end - row.start; } }); return areas; }, {}); } // Parse grid-template function testTrack(node) { return node.type === 'word' && /^\[.+\]$/.test(node.value); } function parseTemplate(decl) { var gridTemplate = parser(decl.value).nodes.reduce(function (result, node) { var type = node.type, value = node.value; if (testTrack(node) || type === 'space') return result; // area if (type === 'string') { result.areas.push(value); } // values and function if (type === 'word' || type === 'function') { if (type === 'function' && value === 'repeat') { result[result.key].push(transformRepeat(node)); } else { result[result.key].push(parser.stringify(node)); } } // devider(/) if (type === 'div' && value === '/') { result.key = 'columns'; } return result; }, { key: 'rows', columns: [], rows: [], areas: [] }); return { areas: parseGridAreas(gridTemplate.areas), columns: gridTemplate.columns.join(' '), rows: gridTemplate.rows.join(' ') }; } // Insert parsed grid areas function getRoot(parent) { if (parent.type === 'atrule' || !parent.parent) { return parent; } return getRoot(parent.parent); } function insertAreas(areas, decl, result) { var missed = Object.keys(areas); getRoot(decl.parent).walkDecls('grid-area', function (gridArea) { var value = gridArea.value; var area = areas[value]; missed = missed.filter(function (e) { return e !== value; }); if (area) { gridArea.parent.walkDecls(/-ms-grid-(row|column)/, function (d) { d.remove(); }); gridArea.cloneBefore({ prop: '-ms-grid-row', value: String(area.row.start) }); if (area.row.span > 1) { gridArea.cloneBefore({ prop: '-ms-grid-row-span', value: String(area.row.span) }); } gridArea.cloneBefore({ prop: '-ms-grid-column', value: String(area.column.start) }); if (area.column.span > 1) { gridArea.cloneBefore({ prop: '-ms-grid-column-span', value: String(area.column.span) }); } } return undefined; }); if (missed.length > 0) { decl.warn(result, 'Can not find grid areas: ' + missed.join(', ')); } } module.exports = { parse: parse, translate: translate, changeRepeat: changeRepeat, parseTemplate: parseTemplate, parseGridAreas: parseGridAreas, insertAreas: insertAreas, insertDecl: insertDecl }; /***/ }), /* 153 */ /***/ (function(module, exports) { module.exports = {}; /***/ }), /* 154 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(593); var enumBugKeys = __webpack_require__(308); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /* 155 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(1823); var global = __webpack_require__(59); var hide = __webpack_require__(85); var Iterators = __webpack_require__(153); var TO_STRING_TAG = __webpack_require__(51)('toStringTag'); var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + 'TextTrackList,TouchList').split(','); for (var i = 0; i < DOMIterables.length; i++) { var NAME = DOMIterables[i]; var Collection = global[NAME]; var proto = Collection && Collection.prototype; if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }), /* 156 */ /***/ (function(module, exports, __webpack_require__) { var META = __webpack_require__(217)('meta'); var isObject = __webpack_require__(50); var has = __webpack_require__(87); var setDesc = __webpack_require__(71).f; var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var FREEZE = !__webpack_require__(86)(function () { return isExtensible(Object.preventExtensions({})); }); var setMeta = function (it) { setDesc(it, META, { value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs } }); }; var fastKey = function (it, create) { // return primitive with prefix if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function (it, create) { if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function (it) { if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }), /* 157 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /***/ }), /* 158 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(1852), __esModule: true }; /***/ }), /* 159 */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(121); var call = __webpack_require__(1862); var isArrayIter = __webpack_require__(1863); var anObject = __webpack_require__(72); var toLength = __webpack_require__(305); var getIterFn = __webpack_require__(603); var BREAK = {}; var RETURN = {}; var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); var f = ctx(fn, that, entries ? 2 : 1); var index = 0; var length, step, iterator, result; if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if (result === BREAK || result === RETURN) return result; } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { result = call(iterator, f, step.value, entries); if (result === BREAK || result === RETURN) return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; /***/ }), /* 160 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(50); module.exports = function (it, TYPE) { if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); return it; }; /***/ }), /* 161 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EvalPropertyName = EvalPropertyName; exports.default = function (ast, strictCode, env, realm) { // 1. Let obj be ObjectCreate(%ObjectPrototype%). let obj = _singletons.Create.ObjectCreate(realm, realm.intrinsics.ObjectPrototype); // 2. Let status be the result of performing PropertyDefinitionEvaluation of PropertyDefinitionList with arguments obj and true. for (let prop of ast.properties) { if (prop.type === "ObjectProperty") { // 12.2.6.9 case 3 // 1. Let propKey be the result of evaluating PropertyName. let propKey = EvalPropertyNamePartial(prop, env, realm, strictCode); // 2. ReturnIfAbrupt(propKey). // 3. Let exprValueRef be the result of evaluating AssignmentExpression. let exprValueRef = env.evaluate(prop.value, strictCode); // 4. Let propValue be ? GetValue(exprValueRef). let propValue = _singletons.Environment.GetValue(realm, exprValueRef); // 5. If IsAnonymousFunctionDefinition(AssignmentExpression) is true, then if ((0, _index2.IsAnonymousFunctionDefinition)(realm, prop.value)) { (0, _invariant2.default)(propValue instanceof _index.ObjectValue); // a. Let hasNameProperty be ? HasOwnProperty(propValue, "name"). let hasNameProperty = (0, _index2.HasOwnProperty)(realm, propValue, "name"); // b. If hasNameProperty is false, perform SetFunctionName(propValue, propKey). (0, _invariant2.default)(!hasNameProperty); // No expression that passes through IsAnonymousFunctionDefinition can have it here _singletons.Functions.SetFunctionName(realm, propValue, propKey); } // 6. Assert: enumerable is true. // 7. Return CreateDataPropertyOrThrow(object, propKey, propValue). if (propKey instanceof _index.AbstractValue) { if (propKey.mightNotBeString()) { let error = new _errors.CompilerDiagnostic("property key value is unknown", prop.loc, "PP0011", "FatalError"); if (realm.handleError(error) === "Fail") throw new _errors.FatalError(); continue; // recover by ignoring the property, which is only ever safe to do if the property is dead, // which is assuming a bit much, hence the designation as a FatalError. } obj.$SetPartial(propKey, propValue, obj); } else { _singletons.Create.CreateDataPropertyOrThrow(realm, obj, propKey, propValue); } } else { (0, _invariant2.default)(prop.type === "ObjectMethod"); _singletons.Properties.PropertyDefinitionEvaluation(realm, prop, obj, env, strictCode, true); } } // 3. ReturnIfAbrupt(status). // 4. Return obj. return obj; }; var _errors = __webpack_require__(6); var _index = __webpack_require__(0); var _index2 = __webpack_require__(5); var _singletons = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Returns the result of evaluating PropertyName. /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function EvalPropertyName(prop, env, realm, strictCode) { let result = EvalPropertyNamePartial(prop, env, realm, strictCode); if (result instanceof _index.AbstractValue) { let error = new _errors.CompilerDiagnostic("unknown computed property name", prop.loc, "PP0014", "FatalError"); realm.handleError(error); throw new _errors.FatalError(); } return result; } function EvalPropertyNamePartial(prop, env, realm, strictCode) { if (prop.computed) { let propertyKeyName = _singletons.Environment.GetValue(realm, env.evaluate(prop.key, strictCode)); if (propertyKeyName instanceof _index.AbstractValue) return propertyKeyName; (0, _invariant2.default)(propertyKeyName instanceof _index.ConcreteValue); return _singletons.To.ToPropertyKey(realm, propertyKeyName); } else { if (prop.key.type === "Identifier") { return new _index.StringValue(realm, prop.key.name); } else { let propertyKeyName = _singletons.Environment.GetValue(realm, env.evaluate(prop.key, strictCode)); (0, _invariant2.default)(propertyKeyName instanceof _index.ConcreteValue); // syntax only allows literals if !prop.computed return _singletons.To.ToString(realm, propertyKeyName); } } } // ECMA262 12.2.6.8 //# sourceMappingURL=ObjectExpression.js.map /***/ }), /* 162 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /***/ }), /* 163 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseTypeNameOrTemplate = parseTypeNameOrTemplate; exports.createAbstractArgument = createAbstractArgument; exports.createAbstract = createAbstract; var _index = __webpack_require__(0); var _builder = __webpack_require__(53); var _builder2 = _interopRequireDefault(_builder); var _index2 = __webpack_require__(35); var _Error = __webpack_require__(62); var _singletons = __webpack_require__(2); var _AbstractObjectValue = __webpack_require__(625); var _AbstractObjectValue2 = _interopRequireDefault(_AbstractObjectValue); var _errors = __webpack_require__(6); var _singletons2 = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ const throwTemplateSrc = "(function(){throw new global.Error('abstract value defined at ' + A);})()"; const throwTemplate = (0, _builder2.default)(throwTemplateSrc); function parseTypeNameOrTemplate(realm, typeNameOrTemplate) { if (typeNameOrTemplate === undefined || typeNameOrTemplate instanceof _index.UndefinedValue) { return { type: _index.Value, template: undefined }; } else if (typeof typeNameOrTemplate === "string") { let type = _singletons2.Utils.getTypeFromName(typeNameOrTemplate); if (type === undefined) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "unknown typeNameOrTemplate"); } return { type, template: undefined }; } else if (typeNameOrTemplate instanceof _index.StringValue) { let typeNameString = _singletons.To.ToStringPartial(realm, typeNameOrTemplate); let hasFunctionResultType = typeNameString.startsWith(":"); if (hasFunctionResultType) typeNameString = typeNameString.substring(1); let type = _singletons2.Utils.getTypeFromName(typeNameString); if (type === undefined) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "unknown typeNameOrTemplate"); } return hasFunctionResultType ? { type: _index.FunctionValue, template: undefined, functionResultType: type } : { type, template: undefined }; } else if (typeNameOrTemplate instanceof _index.FunctionValue) { return { type: _index.FunctionValue, template: typeNameOrTemplate }; } else if (typeNameOrTemplate instanceof _index.ObjectValue) { return { type: _index.ObjectValue, template: typeNameOrTemplate }; } else { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "typeNameOrTemplate has unsupported type"); } } function createAbstractArgument(realm, name, location) { if (!realm.useAbstractInterpretation) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "realm is not partial"); } let locString; if (location) locString = (0, _Error.describeLocation)(realm, undefined, undefined, location); let locVal = new _index.StringValue(realm, locString || "(unknown location)"); let kind = "__abstract_" + realm.objectCount++; // need not be an object, but must be unique let result = _index.AbstractValue.createFromTemplate(realm, (0, _builder2.default)(name), _index.Value, [locVal], kind); result.intrinsicName = name; return result; } function createAbstract(realm, typeNameOrTemplate, name, ...additionalValues) { if (!realm.useAbstractInterpretation) { throw realm.createErrorThrowCompletion(realm.intrinsics.TypeError, "realm is not partial"); } let { type, template, functionResultType } = parseTypeNameOrTemplate(realm, typeNameOrTemplate); let result; let locString, loc = null; for (let executionContext of realm.contextStack.slice().reverse()) { let caller = executionContext.caller; loc = executionContext.loc; locString = (0, _Error.describeLocation)(realm, caller ? caller.function : undefined, caller ? caller.lexicalEnvironment : undefined, loc); if (locString !== undefined) break; } if (!name) { let locVal = new _index.StringValue(realm, locString || "(unknown location)"); let kind = "__abstract_" + realm.objectCount++; // need not be an object, but must be unique result = _index.AbstractValue.createFromTemplate(realm, throwTemplate, type, [locVal], kind); } else { let kind = "__abstract_" + name; if (!realm.isNameStringUnique(name)) { let error = new _errors.CompilerDiagnostic("An abstract value with the same name exists", loc, "PP0019", "FatalError"); realm.handleError(error); throw new _errors.FatalError(); } else { realm.saveNameString(name); } result = _index.AbstractValue.createFromTemplate(realm, (0, _builder2.default)(name), type, [], kind); result.intrinsicName = name; } if (template) result.values = new _index2.ValuesDomain(new Set([template])); if (template && !(template instanceof _index.FunctionValue)) { // why exclude functions? template.makePartial(); if (name) realm.rebuildNestedProperties(result, name); } if (functionResultType) { (0, _invariant2.default)(result instanceof _AbstractObjectValue2.default); result.functionResultType = functionResultType; } if (additionalValues.length > 0) result = _index.AbstractValue.createAbstractConcreteUnion(realm, result, ...additionalValues); return result; } //# sourceMappingURL=utils.js.map /***/ }), /* 164 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ResidualHeapVisitor = undefined; var _environment = __webpack_require__(12); var _errors = __webpack_require__(6); var _realm = __webpack_require__(11); var _index = __webpack_require__(5); var _index2 = __webpack_require__(0); var _Error = __webpack_require__(62); var _babelTypes = __webpack_require__(4); var t = _interopRequireWildcard(_babelTypes); var _generator = __webpack_require__(34); var _babelTraverse = __webpack_require__(60); var _babelTraverse2 = _interopRequireDefault(_babelTraverse); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _visitors = __webpack_require__(627); var _logger = __webpack_require__(61); var _modules = __webpack_require__(89); var _ResidualHeapInspector = __webpack_require__(165); var _Referentializer = __webpack_require__(326); var _utils = __webpack_require__(166); var _singletons = __webpack_require__(2); var _utils2 = __webpack_require__(27); var _hoisting = __webpack_require__(327); var _ReactElementSet = __webpack_require__(1998); var _ReactElementSet2 = _interopRequireDefault(_ReactElementSet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /* This class visits all values that are reachable in the residual heap. In particular, this "filters out" values that are: - captured by a DeclarativeEnvironmentRecord, but not actually used by any closure. - Unmodified prototype objects TODO #680: Figure out minimal set of values that need to be kept alive for WeakSet and WeakMap instances. */ /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ class ResidualHeapVisitor { constructor(realm, logger, modules, additionalFunctionValuesAndEffects, // Referentializer is null if we're just checking what values exist referentializer) { (0, _invariant2.default)(realm.useAbstractInterpretation); this.realm = realm; this.logger = logger; this.modules = modules; this.referentializer = referentializer === "NO_REFERENTIALIZE" ? undefined : referentializer; this.declarativeEnvironmentRecordsBindings = new Map(); this.globalBindings = new Map(); this.functionInfos = new Map(); this.classMethodInstances = new Map(); this.functionInstances = new Map(); this.values = new Map(); let generator = this.realm.generator; (0, _invariant2.default)(generator); this.scope = this.commonScope = generator; this.inspector = new _ResidualHeapInspector.ResidualHeapInspector(realm, logger); this.referencedDeclaredValues = new Map(); this.delayedVisitGeneratorEntries = []; this.someReactElement = undefined; this.additionalFunctionValuesAndEffects = additionalFunctionValuesAndEffects; this.equivalenceSet = new _index.HashSet(); this.reactElementEquivalenceSet = new _ReactElementSet2.default(realm, this.equivalenceSet); this.additionalFunctionValueInfos = new Map(); this.containingAdditionalFunction = undefined; this.additionalRoots = new Map(); this.inClass = false; this.functionToCapturedScopes = new Map(); this.generatorParents = new Map(); } // Caches that ensure one ResidualFunctionBinding exists per (record, name) pair // Either the realm's generator or the FunctionValue of an additional function to serialize // We only want to add to additionalRoots when we're in an additional function // Tracks objects + functions that were visited from inside additional functions that need to be serialized in a // parent scope of the additional function (e.g. functions/objects only used from additional functions that were // declared outside the additional function need to be serialized in the additional function's parent scope for // identity to work). _registerAdditionalRoot(value) { let additionalFunction = this.containingAdditionalFunction; if (additionalFunction !== undefined && !this.inClass) { let s = this.additionalRoots.get(value); if (s === undefined) this.additionalRoots.set(value, s = new Set()); s.add(additionalFunction); } } _withScope(scope, f) { let oldScope = this.scope; this.scope = scope; try { f(); } finally { this.scope = oldScope; } } visitObjectProperty(binding) { let desc = binding.descriptor; if (desc === undefined) return; //deleted let obj = binding.object; if (obj instanceof _index2.AbstractObjectValue || !this.inspector.canIgnoreProperty(obj, binding.key)) { this.visitDescriptor(desc); } } visitObjectProperties(obj, kind) { let { skipPrototype, constructor } = (0, _utils.getObjectPrototypeMetadata)(this.realm, obj); // visit properties if (!(0, _utils2.isReactElement)(obj)) { for (let [symbol, propertyBinding] of obj.symbols) { (0, _invariant2.default)(propertyBinding); let desc = propertyBinding.descriptor; if (desc === undefined) continue; //deleted this.visitDescriptor(desc); this.visitValue(symbol); } } // visit properties for (let [propertyBindingKey, propertyBindingValue] of obj.properties) { // we don't want to visit these as we handle the serialization ourselves // via a different logic route for classes let descriptor = propertyBindingValue.descriptor; if (obj.$FunctionKind === "classConstructor" && (_utils.ClassPropertiesToIgnore.has(propertyBindingKey) || propertyBindingKey === "length" && (0, _utils.canIgnoreClassLengthProperty)(obj, descriptor, this.logger))) { continue; } if (propertyBindingKey.pathNode !== undefined) continue; // property is written to inside a loop (0, _invariant2.default)(propertyBindingValue); this.visitObjectProperty(propertyBindingValue); } // inject properties with computed names if (obj.unknownProperty !== undefined) { let desc = obj.unknownProperty.descriptor; if (desc !== undefined) { let val = desc.value; (0, _invariant2.default)(val instanceof _index2.AbstractValue); this.visitObjectPropertiesWithComputedNames(val); } } // prototype if (!(0, _utils2.isReactElement)(obj) && !skipPrototype) { // we don't want to the ReactElement prototype visited // as this is contained within the JSXElement, otherwise // they we be need to be emitted during serialization this.visitObjectPrototype(obj); } if (obj instanceof _index2.FunctionValue) { this.visitConstructorPrototype(constructor ? constructor : obj); } else if (obj instanceof _index2.ObjectValue && skipPrototype && constructor) { this.visitValue(constructor); } } visitObjectPrototype(obj) { let proto = obj.$Prototype; let kind = obj.getKind(); if (proto === this.realm.intrinsics[kind + "Prototype"]) return; if (!obj.$IsClassPrototype || proto !== this.realm.intrinsics.null) { this.visitValue(proto); } } visitConstructorPrototype(func) { // If the original prototype object was mutated, // request its serialization here as this might be observable by // residual code. (0, _invariant2.default)(func instanceof _index2.FunctionValue); let prototype = _ResidualHeapInspector.ResidualHeapInspector.getPropertyValue(func, "prototype"); if (prototype instanceof _index2.ObjectValue && prototype.originalConstructor === func && !this.inspector.isDefaultPrototype(prototype)) { this.visitValue(prototype); } } visitObjectPropertiesWithComputedNames(absVal) { if (absVal.kind === "widened property") return; (0, _invariant2.default)(absVal.args.length === 3); let cond = absVal.args[0]; (0, _invariant2.default)(cond instanceof _index2.AbstractValue); if (cond.kind === "template for property name condition") { let P = cond.args[0]; (0, _invariant2.default)(P instanceof _index2.AbstractValue); let V = absVal.args[1]; let earlier_props = absVal.args[2]; if (earlier_props instanceof _index2.AbstractValue) this.visitObjectPropertiesWithComputedNames(earlier_props); this.visitValue(P); this.visitValue(V); } else { // conditional assignment absVal.args[0] = this.visitEquivalentValue(cond); let consequent = absVal.args[1]; (0, _invariant2.default)(consequent instanceof _index2.AbstractValue); let alternate = absVal.args[2]; (0, _invariant2.default)(alternate instanceof _index2.AbstractValue); this.visitObjectPropertiesWithComputedNames(consequent); this.visitObjectPropertiesWithComputedNames(alternate); } } visitDescriptor(desc) { (0, _invariant2.default)(desc.value === undefined || desc.value instanceof _index2.Value); if (desc.joinCondition !== undefined) { desc.joinCondition = this.visitEquivalentValue(desc.joinCondition); if (desc.descriptor1 !== undefined) this.visitDescriptor(desc.descriptor1); if (desc.descriptor2 !== undefined) this.visitDescriptor(desc.descriptor2); return; } if (desc.value !== undefined) desc.value = this.visitEquivalentValue(desc.value); if (desc.get !== undefined) this.visitValue(desc.get); if (desc.set !== undefined) this.visitValue(desc.set); } visitValueArray(val) { this.visitObjectProperties(val); const realm = this.realm; let lenProperty; if (val.isHavocedObject()) { lenProperty = this.realm.evaluateWithoutLeakLogic(() => (0, _index.Get)(realm, val, "length")); } else { lenProperty = (0, _index.Get)(realm, val, "length"); } if (lenProperty instanceof _index2.AbstractValue || _singletons.To.ToLength(realm, lenProperty) !== (0, _utils.getSuggestedArrayLiteralLength)(realm, val)) { this.visitValue(lenProperty); } } visitValueMap(val) { let kind = val.getKind(); let entries; if (kind === "Map") { entries = val.$MapData; } else { (0, _invariant2.default)(kind === "WeakMap"); entries = val.$WeakMapData; } (0, _invariant2.default)(entries !== undefined); let len = entries.length; for (let i = 0; i < len; i++) { let entry = entries[i]; let key = entry.$Key; let value = entry.$Value; if (key === undefined || value === undefined) continue; this.visitValue(key); this.visitValue(value); } } visitValueSet(val) { let kind = val.getKind(); let entries; if (kind === "Set") { entries = val.$SetData; } else { (0, _invariant2.default)(kind === "WeakSet"); entries = val.$WeakSetData; } (0, _invariant2.default)(entries !== undefined); let len = entries.length; for (let i = 0; i < len; i++) { let entry = entries[i]; if (entry === undefined) continue; this.visitValue(entry); } } visitValueFunction(val, parentScope) { let isClass = false; this._registerAdditionalRoot(val); if (val.$FunctionKind === "classConstructor") { (0, _invariant2.default)(val instanceof _index2.ECMAScriptSourceFunctionValue); let homeObject = val.$HomeObject; if (homeObject instanceof _index2.ObjectValue && homeObject.$IsClassPrototype) { isClass = true; this.inClass = true; } } this.visitObjectProperties(val); if (isClass && this.inClass) { this.inClass = false; } if (val instanceof _index2.BoundFunctionValue) { this.visitValue(val.$BoundTargetFunction); this.visitValue(val.$BoundThis); for (let boundArg of val.$BoundArguments) this.visitValue(boundArg); return; } (0, _invariant2.default)(!(val instanceof _index2.NativeFunctionValue), "all native function values should be intrinsics"); (0, _invariant2.default)(val instanceof _index2.ECMAScriptSourceFunctionValue); (0, _invariant2.default)(val.constructor === _index2.ECMAScriptSourceFunctionValue); let formalParameters = val.$FormalParameters; let code = val.$ECMAScriptCode; let functionInfo = this.functionInfos.get(code); let residualFunctionBindings = new Map(); this.functionInstances.set(val, { residualFunctionBindings, initializationStatements: [], functionValue: val, scopeInstances: new Map() }); if (!functionInfo) { functionInfo = { unbound: new Set(), modified: new Set(), usesArguments: false, usesThis: false }; let state = { tryQuery: this.logger.tryQuery.bind(this.logger), val, functionInfo, realm: this.realm }; (0, _babelTraverse2.default)(t.file(t.program([t.expressionStatement(t.functionExpression(null, formalParameters, code))])), _visitors.ClosureRefVisitor, null, state); this.functionInfos.set(code, functionInfo); if (val.isResidual && functionInfo.unbound.size) { if (!val.isUnsafeResidual) { this.logger.logError(val, `residual function ${(0, _Error.describeLocation)(this.realm, val, undefined, code.loc) || "(unknown)"} refers to the following identifiers defined outside of the local scope: ${Object.keys(functionInfo.unbound).join(", ")}`); } } } let additionalFunctionEffects = this.additionalFunctionValuesAndEffects.get(val); if (additionalFunctionEffects) { this._visitAdditionalFunction(val, additionalFunctionEffects, parentScope); } else { this._withScope(val, () => { (0, _invariant2.default)(functionInfo); for (let innerName of functionInfo.unbound) { let residualBinding = this.visitBinding(val, innerName); (0, _invariant2.default)(residualBinding !== undefined); residualFunctionBindings.set(innerName, residualBinding); if (functionInfo.modified.has(innerName)) { residualBinding.modified = true; } } }); } if (isClass && val.$HomeObject instanceof _index2.ObjectValue) { this._visitClass(val, val.$HomeObject); } this.functionInstances.set(val, { residualFunctionBindings, initializationStatements: [], functionValue: val, scopeInstances: new Map() }); } // Addresses the case: // let x = []; // let y = []; // function a() { x.push("hi"); } // function b() { y.push("bye"); } // function c() { return x.length + y.length; } // Here we need to make sure that a and b both initialize x and y because x and y will be in the same // captured scope because c captures both x and y. _recordBindingVisitedAndRevisit(val, residualFunctionBinding) { let refScope = this.containingAdditionalFunction ? this.containingAdditionalFunction : "GLOBAL"; (0, _invariant2.default)(!(refScope instanceof _generator.Generator)); let funcToScopes = (0, _utils.getOrDefault)(this.functionToCapturedScopes, refScope, () => new Map()); let envRec = residualFunctionBinding.declarativeEnvironmentRecord; (0, _invariant2.default)(envRec !== null); let bindingState = (0, _utils.getOrDefault)(funcToScopes, envRec, () => ({ capturedBindings: new Set(), capturingFunctionsToCommonScope: new Map() })); // If the binding is new for this bindingState, have all functions capturing bindings from that scope visit it if (!bindingState.capturedBindings.has(residualFunctionBinding)) { if (residualFunctionBinding.value) { (0, _invariant2.default)(this); for (let [functionValue, functionCommonScope] of bindingState.capturingFunctionsToCommonScope) { (0, _invariant2.default)(this); let prevCommonScope = this.commonScope; try { this.commonScope = functionCommonScope; let value = residualFunctionBinding.value; this._withScope(functionValue, () => this.visitValue(value)); } finally { this.commonScope = prevCommonScope; } } } bindingState.capturedBindings.add(residualFunctionBinding); } // If the function is new for this bindingState, visit all existent bindings in this scope if (!bindingState.capturingFunctionsToCommonScope.has(val)) { for (let residualBinding of bindingState.capturedBindings) { if (residualBinding.value) this.visitValue(residualBinding.value); } bindingState.capturingFunctionsToCommonScope.set(val, this.commonScope); } } // Visits a binding, if createBinding is true, will always return a ResidualFunctionBinding // otherwise visits + returns the binding only if one already exists. visitBinding(val, name, createBinding = true) { let residualFunctionBinding; let doesNotMatter = true; let reference = this.logger.tryQuery(() => _singletons.Environment.ResolveBinding(this.realm, name, doesNotMatter, val.$Environment), undefined); let getFromMap = createBinding ? _utils.getOrDefault : (map, key, defaultFn) => map.get(key); if (reference === undefined || _singletons.Environment.IsUnresolvableReference(this.realm, reference) || reference.base instanceof _environment.GlobalEnvironmentRecord) { // Global Binding residualFunctionBinding = getFromMap(this.globalBindings, name, () => ({ value: this.realm.getGlobalLetBinding(name), modified: true, declarativeEnvironmentRecord: null })); } else { // DeclarativeEnvironmentRecord binding (0, _invariant2.default)(!_singletons.Environment.IsUnresolvableReference(this.realm, reference)); let referencedBase = reference.base; let referencedName = reference.referencedName; if (typeof referencedName !== "string") { throw new _errors.FatalError("TODO: do not know how to visit reference with symbol"); } (0, _invariant2.default)(referencedBase instanceof _environment.DeclarativeEnvironmentRecord); let residualFunctionBindings = (0, _utils.getOrDefault)(this.declarativeEnvironmentRecordsBindings, referencedBase, () => new Map()); let createdBinding = !residualFunctionBindings.has(referencedName); residualFunctionBinding = getFromMap(residualFunctionBindings, referencedName, () => { (0, _invariant2.default)(referencedBase instanceof _environment.DeclarativeEnvironmentRecord); let binding = referencedBase.bindings[referencedName]; (0, _invariant2.default)(!binding.deletable); return { value: binding.initialized && binding.value || this.realm.intrinsics.undefined, modified: false, declarativeEnvironmentRecord: referencedBase }; }); if (residualFunctionBinding) { if (this.containingAdditionalFunction && createdBinding) residualFunctionBinding.referencedOnlyFromAdditionalFunctions = this.containingAdditionalFunction; if (!this.containingAdditionalFunction && residualFunctionBinding.referencedOnlyFromAdditionalFunctions) delete residualFunctionBinding.referencedOnlyFromAdditionalFunctions; this._recordBindingVisitedAndRevisit(val, residualFunctionBinding); } } if (residualFunctionBinding && residualFunctionBinding.value) { residualFunctionBinding.value = this.visitEquivalentValue(residualFunctionBinding.value); } return residualFunctionBinding; } _visitClass(classFunc, classPrototype) { let visitClassMethod = (propertyNameOrSymbol, methodFunc, methodType, isStatic) => { if (methodFunc instanceof _index2.ECMAScriptSourceFunctionValue) { // if the method does not have a $HomeObject, it's not a class method if (methodFunc.$HomeObject !== undefined) { if (methodFunc !== classFunc) { this._visitClassMethod(methodFunc, methodType, classPrototype, !!isStatic); } } } }; for (let [propertyName, method] of classPrototype.properties) { (0, _utils.withDescriptorValue)(propertyName, method.descriptor, visitClassMethod); } for (let [symbol, method] of classPrototype.symbols) { (0, _utils.withDescriptorValue)(symbol, method.descriptor, visitClassMethod); } // handle class inheritance if (!(classFunc.$Prototype instanceof _index2.NativeFunctionValue)) { this.visitValue(classFunc.$Prototype); } if (classPrototype.properties.has("constructor")) { let constructor = classPrototype.properties.get("constructor"); (0, _invariant2.default)(constructor !== undefined); // check if the constructor was deleted, as it can't really be deleted // it just gets set to empty (the default again) if (constructor.descriptor === undefined) { classFunc.$HasEmptyConstructor = true; } else { let visitClassProperty = (propertyNameOrSymbol, methodFunc, methodType) => { visitClassMethod(propertyNameOrSymbol, methodFunc, methodType, true); }; // check if we have any static methods we need to include let constructorFunc = (0, _index.Get)(this.realm, classPrototype, "constructor"); (0, _invariant2.default)(constructorFunc instanceof _index2.ObjectValue); for (let [propertyName, method] of constructorFunc.properties) { if (!_utils.ClassPropertiesToIgnore.has(propertyName) && method.descriptor !== undefined && !(propertyName === "length" && (0, _utils.canIgnoreClassLengthProperty)(constructorFunc, method.descriptor, this.logger))) { (0, _utils.withDescriptorValue)(propertyName, method.descriptor, visitClassProperty); } } } } this.classMethodInstances.set(classFunc, { classPrototype, methodType: "constructor", classSuperNode: undefined, classMethodIsStatic: false, classMethodKeyNode: undefined, classMethodComputed: false }); } _visitClassMethod(methodFunc, methodType, classPrototype, isStatic) { this.classMethodInstances.set(methodFunc, { classPrototype, methodType: methodType === "value" ? "method" : methodType, classSuperNode: undefined, classMethodIsStatic: isStatic, classMethodKeyNode: undefined, classMethodComputed: !!methodFunc.$HasComputedName }); } visitValueObject(val) { this._registerAdditionalRoot(val); let kind = val.getKind(); this.visitObjectProperties(val, kind); // If this object is a prototype object that was implicitly created by the runtime // for a constructor, then we can obtain a reference to this object // in a special way that's handled alongside function serialization. let constructor = val.originalConstructor; if (constructor !== undefined) { this.visitValue(constructor); return; } switch (kind) { case "RegExp": case "Number": case "String": case "Boolean": case "ArrayBuffer": return; case "ReactElement": this.someReactElement = val; // check we can hoist a React Element (0, _hoisting.canHoistReactElement)(this.realm, val, this); return; case "Date": let dateValue = val.$DateValue; (0, _invariant2.default)(dateValue !== undefined); this.visitValue(dateValue); return; case "Float32Array": case "Float64Array": case "Int8Array": case "Int16Array": case "Int32Array": case "Uint8Array": case "Uint16Array": case "Uint32Array": case "Uint8ClampedArray": case "DataView": let buf = val.$ViewedArrayBuffer; (0, _invariant2.default)(buf !== undefined); this.visitValue(buf); return; case "Map": case "WeakMap": this.visitValueMap(val); return; case "Set": case "WeakSet": this.visitValueSet(val); return; default: if (kind !== "Object") this.logger.logError(val, `Object of kind ${kind} is not supported in residual heap.`); if (this.$ParameterMap !== undefined) { this.logger.logError(val, `Arguments object is not supported in residual heap.`); } if (this.realm.react.enabled && (0, _utils2.valueIsReactLibraryObject)(this.realm, val, this.logger)) { this.realm.fbLibraries.react = val; } return; } } visitValueSymbol(val) { if (val.$Description) this.visitValue(val.$Description); } visitValueProxy(val) { this.visitValue(val.$ProxyTarget); this.visitValue(val.$ProxyHandler); } visitAbstractValue(val) { if (val.kind === "sentinel member expression") this.logger.logError(val, "expressions of type o[p] are not yet supported for partially known o and unknown p"); if (val.kind === "sentinel ToObject") this.logger.logError(val, "Unknown object cannot be coerced to Object"); for (let i = 0, n = val.args.length; i < n; i++) { val.args[i] = this.visitEquivalentValue(val.args[i]); } } // Overridable hook for pre-visiting the value. // Return false will tell visitor to skip visiting children of this node. preProcessValue(val) { return this._mark(val); } // Overridable hook for post-visiting the value. postProcessValue(val) {} _mark(val) { let scopes = this.values.get(val); if (scopes === undefined) this.values.set(val, scopes = new Set()); if (scopes.has(this.scope)) return false; scopes.add(this.scope); return true; } visitEquivalentValue(val) { if (val instanceof _index2.AbstractValue) { let equivalentValue = this.equivalenceSet.add(val); if (this.preProcessValue(equivalentValue)) this.visitAbstractValue(equivalentValue); this.postProcessValue(equivalentValue); return equivalentValue; } if (val instanceof _index2.ObjectValue && (0, _utils2.isReactElement)(val)) { let equivalentReactElementValue = this.reactElementEquivalenceSet.add(val); if (this._mark(equivalentReactElementValue)) this.visitValueObject(equivalentReactElementValue); return equivalentReactElementValue; } this.visitValue(val); return val; } visitValue(val) { (0, _invariant2.default)(!val.refuseSerialization); if (val instanceof _index2.AbstractValue) { if (this.preProcessValue(val)) this.visitAbstractValue(val); } else if (val.isIntrinsic()) { // All intrinsic values exist from the beginning of time... // ...except for a few that come into existence as templates for abstract objects via executable code. if (val._isScopedTemplate) this.preProcessValue(val);else this._withScope(this.commonScope, () => { this.preProcessValue(val); }); } else if (val instanceof _index2.EmptyValue) { this.preProcessValue(val); } else if (_ResidualHeapInspector.ResidualHeapInspector.isLeaf(val)) { this.preProcessValue(val); } else if ((0, _index.IsArray)(this.realm, val)) { (0, _invariant2.default)(val instanceof _index2.ObjectValue); if (this.preProcessValue(val)) this.visitValueArray(val); } else if (val instanceof _index2.ProxyValue) { if (this.preProcessValue(val)) this.visitValueProxy(val); } else if (val instanceof _index2.FunctionValue) { // Function declarations should get hoisted in common scope so that instances only get allocated once let parentScope = this.scope; // Every function references itself through arguments, prevent the recursive double-visit if (this.scope !== val && this.commonScope !== val) this._withScope(this.commonScope, () => { (0, _invariant2.default)(val instanceof _index2.FunctionValue); if (this.preProcessValue(val)) this.visitValueFunction(val, parentScope); }); } else if (val instanceof _index2.SymbolValue) { if (this.preProcessValue(val)) this.visitValueSymbol(val); } else { (0, _invariant2.default)(val instanceof _index2.ObjectValue); // Prototypes are reachable via function declarations, and those get hoisted, so we need to move // prototype initialization to the common scope code as well. if (val.originalConstructor !== undefined) { this._withScope(this.commonScope, () => { (0, _invariant2.default)(val instanceof _index2.ObjectValue); if (this.preProcessValue(val)) this.visitValueObject(val); }); } else { if (this.preProcessValue(val)) this.visitValueObject(val); } } this.postProcessValue(val); } createGeneratorVisitCallbacks(commonScope) { return { visitValues: values => { for (let i = 0, n = values.length; i < n; i++) values[i] = this.visitEquivalentValue(values[i]); }, visitGenerator: (generator, parent) => { // TODO: The serializer assumes that each generator has a unique parent; however, in the presence of conditional exceptions that is not actually true. // invariant(!this.generatorParents.has(generator)); this.generatorParents.set(generator, parent); this.visitGenerator(generator); }, canSkip: value => { return !this.referencedDeclaredValues.has(value) && !this.values.has(value); }, recordDeclaration: value => { this.referencedDeclaredValues.set(value, this.containingAdditionalFunction); }, recordDelayedEntry: (generator, entry) => { this.delayedVisitGeneratorEntries.push({ commonScope, generator, entry }); } }; } visitGenerator(generator) { this._withScope(generator, () => { generator.visit(this.createGeneratorVisitCallbacks(this.commonScope)); }); } // result -- serialized as a return statement // Generator -- visit all entries // Bindings -- (modifications to named variables) only need to serialize bindings if they're // captured by a residual function // -- need to apply them and maybe need to revisit functions in ancestors to make sure // we don't overwrite anything they capture // PropertyBindings -- (property modifications) visit any property bindings to pre-existing objects // CreatedObjects -- should take care of itself _visitEffects(additionalFunctionInfo, effects) { let functionValue = additionalFunctionInfo.functionValue; (0, _invariant2.default)(functionValue instanceof _index2.ECMAScriptSourceFunctionValue); let code = functionValue.$ECMAScriptCode; let functionInfo = this.functionInfos.get(code); (0, _invariant2.default)(functionInfo !== undefined); let [result,, modifiedBindings, modifiedProperties, createdObjects] = effects; for (let propertyBinding of modifiedProperties.keys()) { let object = propertyBinding.object; if (object instanceof _index2.ObjectValue && createdObjects.has(object)) continue; // Created Object's binding if (object.refuseSerialization) continue; // modification to internal state if (object.intrinsicName === "global") continue; // Avoid double-counting this.visitObjectProperty(propertyBinding); } // Handing of ModifiedBindings for (let [additionalBinding, previousValue] of modifiedBindings) { let modifiedBinding = additionalBinding; let residualBinding; this._withScope(functionValue, () => { // Also visit the original value of the binding residualBinding = this.visitBinding(functionValue, modifiedBinding.name); (0, _invariant2.default)(residualBinding !== undefined); // named functions inside an additional function that have a global binding // can be skipped, as we don't want them to bind to the global if (residualBinding.declarativeEnvironmentRecord === null && modifiedBinding.value instanceof _index2.ECMAScriptSourceFunctionValue) { residualBinding = null; return; } // Fixup the binding to have the correct value // No previousValue means this is a binding for a nested function if (previousValue && previousValue.value) residualBinding.value = this.visitEquivalentValue(previousValue.value); (0, _invariant2.default)(functionInfo !== undefined); if (functionInfo.modified.has(modifiedBinding.name)) residualBinding.modified; }); if (residualBinding === null) continue; (0, _invariant2.default)(residualBinding); let funcInstance = additionalFunctionInfo.instance; (0, _invariant2.default)(funcInstance !== undefined); funcInstance.residualFunctionBindings.set(modifiedBinding.name, residualBinding); let newValue = modifiedBinding.value; (0, _invariant2.default)(newValue); this.visitValue(newValue); residualBinding.modified = true; // This should be enforced by checkThatFunctionsAreIndependent (0, _invariant2.default)(!residualBinding.additionalFunctionOverridesValue, "We should only have one additional function value modifying any given residual binding"); if (previousValue && previousValue.value) residualBinding.additionalFunctionOverridesValue = functionValue; additionalFunctionInfo.modifiedBindings.set(modifiedBinding, residualBinding); } (0, _invariant2.default)(result instanceof _index2.Value); if (!(result instanceof _index2.UndefinedValue)) this.visitValue(result); } _visitAdditionalFunction(functionValue, additionalEffects, parentScope) { // Get Instance + Info (0, _invariant2.default)(functionValue instanceof _index2.ECMAScriptSourceFunctionValue); let code = functionValue.$ECMAScriptCode; let functionInfo = this.functionInfos.get(code); (0, _invariant2.default)(functionInfo !== undefined); let funcInstance = this.functionInstances.get(functionValue); (0, _invariant2.default)(funcInstance !== undefined); // Set Visitor state // Allows us to emit function declarations etc. inside of this additional // function instead of adding them at global scope let prevCommonScope = this.commonScope; this.commonScope = functionValue; let oldReactElementEquivalenceSet = this.reactElementEquivalenceSet; this.reactElementEquivalenceSet = new _ReactElementSet2.default(this.realm, this.equivalenceSet); let oldcontainingAdditionalFunction = this.containingAdditionalFunction; this.containingAdditionalFunction = functionValue; let prevReVisit = this.additionalRoots; this.additionalRoots = new Map(); let modifiedBindingInfo = new Map(); let [, generator,,, createdObjects] = additionalEffects.effects; (0, _invariant2.default)(funcInstance !== undefined); (0, _invariant2.default)(functionInfo !== undefined); let additionalFunctionInfo = { functionValue, captures: functionInfo.unbound, modifiedBindings: modifiedBindingInfo, instance: funcInstance }; this.additionalFunctionValueInfos.set(functionValue, additionalFunctionInfo); this.realm.withEffectsAppliedInGlobalEnv(effects => { this.visitGenerator(generator); // All modified properties and bindings should be accessible // from its containing additional function scope. this._withScope(functionValue, this._visitEffects.bind(this, additionalFunctionInfo, effects)); return this.realm.intrinsics.undefined; }, additionalEffects.effects); for (let createdObject of createdObjects) this.additionalRoots.delete(createdObject); // Cleanup this.commonScope = prevCommonScope; this.reactElementEquivalenceSet = oldReactElementEquivalenceSet; this._withScope(parentScope, // Re-visit any bindings corresponding to unbound values or values closed over from outside additional function // they're serialized in the correct scope () => { (0, _invariant2.default)(functionInfo !== undefined); (0, _invariant2.default)(funcInstance !== undefined); for (let [value, additionalParentGenerators] of this.additionalRoots) { // Populate old additionalRoots because we switched them out prevReVisit.set(value, additionalParentGenerators); this.visitValue(value); } for (let innerName of functionInfo.unbound) { let residualBinding = this.visitBinding(functionValue, innerName, false); if (residualBinding) { funcInstance.residualFunctionBindings.set(innerName, residualBinding); delete residualBinding.referencedOnlyFromAdditionalFunctions; } } this.additionalRoots = prevReVisit; }); this.containingAdditionalFunction = oldcontainingAdditionalFunction; } visitRoots() { let generator = this.realm.generator; (0, _invariant2.default)(generator); this.visitGenerator(generator); for (let moduleValue of this.modules.initializedModules.values()) this.visitValue(moduleValue); if (this.realm.react.enabled && this.someReactElement !== undefined) { this._visitReactLibrary(this.someReactElement); } // Do a fixpoint over all pure generator entries to make sure that we visit // arguments of only BodyEntries that are required by some other residual value let oldDelayedEntries = []; while (oldDelayedEntries.length !== this.delayedVisitGeneratorEntries.length) { oldDelayedEntries = this.delayedVisitGeneratorEntries; this.delayedVisitGeneratorEntries = []; for (let _ref of oldDelayedEntries) { let { commonScope, generator: entryGenerator, entry } = _ref; this.commonScope = commonScope; this._withScope(entryGenerator, () => { entryGenerator.visitEntry(entry, this.createGeneratorVisitCallbacks(commonScope)); }); } } let referentializer = this.referentializer; if (referentializer !== undefined) { let bodyToInstances = new Map(); for (let instance of this.functionInstances.values()) { // TODO: do something for additional functions if (!this.additionalFunctionValuesAndEffects.has(instance.functionValue)) { let code = instance.functionValue.$ECMAScriptCode; (0, _invariant2.default)(code !== undefined); (0, _utils.getOrDefault)(bodyToInstances, code, () => []).push(instance); } } for (let [funcBody, instances] of bodyToInstances) { let functionInfo = this.functionInfos.get(funcBody); (0, _invariant2.default)(functionInfo !== undefined); referentializer.referentialize(functionInfo.unbound, instances, instance => !this.additionalFunctionValuesAndEffects.has(instance.functionValue)); } } } _visitReactLibrary(someReactElement) { // find and visit the React library let reactLibraryObject = this.realm.fbLibraries.react; if (this.realm.react.output === "jsx") { // React might not be defined in scope, i.e. another library is using JSX // we don't throw an error as we should support JSX stand-alone if (reactLibraryObject !== undefined) { this.visitValue(reactLibraryObject); } } else if (this.realm.react.output === "create-element") { let logError = () => { this.logger.logError(someReactElement, "unable to visit createElement due to React not being referenced in scope"); }; // createElement output needs React in scope if (reactLibraryObject === undefined) { logError(); } else { (0, _invariant2.default)(reactLibraryObject instanceof _index2.ObjectValue); let createElement = reactLibraryObject.properties.get("createElement"); if (createElement === undefined || createElement.descriptor === undefined) { logError(); } else { let reactCreateElement = (0, _index.Get)(this.realm, reactLibraryObject, "createElement"); this.visitValue(reactCreateElement); } } } } } exports.ResidualHeapVisitor = ResidualHeapVisitor; //# sourceMappingURL=ResidualHeapVisitor.js.map /***/ }), /* 165 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ResidualHeapInspector = undefined; var _realm = __webpack_require__(11); var _index = __webpack_require__(5); var _index2 = __webpack_require__(0); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _logger = __webpack_require__(61); var _utils = __webpack_require__(27); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ class ResidualHeapInspector { constructor(realm, logger) { this.realm = realm; this.logger = logger; this.ignoredProperties = new Map(); this._targetIntegrityCommands = new Map(); } getTargetIntegrityCommand(val) { let command = this._targetIntegrityCommands.get(val); if (command === undefined) { command = ""; if (val instanceof _index2.ProxyValue) { // proxies don't participate in regular object freezing/sealing, // only their underlying proxied objects do } else { let extensible = val.$Extensible; if (!(extensible instanceof _index2.BooleanValue)) { this.logger.logError(val, "Object that might or might not be sealed or frozen are not supported in residual heap."); } else if (!extensible.value) { let anyWritable = false, anyConfigurable = false; for (let propertyBinding of val.properties.values()) { let desc = propertyBinding.descriptor; if (desc === undefined) continue; //deleted if (desc.configurable) anyConfigurable = true;else if (desc.value !== undefined && desc.writable) anyWritable = true; } command = anyConfigurable ? "preventExtensions" : anyWritable ? "seal" : "freeze"; } } this._targetIntegrityCommands.set(val, command); } return command; } getTargetIntegrityDescriptor(val) { return ResidualHeapInspector._integrityDescriptors[this.getTargetIntegrityCommand(val)]; } static isLeaf(val) { if (val instanceof _index2.SymbolValue) { return false; } if (val instanceof _index2.AbstractValue && val.hasIdentifier()) { return true; } if (val.isIntrinsic()) { return false; } return val instanceof _index2.PrimitiveValue; } // Object properties which have the default value can be ignored by the serializer. canIgnoreProperty(val, key) { let set = this.ignoredProperties.get(val); if (!set) { this.ignoredProperties.set(val, set = this._getIgnoredProperties(val)); } return set.has(key); } _getIgnoredProperties(val) { let set = new Set(); for (let [key, propertyBinding] of val.properties) { (0, _invariant2.default)(propertyBinding); let desc = propertyBinding.descriptor; if (desc === undefined) continue; //deleted if (this._canIgnoreProperty(val, key, desc)) set.add(key); } return set; } _canIgnoreProperty(val, key, desc) { let targetDescriptor = this.getTargetIntegrityDescriptor(val); if ((0, _index.IsArray)(this.realm, val)) { if (key === "length" && desc.writable === targetDescriptor.writable && !desc.enumerable && !desc.configurable) { // length property has the correct descriptor values return true; } } else if ((0, _utils.isReactElement)(val)) { // we don't want to visit/serialize $$typeof, _owner and _store properties // as these are all internals of JSX/createElement if (key === "$$typeof" || key === "_owner" || key === "_store") { return true; } if ((key === "ref" || key === "key") && desc.value === this.realm.intrinsics.null) { return true; } } else if (val instanceof _index2.FunctionValue) { if (key === "length") { if (desc.value === undefined) { this.logger.logError(val, "Functions with length accessor properties are not supported in residual heap."); // Rationale: .bind() would call the accessor, which might throw, mutate state, or do whatever... } // length property will be inferred already by the amount of parameters return !desc.writable && !desc.enumerable && desc.configurable === targetDescriptor.configurable && val.hasDefaultLength(); } if (key === "name") { // TODO #474: Make sure that we retain original function names. Or set name property. // Or ensure that nothing references the name property. // NOTE: with some old runtimes notably JSC, function names are not configurable // For now don't ignore the property if it is different from the function name. // I.e. if it was set explicitly in the code, retain it. if (desc.value !== undefined && !this.realm.isCompatibleWith(this.realm.MOBILE_JSC_VERSION) && !this.realm.isCompatibleWith("mobile") && (desc.value instanceof _index2.AbstractValue || val.__originalName && val.__originalName !== "" && desc.value.value !== val.__originalName)) return false; return true; } // Properties `caller` and `arguments` are added to normal functions in non-strict mode to prevent TypeErrors. // Because they are autogenerated, they should be ignored. if (key === "arguments" || key === "caller") { (0, _invariant2.default)(val instanceof _index2.ECMAScriptSourceFunctionValue); if (!val.$Strict && desc.writable === (!val.$Strict && targetDescriptor.writable) && !desc.enumerable && desc.configurable === targetDescriptor.configurable && desc.value instanceof _index2.UndefinedValue && val.$FunctionKind === "normal") return true; } // ignore the `prototype` property when it's the right one if (key === "prototype") { if (!desc.configurable && !desc.enumerable && desc.writable === targetDescriptor.writable && desc.value instanceof _index2.ObjectValue && desc.value.originalConstructor === val) { return true; } } } else { let kind = val.getKind(); switch (kind) { case "RegExp": if (key === "lastIndex" && desc.writable === targetDescriptor.writable && !desc.enumerable && !desc.configurable) { // length property has the correct descriptor values let v = desc.value; return v instanceof _index2.NumberValue && v.value === 0; } break; default: break; } } if (key === "constructor") { if (desc.configurable === targetDescriptor.configurable && !desc.enumerable && desc.writable === targetDescriptor.writable && desc.value === val.originalConstructor) return true; } return false; } static getPropertyValue(val, name) { let prototypeBinding = val.properties.get(name); if (prototypeBinding === undefined) return undefined; let prototypeDesc = prototypeBinding.descriptor; if (prototypeDesc === undefined) return undefined; (0, _invariant2.default)(prototypeDesc.value === undefined || prototypeDesc.value instanceof _index2.Value); return prototypeDesc.value; } isDefaultPrototype(prototype) { if (prototype.symbols.size !== 0 || prototype.$Prototype !== this.realm.intrinsics.ObjectPrototype || prototype.$Extensible.mightNotBeTrue()) { return false; } let foundConstructor = false; for (let name of prototype.properties.keys()) if (name === "constructor" && ResidualHeapInspector.getPropertyValue(prototype, name) === prototype.originalConstructor) foundConstructor = true;else return false; return foundConstructor; } } exports.ResidualHeapInspector = ResidualHeapInspector; ResidualHeapInspector._integrityDescriptors = { "": { writable: true, configurable: true }, preventExtensions: { writable: true, configurable: true }, seal: { writable: true, configurable: false }, freeze: { writable: false, configurable: false } }; //# sourceMappingURL=ResidualHeapInspector.js.map /***/ }), /* 166 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClassPropertiesToIgnore = undefined; exports.getSuggestedArrayLiteralLength = getSuggestedArrayLiteralLength; exports.commonAncestorOf = commonAncestorOf; exports.getOrDefault = getOrDefault; exports.withDescriptorValue = withDescriptorValue; exports.canIgnoreClassLengthProperty = canIgnoreClassLengthProperty; exports.getObjectPrototypeMetadata = getObjectPrototypeMetadata; var _index = __webpack_require__(0); var _errors = __webpack_require__(6); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _index2 = __webpack_require__(5); var _logger = __webpack_require__(61); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Get index property list length by searching array properties list for the max index key value plus 1. */ function getSuggestedArrayLiteralLength(realm, val) { (0, _invariant2.default)((0, _index2.IsArray)(realm, val)); let length = 0; for (const key of val.properties.keys()) { if ((0, _index2.IsArrayIndex)(realm, key) && Number(key) >= length) { length = Number(key) + 1; } } return length; } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function commonAncestorOf(node1, node2, getParent) { if (node1 === node2) return node1; // First get the path length to the root node for both nodes while also checking if // either node is the parent of the other. let n1 = node1, n2 = node2, count1 = 0, count2 = 0; while (true) { let p1 = n1 && getParent(n1); let p2 = n2 && getParent(n2); if (p1 === node2) return node2; if (p2 === node1) return node1; if (p1) count1++; if (p2) count2++; if (!p1 && !p2) break; n1 = p1; n2 = p2; } // Now shorten the longest path to the same length as the shorter path n1 = node1; while (count1 > count2) { (0, _invariant2.default)(n1 !== undefined); n1 = getParent(n1); count1--; } n2 = node2; while (count1 < count2) { (0, _invariant2.default)(n2 !== undefined); n2 = getParent(n2); count2--; } // Now run up both paths in tandem, stopping at the first common entry while (n1 !== n2) { (0, _invariant2.default)(n1 !== undefined); n1 = getParent(n1); (0, _invariant2.default)(n2 !== undefined); n2 = getParent(n2); } return n1; } // Gets map[key] with default value provided by defaultFn function getOrDefault(map, key, defaultFn) { let value = map.get(key); if (value === undefined) map.set(key, value = defaultFn()); (0, _invariant2.default)(value !== undefined); return value; } function withDescriptorValue(propertyNameOrSymbol, descriptor, func) { if (descriptor !== undefined) { if (descriptor.value !== undefined) { func(propertyNameOrSymbol, descriptor.value, "value"); } else { if (descriptor.get !== undefined) { func(propertyNameOrSymbol, descriptor.get, "get"); } if (descriptor.set !== undefined) { func(propertyNameOrSymbol, descriptor.set, "set"); } } } } const ClassPropertiesToIgnore = exports.ClassPropertiesToIgnore = new Set(["arguments", "name", "caller"]); function canIgnoreClassLengthProperty(val, desc, logger) { if (desc && desc.value === undefined) { logger.logError(val, "Functions with length accessor properties are not supported in residual heap."); } return true; } function getObjectPrototypeMetadata(realm, obj) { let proto = obj.$Prototype; let skipPrototype = false; let constructor; if (obj.$IsClassPrototype) { skipPrototype = true; } if (proto.$IsClassPrototype) { (0, _invariant2.default)(proto instanceof _index.ObjectValue); // we now need to check if the prototpe has a constructor if (proto.properties.has("constructor")) { let _constructor = proto.properties.get("constructor"); (0, _invariant2.default)(_constructor !== undefined); // if the contructor has been deleted then we have no way // to serialize the original class AST as it won't have been // evluated and thus visited if (_constructor.descriptor === undefined) { throw new _errors.FatalError("TODO #1024: implement object prototype serialization with deleted constructor"); } let classFunc = (0, _index2.Get)(realm, proto, "constructor"); constructor = classFunc; (0, _invariant2.default)(constructor instanceof _index.ECMAScriptSourceFunctionValue); skipPrototype = true; } } return { skipPrototype, constructor }; } //# sourceMappingURL=utils.js.map /***/ }), /* 167 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InternalGetResultValue = InternalGetResultValue; exports.LoopContinues = LoopContinues; exports.ForInOfHeadEvaluation = ForInOfHeadEvaluation; exports.ForInOfBodyEvaluation = ForInOfBodyEvaluation; exports.default = function (ast, strictCode, env, realm, labelSet) { let { left, right, body } = ast; try { if (left.type === "VariableDeclaration") { if (left.kind === "var") { // for (var ForBinding o fAssignmentExpression) Statement // 1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(« », AssignmentExpression, iterate). let keyResult = ForInOfHeadEvaluation(realm, env, [], right, "iterate", strictCode); (0, _invariant2.default)(keyResult instanceof _index.ObjectValue); // 2. Return ? ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult, varBinding, labelSet). return ForInOfBodyEvaluation(realm, env, left.declarations[0].id, body, keyResult, "varBinding", labelSet, strictCode); } else { // for (ForDeclaration of AssignmentExpression) Statement // 1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(BoundNames of ForDeclaration, AssignmentExpression, iterate). let keyResult = ForInOfHeadEvaluation(realm, env, _singletons.Environment.BoundNames(realm, left), right, "iterate", strictCode); (0, _invariant2.default)(keyResult instanceof _index.ObjectValue); // 2. Return ? ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, lexicalBinding, labelSet). return ForInOfBodyEvaluation(realm, env, left, body, keyResult, "lexicalBinding", labelSet, strictCode); } } else { // for (LeftHandSideExpression of AssignmentExpression) Statement // 1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(« », AssignmentExpression, iterate). let keyResult = ForInOfHeadEvaluation(realm, env, [], right, "iterate", strictCode); (0, _invariant2.default)(keyResult instanceof _index.ObjectValue); // 2. Return ? ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, assignment, labelSet). return ForInOfBodyEvaluation(realm, env, left, body, keyResult, "assignment", labelSet, strictCode); } } catch (e) { if (e instanceof _completions.BreakCompletion) { if (!e.target) return (0, _index2.UpdateEmpty)(realm, e, realm.intrinsics.undefined).value; } throw e; } }; var _errors = __webpack_require__(6); var _environment = __webpack_require__(12); var _completions = __webpack_require__(3); var _index = __webpack_require__(0); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _index2 = __webpack_require__(5); var _singletons = __webpack_require__(2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function InternalGetResultValue(realm, result) { if (result instanceof _completions.AbruptCompletion) { return result.value; } else { return result; } } // ECMA262 13.7.1.2 function LoopContinues(realm, completion, labelSet) { // 1. If completion.[[Type]] is normal, return true. if (completion instanceof _index.Value) return true; (0, _invariant2.default)(completion instanceof _completions.AbruptCompletion); // 2. If completion.[[Type]] is not continue, return false. if (!(completion instanceof _completions.ContinueCompletion)) return false; // 3. If completion.[[Target]] is empty, return true. if (!completion.target) return true; // 4. If completion.[[Target]] is an element of labelSet, return true. if (labelSet != null && labelSet.indexOf(completion.target) >= 0) return true; // 5. Return false. return false; } // ECMA262 13.7.5.10 function BindingInstantiation(realm, ast, env) { // ast = ForDeclaration : LetOrConst ForBinding // 1. Let envRec be environment's EnvironmentRecord. let envRec = env.environmentRecord; // 2. Assert: envRec is a declarative Environment Record. (0, _invariant2.default)(envRec instanceof _environment.DeclarativeEnvironmentRecord); // 3. For each element name of the BoundNames of ForBinding do for (let name of _singletons.Environment.BoundNames(realm, ast)) { // a. If IsConstantDeclaration of LetOrConst is true, then if (ast.kind === "const") { // i. Perform ! envRec.CreateImmutableBinding(name, true). envRec.CreateImmutableBinding(name, true); } else { // b. // i. Perform ! envRec.CreateMutableBinding(name, false). envRec.CreateMutableBinding(name, false); } } } // ECMA262 13.7.5.12 function ForInOfHeadEvaluation(realm, env, TDZnames, expr, iterationKind, strictCode) { // 1. Let oldEnv be the running execution context's LexicalEnvironment. let oldEnv = realm.getRunningContext().lexicalEnvironment; // 2. If TDZnames is not an empty List, then if (TDZnames.length) { // a. Assert: TDZnames has no duplicate entries. // b. Let TDZ be NewDeclarativeEnvironment(oldEnv). let TDZ = _singletons.Environment.NewDeclarativeEnvironment(realm, oldEnv); // c. Let TDZEnvRec be TDZ's EnvironmentRecord. let TDZEnvRec = TDZ.environmentRecord; // d. For each string name in TDZnames, do for (let name of TDZnames) { // i. Perform ! TDZEnvRec.CreateMutableBinding(name, false). TDZEnvRec.CreateMutableBinding(name, false); } // e. Set the running execution context's LexicalEnvironment to TDZ. realm.getRunningContext().lexicalEnvironment = TDZ; env = TDZ; } let exprRef; try { // 3. Let exprRef be the result of evaluating expr. exprRef = env.evaluate(expr, strictCode); } finally { // 4. Set the running execution context's LexicalEnvironment to oldEnv. let lexEnv = realm.getRunningContext().lexicalEnvironment; if (lexEnv !== oldEnv) realm.onDestroyScope(lexEnv); realm.getRunningContext().lexicalEnvironment = oldEnv; } env = oldEnv; // 5. Let exprValue be ? GetValue(exprRef). let exprValue = _singletons.Environment.GetValue(realm, exprRef); // 6. If iterationKind is enumerate, then if (iterationKind === "enumerate") { // a. If exprValue.[[Value]] is null or undefined, then if (exprValue instanceof _index.NullValue || exprValue instanceof _index.UndefinedValue) { // i. Return Completion{[[Type]]: break, [[Value]]: empty, [[Target]]: empty}. throw new _completions.BreakCompletion(realm.intrinsics.empty, expr.loc, undefined); } // b. Let obj be ToObject(exprValue). let obj = _singletons.To.ToObjectPartial(realm, exprValue); // c. Return ? EnumerateObjectProperties(obj). if (obj.isPartialObject() || obj instanceof _index.AbstractObjectValue) { return obj; } else { return _singletons.Properties.EnumerateObjectProperties(realm, obj); } } else { // 8. Else, // 1. Assert: iterationKind is iterate. (0, _invariant2.default)(iterationKind === "iterate", "expected iterationKind to be iterate"); if (exprValue instanceof _index.AbstractValue) { let error = new _errors.CompilerDiagnostic("for of loops over unknown collections are not yet supported", expr.loc, "PP0014", "FatalError"); realm.handleError(error); throw new _errors.FatalError(); } // 1. Return ? GetIterator(exprValue). return (0, _index2.GetIterator)(realm, exprValue); } } // ECMA262 13.7.5.13 function ForInOfBodyEvaluation(realm, env, lhs, stmt, iterator, lhsKind, labelSet, strictCode) { // 1. Let oldEnv be the running execution context's LexicalEnvironment. let oldEnv = realm.getRunningContext().lexicalEnvironment; // 2. Let V be undefined. let V = realm.intrinsics.undefined; // 3. Let destructuring be IsDestructuring of lhs. let destructuring = _singletons.Environment.IsDestructuring(lhs); // 4. If destructuring is true and if lhsKind is assignment, then if (destructuring && lhsKind === "assignment") { // a. Assert: lhs is a LeftHandSideExpression. (0, _invariant2.default)(lhs.type !== "VariableDeclaration"); // b. Let assignmentPattern be the parse of the source text corresponding to lhs using AssignmentPattern as the goal symbol. } // 5. Repeat while (true) { // a. Let nextResult be ? IteratorStep(iterator). let nextResult = (0, _index2.IteratorStep)(realm, iterator); // b. If nextResult is false, return NormalCompletion(V). if (!nextResult) return V; // c. Let nextValue be ? IteratorValue(nextResult). let nextValue = (0, _index2.IteratorValue)(realm, nextResult); // d. If lhsKind is either assignment or varBinding, then let iterationEnv; let lhsRef; if (lhsKind === "assignment" || lhsKind === "varBinding") { // i. If destructuring is false, then if (!destructuring) { // 1. Let lhsRef be the result of evaluating lhs. (It may be evaluated repeatedly.) lhsRef = env.evaluateCompletion(lhs, strictCode); } } else { // e. Else, // i. Assert: lhsKind is lexicalBinding. (0, _invariant2.default)(lhsKind === "lexicalBinding", "expected lhsKind to be lexicalBinding"); (0, _invariant2.default)(lhs.type === "VariableDeclaration"); // ii. Assert: lhs is a ForDeclaration. // iii. Let iterationEnv be NewDeclarativeEnvironment(oldEnv). iterationEnv = _singletons.Environment.NewDeclarativeEnvironment(realm, oldEnv); // iv. Perform BindingInstantiation for lhs passing iterationEnv as the argument. BindingInstantiation(realm, lhs, iterationEnv); // v. Set the running execution context's LexicalEnvironment to iterationEnv. realm.getRunningContext().lexicalEnvironment = iterationEnv; env = iterationEnv; // vi. If destructuring is false, then if (!destructuring) { let names = _singletons.Environment.BoundNames(realm, lhs); // 1. Assert: lhs binds a single name. (0, _invariant2.default)(names.length === 1, "expected single name"); // 2. Let lhsName be the sole element of BoundNames of lhs. let lhsName = names[0]; // 3. Let lhsRef be ! ResolveBinding(lhsName). lhsRef = _singletons.Environment.ResolveBinding(realm, lhsName, strictCode); } } // f. If destructuring is false, then let status; try { if (!destructuring) { // i. If lhsRef is an abrupt completion, then if (lhsRef instanceof _completions.AbruptCompletion) { // 1. Let status be lhsRef. status = lhsRef; } else if (lhsKind === "lexicalBinding") { // ii. Else if lhsKind is lexicalBinding, then // 1. Let status be InitializeReferencedBinding(lhsRef, nextValue). (0, _invariant2.default)(lhsRef instanceof _environment.Reference); status = _singletons.Environment.InitializeReferencedBinding(realm, lhsRef, nextValue); } else { // iii. Else, // 1. Let status be PutValue(lhsRef, nextValue). (0, _invariant2.default)(lhsRef !== undefined); status = _singletons.Properties.PutValue(realm, lhsRef, nextValue); } } else { // g. Else, // i. If lhsKind is assignment, then if (lhsKind === "assignment") { (0, _invariant2.default)(lhs.type === "ArrayPattern" || lhs.type === "ObjectPattern"); // 1. Let status be the result of performing DestructuringAssignmentEvaluation of assignmentPattern using nextValue as the argument. status = (0, _index2.DestructuringAssignmentEvaluation)(realm, lhs, nextValue, strictCode, iterationEnv || env); } else if (lhsKind === "varBinding") { // ii. Else if lhsKind is varBinding, then // 1. Assert: lhs is a ForBinding. // 2. Let status be the result of performing BindingInitialization for lhs passing nextValue and undefined as the arguments. status = _singletons.Environment.BindingInitialization(realm, lhs, nextValue, strictCode, undefined); } else { // iii. Else, // 1. Assert: lhsKind is lexicalBinding. (0, _invariant2.default)(lhsKind === "lexicalBinding"); // 2. Assert: lhs is a ForDeclaration. // 3. Let status be the result of performing BindingInitialization for lhs passing nextValue and iterationEnv as arguments. (0, _invariant2.default)(iterationEnv !== undefined); status = _singletons.Environment.BindingInitialization(realm, lhs, nextValue, strictCode, iterationEnv); } } } catch (e) { if (e instanceof _completions.AbruptCompletion) { status = e; } else { throw e; } } // h. If status is an abrupt completion, then if (status instanceof _completions.AbruptCompletion) { // i. Set the running execution context's LexicalEnvironment to oldEnv. realm.getRunningContext().lexicalEnvironment = oldEnv; // ii. Return ? IteratorClose(iterator, status). throw (0, _index2.IteratorClose)(realm, iterator, status); } // i. Let result be the result of evaluating stmt. let result = env.evaluateCompletion(stmt, strictCode); (0, _invariant2.default)(result instanceof _index.Value || result instanceof _completions.AbruptCompletion); // j. Set the running execution context's LexicalEnvironment to oldEnv. let lexEnv = realm.getRunningContext().lexicalEnvironment; if (lexEnv !== oldEnv) realm.onDestroyScope(lexEnv); realm.getRunningContext().lexicalEnvironment = oldEnv; env = oldEnv; // k. If LoopContinues(result, labelSet) is false, return ? IteratorClose(iterator, UpdateEmpty(result, V)). if (!LoopContinues(realm, result, labelSet)) { (0, _invariant2.default)(result instanceof _completions.AbruptCompletion); result = (0, _index2.UpdateEmpty)(realm, result, V); (0, _invariant2.default)(result instanceof _completions.AbruptCompletion); throw (0, _index2.IteratorClose)(realm, iterator, result); } // l. If result.[[Value]] is not empty, let V be result.[[Value]]. let resultValue = InternalGetResultValue(realm, result); if (!(resultValue instanceof _index.EmptyValue)) V = resultValue; } /* istanbul ignore next */ (0, _invariant2.default)(false); // can't get here but there is no other way to make Flow happy } // ECMA262 13.7.5.11 //# sourceMappingURL=ForOfStatement.js.map /***/ }), /* 168 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = invariant; /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function invariant(condition, format) { if (condition) return; let error = new Error(format); error.name = "Invariant Violation"; throw error; } //# sourceMappingURL=invariant.js.map /***/ }), /* 169 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(13).Buffer)) /***/ }), /* 170 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var inherits = __webpack_require__(8) var MD5 = __webpack_require__(335) var RIPEMD160 = __webpack_require__(336) var sha = __webpack_require__(337) var Base = __webpack_require__(91) function Hash (hash) { Base.call(this, 'digest') this._hash = hash } inherits(Hash, Base) Hash.prototype._update = function (data) { this._hash.update(data) } Hash.prototype._final = function () { return this._hash.digest() } module.exports = function createHash (alg) { alg = alg.toLowerCase() if (alg === 'md5') return new MD5() if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() return new Hash(sha(alg)) } /***/ }), /* 171 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {module.exports = function xor (a, b) { var length = Math.min(a.length, b.length) var buffer = new Buffer(length) for (var i = 0; i < length; ++i) { buffer[i] = a[i] ^ b[i] } return buffer } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(13).Buffer)) /***/ }), /* 172 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(65); var assert = __webpack_require__(43); function BlockHash() { this.pending = null; this.pendingTotal = 0; this.blockSize = this.constructor.blockSize; this.outSize = this.constructor.outSize; this.hmacStrength = this.constructor.hmacStrength; this.padLength = this.constructor.padLength / 8; this.endian = 'big'; this._delta8 = this.blockSize / 8; this._delta32 = this.blockSize / 32; } exports.BlockHash = BlockHash; BlockHash.prototype.update = function update(msg, enc) { // Convert message to array, pad it, and join into 32bit blocks msg = utils.toArray(msg, enc); if (!this.pending) this.pending = msg; else this.pending = this.pending.concat(msg); this.pendingTotal += msg.length; // Enough data, try updating if (this.pending.length >= this._delta8) { msg = this.pending; // Process pending data in blocks var r = msg.length % this._delta8; this.pending = msg.slice(msg.length - r, msg.length); if (this.pending.length === 0) this.pending = null; msg = utils.join32(msg, 0, msg.length - r, this.endian); for (var i = 0; i < msg.length; i += this._delta32) this._update(msg, i, i + this._delta32); } return this; }; BlockHash.prototype.digest = function digest(enc) { this.update(this._pad()); assert(this.pending === null); return this._digest(enc); }; BlockHash.prototype._pad = function pad() { var len = this.pendingTotal; var bytes = this._delta8; var k = bytes - ((len + this.padLength) % bytes); var res = new Array(k + this.padLength); res[0] = 0x80; for (var i = 1; i < k; i++) res[i] = 0; // Append length len <<= 3; if (this.endian === 'big') { for (var t = 8; t < this.padLength; t++) res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = (len >>> 24) & 0xff; res[i++] = (len >>> 16) & 0xff; res[i++] = (len >>> 8) & 0xff; res[i++] = len & 0xff; } else { res[i++] = len & 0xff; res[i++] = (len >>> 8) & 0xff; res[i++] = (len >>> 16) & 0xff; res[i++] = (len >>> 24) & 0xff; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; for (t = 8; t < this.padLength; t++) res[i++] = 0; } return res; }; /***/ }), /* 173 */ /***/ (function(module, exports, __webpack_require__) { var asn1 = exports; asn1.bignum = __webpack_require__(24); asn1.define = __webpack_require__(2308).define; asn1.base = __webpack_require__(174); asn1.constants = __webpack_require__(671); asn1.decoders = __webpack_require__(2314); asn1.encoders = __webpack_require__(2316); /***/ }), /* 174 */ /***/ (function(module, exports, __webpack_require__) { var base = exports; base.Reporter = __webpack_require__(2311).Reporter; base.DecoderBuffer = __webpack_require__(670).DecoderBuffer; base.EncoderBuffer = __webpack_require__(670).EncoderBuffer; base.Node = __webpack_require__(2312); /***/ }), /* 175 */ /***/ (function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /***/ }), /* 176 */ /***/ (function(module, exports, __webpack_require__) { var baseClone = __webpack_require__(350); /** Used to compose bitmasks for cloning. */ var CLONE_SYMBOLS_FLAG = 4; /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } module.exports = clone; /***/ }), /* 177 */ /***/ (function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(729), listCacheDelete = __webpack_require__(730), listCacheGet = __webpack_require__(731), listCacheHas = __webpack_require__(732), listCacheSet = __webpack_require__(733); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }), /* 178 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(129); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }), /* 179 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(92); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }), /* 180 */ /***/ (function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(753); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } module.exports = getMapData; /***/ }), /* 181 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(352); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(23)(module))) /***/ }), /* 182 */ /***/ (function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; /***/ }), /* 183 */ /***/ (function(module, exports, __webpack_require__) { var DataView = __webpack_require__(774), Map = __webpack_require__(237), Promise = __webpack_require__(775), Set = __webpack_require__(363), WeakMap = __webpack_require__(776), baseGetTag = __webpack_require__(75), toSource = __webpack_require__(353); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }), /* 184 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getBindingIdentifiers; var _generated = __webpack_require__(26); function getBindingIdentifiers(node, duplicates, outerOnly) { let search = [].concat(node); const ids = Object.create(null); while (search.length) { const id = search.shift(); if (!id) continue; const keys = getBindingIdentifiers.keys[id.type]; if ((0, _generated.isIdentifier)(id)) { if (duplicates) { const _ids = ids[id.name] = ids[id.name] || []; _ids.push(id); } else { ids[id.name] = id; } continue; } if ((0, _generated.isExportDeclaration)(id)) { if ((0, _generated.isDeclaration)(id.declaration)) { search.push(id.declaration); } continue; } if (outerOnly) { if ((0, _generated.isFunctionDeclaration)(id)) { search.push(id.id); continue; } if ((0, _generated.isFunctionExpression)(id)) { continue; } } if (keys) { for (let i = 0; i < keys.length; i++) { const key = keys[i]; if (id[key]) { search = search.concat(id[key]); } } } } return ids; } getBindingIdentifiers.keys = { DeclareClass: ["id"], DeclareFunction: ["id"], DeclareModule: ["id"], DeclareVariable: ["id"], DeclareInterface: ["id"], DeclareTypeAlias: ["id"], DeclareOpaqueType: ["id"], InterfaceDeclaration: ["id"], TypeAlias: ["id"], OpaqueType: ["id"], CatchClause: ["param"], LabeledStatement: ["label"], UnaryExpression: ["argument"], AssignmentExpression: ["left"], ImportSpecifier: ["local"], ImportNamespaceSpecifier: ["local"], ImportDefaultSpecifier: ["local"], ImportDeclaration: ["specifiers"], ExportSpecifier: ["exported"], ExportNamespaceSpecifier: ["exported"], ExportDefaultSpecifier: ["exported"], FunctionDeclaration: ["id", "params"], FunctionExpression: ["id", "params"], ArrowFunctionExpression: ["params"], ObjectMethod: ["params"], ClassMethod: ["params"], ForInStatement: ["left"], ForOfStatement: ["left"], ClassDeclaration: ["id"], ClassExpression: ["id"], RestElement: ["argument"], UpdateExpression: ["argument"], ObjectProperty: ["value"], AssignmentPattern: ["left"], ArrayPattern: ["elements"], ObjectPattern: ["properties"], VariableDeclaration: ["declarations"], VariableDeclarator: ["id"] }; /***/ }), /* 185 */ /***/ (function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }), /* 186 */ /***/ (function(module, exports, __webpack_require__) { var baseRepeat = __webpack_require__(846), isIterateeCall = __webpack_require__(187), toInteger = __webpack_require__(135), toString = __webpack_require__(389); /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } module.exports = repeat; /***/ }), /* 187 */ /***/ (function(module, exports, __webpack_require__) { var eq = __webpack_require__(129), isArrayLike = __webpack_require__(78), isIndex = __webpack_require__(242), isObject = __webpack_require__(76); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; /***/ }), /* 188 */ /***/ (function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }), /* 189 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.clear = clear; exports.clearPath = clearPath; exports.clearScope = clearScope; exports.scope = exports.path = void 0; let path = new WeakMap(); exports.path = path; let scope = new WeakMap(); exports.scope = scope; function clear() { clearPath(); clearScope(); } function clearPath() { exports.path = path = new WeakMap(); } function clearScope() { exports.scope = scope = new WeakMap(); } /***/ }), /* 190 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) { Object.defineProperty(exports, "__esModule", { value: true }); exports.codeFrameColumns = codeFrameColumns; exports.default = _default; function _highlight() { const data = _interopRequireWildcard(__webpack_require__(889)); _highlight = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } let deprecationWarningShown = false; function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold }; } const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; function getMarkerLines(loc, source, opts) { const startLoc = Object.assign({ column: 0, line: -1 }, loc.start); const endLoc = Object.assign({}, startLoc, loc.end); const { linesAbove = 2, linesBelow = 3 } = opts || {}; const startLine = startLoc.line; const startColumn = startLoc.column; const endLine = endLoc.line; const endColumn = endLoc.column; let start = Math.max(startLine - (linesAbove + 1), 0); let end = Math.min(source.length, endLine + linesBelow); if (startLine === -1) { start = 0; } if (endLine === -1) { end = source.length; } const lineDiff = endLine - startLine; const markerLines = {}; if (lineDiff) { for (let i = 0; i <= lineDiff; i++) { const lineNumber = i + startLine; if (!startColumn) { markerLines[lineNumber] = true; } else if (i === 0) { const sourceLength = source[lineNumber - 1].length; markerLines[lineNumber] = [startColumn, sourceLength - startColumn]; } else if (i === lineDiff) { markerLines[lineNumber] = [0, endColumn]; } else { const sourceLength = source[lineNumber - i].length; markerLines[lineNumber] = [0, sourceLength]; } } } else { if (startColumn === endColumn) { if (startColumn) { markerLines[startLine] = [startColumn, 0]; } else { markerLines[startLine] = true; } } else { markerLines[startLine] = [startColumn, endColumn - startColumn]; } } return { start, end, markerLines }; } function codeFrameColumns(rawLines, loc, opts = {}) { const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts); const chalk = (0, _highlight().getChalk)(opts); const defs = getDefs(chalk); const maybeHighlight = (chalkFn, string) => { return highlighted ? chalkFn(string) : string; }; if (highlighted) rawLines = (0, _highlight().default)(rawLines, opts); const lines = rawLines.split(NEWLINE); const { start, end, markerLines } = getMarkerLines(loc, lines, opts); const hasColumns = loc.start && typeof loc.start.column === "number"; const numberMaxWidth = String(end).length; let frame = lines.slice(start, end).map((line, index) => { const number = start + 1 + index; const paddedNumber = ` ${number}`.slice(-numberMaxWidth); const gutter = ` ${paddedNumber} | `; const hasMarker = markerLines[number]; const lastMarkerLine = !markerLines[number + 1]; if (hasMarker) { let markerLine = ""; if (Array.isArray(hasMarker)) { const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); const numberOfMarkers = hasMarker[1] || 1; markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); if (lastMarkerLine && opts.message) { markerLine += " " + maybeHighlight(defs.message, opts.message); } } return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); } else { return ` ${maybeHighlight(defs.gutter, gutter)}${line}`; } }).join("\n"); if (opts.message && !hasColumns) { frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; } if (highlighted) { return chalk.reset(frame); } else { return frame; } } function _default(rawLines, lineNumber, colNumber, opts = {}) { if (!deprecationWarningShown) { deprecationWarningShown = true; const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; if (process.emitWarning) { process.emitWarning(message, "DeprecationWarning"); } else { const deprecationError = new Error(message); deprecationError.name = "DeprecationWarning"; console.warn(new Error(message)); } } colNumber = Math.max(colNumber, 0); const location = { start: { column: colNumber, line: lineNumber } }; return codeFrameColumns(rawLines, location, opts); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }), /* 191 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.program = exports.expression = exports.statements = exports.statement = exports.smart = void 0; var formatters = _interopRequireWildcard(__webpack_require__(901)); var _builder = _interopRequireDefault(__webpack_require__(902)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const smart = (0, _builder.default)(formatters.smart); exports.smart = smart; const statement = (0, _builder.default)(formatters.statement); exports.statement = statement; const statements = (0, _builder.default)(formatters.statements); exports.statements = statements; const expression = (0, _builder.default)(formatters.expression); exports.expression = expression; const program = (0, _builder.default)(formatters.program); exports.program = program; var _default = Object.assign(smart.bind(undefined), { smart, statement, statements, expression, program, ast: smart.ast }); exports.default = _default; /***/ }), /* 192 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createItemFromDescriptor = createItemFromDescriptor; exports.createConfigItem = createConfigItem; exports.getItemDescriptor = getItemDescriptor; function _path() { const data = _interopRequireDefault(__webpack_require__(31)); _path = function () { return data; }; return data; } var _configDescriptors = __webpack_require__(405); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createItemFromDescriptor(desc) { return new ConfigItem(desc); } function createConfigItem(value, { dirname = ".", type } = {}) { const descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), { type, alias: "programmatic item" }); return createItemFromDescriptor(descriptor); } function getItemDescriptor(item) { if (item instanceof ConfigItem) { return item._descriptor; } return undefined; } class ConfigItem { constructor(descriptor) { this._descriptor = descriptor; Object.defineProperty(this, "_descriptor", { enumerable: false }); if (this._descriptor.options === false) { throw new Error("Assertion failure - unexpected false options"); } this.value = this._descriptor.value; this.options = this._descriptor.options; this.dirname = this._descriptor.dirname; this.name = this._descriptor.name; this.file = this._descriptor.file ? { request: this._descriptor.file.request, resolved: this._descriptor.file.resolved } : undefined; Object.freeze(this); } } Object.freeze(ConfigItem.prototype); /***/ }), /* 193 */ /***/ (function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(136); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }), /* 194 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; const NotImplementedError = Error("NotImplementedError"); class Collapser { isInitTypeValid() { throw NotImplementedError; } isExpressionTypeValid() { throw NotImplementedError; } getExpressionChecker() { throw NotImplementedError; } extractAssignment() { throw NotImplementedError; } addSuccessfully() { throw NotImplementedError; } isSizeSmaller() { return true; } } module.exports = Collapser; /***/ }), /* 195 */ /***/ (function(module, exports, __webpack_require__) { // This is (almost) directly from Node.js utils // https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js var getName = __webpack_require__(438); var getProperties = __webpack_require__(439); var getEnumerableProperties = __webpack_require__(1068); var config = __webpack_require__(96); module.exports = inspect; /** * ### .inspect(obj, [showHidden], [depth], [colors]) * * Echoes the value of a value. Tries to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Boolean} showHidden Flag that shows hidden (not enumerable) * properties of objects. Default is false. * @param {Number} depth Depth in which to descend in object. Default is 2. * @param {Boolean} colors Flag to turn on ANSI escape codes to color the * output. Default is false (no coloring). * @namespace Utils * @name inspect */ function inspect(obj, showHidden, depth, colors) { var ctx = { showHidden: showHidden, seen: [], stylize: function (str) { return str; } }; return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); } // Returns true if object is a DOM element. var isDOMElement = function (object) { if (typeof HTMLElement === 'object') { return object instanceof HTMLElement; } else { return object && typeof object === 'object' && 'nodeType' in object && object.nodeType === 1 && typeof object.nodeName === 'string'; } }; function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (value && typeof value.inspect === 'function' && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (typeof ret !== 'string') { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // If this is a DOM element, try to get the outer HTML. if (isDOMElement(value)) { if ('outerHTML' in value) { return value.outerHTML; // This value does not have an outerHTML attribute, // it could still be an XML element } else { // Attempt to serialize it try { if (document.xmlVersion) { var xmlSerializer = new XMLSerializer(); return xmlSerializer.serializeToString(value); } else { // Firefox 11- do not support outerHTML // It does, however, support innerHTML // Use the following to render the element var ns = "http://www.w3.org/1999/xhtml"; var container = document.createElementNS(ns, '_'); container.appendChild(value.cloneNode(false)); var html = container.innerHTML .replace('><', '>' + value.innerHTML + '<'); container.innerHTML = ''; return html; } } catch (err) { // This could be a non-native DOM implementation, // continue with the normal flow: // printing the element as if it is an object. } } } // Look up the keys of the object. var visibleKeys = getEnumerableProperties(value); var keys = ctx.showHidden ? getProperties(value) : visibleKeys; var name, nameSuffix; // Some type of object without properties can be shortcutted. // In IE, errors have a single `stack` property, or if they are vanilla `Error`, // a `stack` plus `description` property; ignore those for consistency. if (keys.length === 0 || (isError(value) && ( (keys.length === 1 && keys[0] === 'stack') || (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') ))) { if (typeof value === 'function') { name = getName(value); nameSuffix = name ? ': ' + name : ''; return ctx.stylize('[Function' + nameSuffix + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '' , array = false , typedArray = false , braces = ['{', '}']; if (isTypedArray(value)) { typedArray = true; braces = ['[', ']']; } // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (typeof value === 'function') { name = getName(value); nameSuffix = name ? ': ' + name : ''; base = ' [Function' + nameSuffix + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { return formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else if (typedArray) { return formatTypedArray(value); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { switch (typeof value) { case 'undefined': return ctx.stylize('undefined', 'undefined'); case 'string': var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); case 'number': if (value === 0 && (1/value) === -Infinity) { return ctx.stylize('-0', 'number'); } return ctx.stylize('' + value, 'number'); case 'boolean': return ctx.stylize('' + value, 'boolean'); case 'symbol': return ctx.stylize(value.toString(), 'symbol'); } // For some reason typeof null is "object", so special case here. if (value === null) { return ctx.stylize('null', 'null'); } } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (Object.prototype.hasOwnProperty.call(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatTypedArray(value) { var str = '[ '; for (var i = 0; i < value.length; ++i) { if (str.length >= config.truncateThreshold - 7) { str += '...'; break; } str += value[i] + ', '; } str += ' ]'; // Removing trailing `, ` if the array was not truncated if (str.indexOf(', ]') !== -1) { str = str.replace(', ]', ' ]'); } return str; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name; var propDescriptor = Object.getOwnPropertyDescriptor(value, key); var str; if (propDescriptor) { if (propDescriptor.get) { if (propDescriptor.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (propDescriptor.set) { str = ctx.stylize('[Setter]', 'special'); } } } if (visibleKeys.indexOf(key) < 0) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(value[key]) < 0) { if (recurseTimes === null) { str = formatValue(ctx, value[key], null); } else { str = formatValue(ctx, value[key], recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (typeof name === 'undefined') { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } function isTypedArray(ar) { // Unfortunately there's no way to check if an object is a TypedArray // We have to check if it's one of these types return (typeof ar === 'object' && /\w+Array]$/.test(objectToString(ar))); } function isArray(ar) { return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]'); } function isRegExp(re) { return typeof re === 'object' && objectToString(re) === '[object RegExp]'; } function isDate(d) { return typeof d === 'object' && objectToString(d) === '[object Date]'; } function isError(e) { return typeof e === 'object' && objectToString(e) === '[object Error]'; } function objectToString(o) { return Object.prototype.toString.call(o); } /***/ }), /* 196 */ /***/ (function(module, exports, __webpack_require__) { var config = __webpack_require__(96); /*! * Chai - isProxyEnabled helper * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ /** * ### .isProxyEnabled() * * Helper function to check if Chai's proxy protection feature is enabled. If * proxies are unsupported or disabled via the user's Chai config, then return * false. Otherwise, return true. * * @namespace Utils * @name isProxyEnabled */ module.exports = function isProxyEnabled() { return config.useProxy && typeof Proxy !== 'undefined' && typeof Reflect !== 'undefined'; }; /***/ }), /* 197 */ /***/ (function(module, exports, __webpack_require__) { var config = __webpack_require__(96); var fnLengthDesc = Object.getOwnPropertyDescriptor(function () {}, 'length'); /*! * Chai - addLengthGuard utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ /** * ### .addLengthGuard(fn, assertionName, isChainable) * * Define `length` as a getter on the given uninvoked method assertion. The * getter acts as a guard against chaining `length` directly off of an uninvoked * method assertion, which is a problem because it references `function`'s * built-in `length` property instead of Chai's `length` assertion. When the * getter catches the user making this mistake, it throws an error with a * helpful message. * * There are two ways in which this mistake can be made. The first way is by * chaining the `length` assertion directly off of an uninvoked chainable * method. In this case, Chai suggests that the user use `lengthOf` instead. The * second way is by chaining the `length` assertion directly off of an uninvoked * non-chainable method. Non-chainable methods must be invoked prior to * chaining. In this case, Chai suggests that the user consult the docs for the * given assertion. * * If the `length` property of functions is unconfigurable, then return `fn` * without modification. * * Note that in ES6, the function's `length` property is configurable, so once * support for legacy environments is dropped, Chai's `length` property can * replace the built-in function's `length` property, and this length guard will * no longer be necessary. In the mean time, maintaining consistency across all * environments is the priority. * * @param {Function} fn * @param {String} assertionName * @param {Boolean} isChainable * @namespace Utils * @name addLengthGuard */ module.exports = function addLengthGuard (fn, assertionName, isChainable) { if (!fnLengthDesc.configurable) return fn; Object.defineProperty(fn, 'length', { get: function () { if (isChainable) { throw Error('Invalid Chai property: ' + assertionName + '.length. Due' + ' to a compatibility issue, "length" cannot directly follow "' + assertionName + '". Use "' + assertionName + '.lengthOf" instead.'); } throw Error('Invalid Chai property: ' + assertionName + '.length. See' + ' docs for proper usage of "' + assertionName + '".'); } }); return fn; }; /***/ }), /* 198 */ /***/ (function(module, exports, __webpack_require__) { var config = __webpack_require__(96); var flag = __webpack_require__(58); var getProperties = __webpack_require__(439); var isProxyEnabled = __webpack_require__(196); /*! * Chai - proxify utility * Copyright(c) 2012-2014 Jake Luer * MIT Licensed */ /** * ### .proxify(object) * * Return a proxy of given object that throws an error when a non-existent * property is read. By default, the root cause is assumed to be a misspelled * property, and thus an attempt is made to offer a reasonable suggestion from * the list of existing properties. However, if a nonChainableMethodName is * provided, then the root cause is instead a failure to invoke a non-chainable * method prior to reading the non-existent property. * * If proxies are unsupported or disabled via the user's Chai config, then * return object without modification. * * @param {Object} obj * @param {String} nonChainableMethodName * @namespace Utils * @name proxify */ var builtins = ['__flags', '__methods', '_obj', 'assert']; module.exports = function proxify(obj, nonChainableMethodName) { if (!isProxyEnabled()) return obj; return new Proxy(obj, { get: function proxyGetter(target, property) { // This check is here because we should not throw errors on Symbol properties // such as `Symbol.toStringTag`. // The values for which an error should be thrown can be configured using // the `config.proxyExcludedKeys` setting. if (typeof property === 'string' && config.proxyExcludedKeys.indexOf(property) === -1 && !Reflect.has(target, property)) { // Special message for invalid property access of non-chainable methods. if (nonChainableMethodName) { throw Error('Invalid Chai property: ' + nonChainableMethodName + '.' + property + '. See docs for proper usage of "' + nonChainableMethodName + '".'); } var orderedProperties = getProperties(target).filter(function(property) { return !Object.prototype.hasOwnProperty(property) && builtins.indexOf(property) === -1; }).sort(function(a, b) { return stringDistance(property, a) - stringDistance(property, b); }); if (orderedProperties.length && stringDistance(orderedProperties[0], property) < 4) { // If the property is reasonably close to an existing Chai property, // suggest that property to the user. throw Error('Invalid Chai property: ' + property + '. Did you mean "' + orderedProperties[0] + '"?'); } else { throw Error('Invalid Chai property: ' + property); } } // Use this proxy getter as the starting point for removing implementation // frames from the stack trace of a failed assertion. For property // assertions, this prevents the proxy getter from showing up in the stack // trace since it's invoked before the property getter. For method and // chainable method assertions, this flag will end up getting changed to // the method wrapper, which is good since this frame will no longer be in // the stack once the method is invoked. Note that Chai builtin assertion // properties such as `__flags` are skipped since this is only meant to // capture the starting point of an assertion. This step is also skipped // if the `lockSsfi` flag is set, thus indicating that this assertion is // being called from within another assertion. In that case, the `ssfi` // flag is already set to the outer assertion's starting point. if (builtins.indexOf(property) === -1 && !flag(target, 'lockSsfi')) { flag(target, 'ssfi', proxyGetter); } return Reflect.get(target, property); } }); }; /** * # stringDistance(strA, strB) * Return the Levenshtein distance between two strings. * @param {string} strA * @param {string} strB * @return {number} the string distance between strA and strB * @api private */ function stringDistance(strA, strB, memo) { if (!memo) { // `memo` is a two-dimensional array containing a cache of distances // memo[i][j] is the distance between strA.slice(0, i) and // strB.slice(0, j). memo = []; for (var i = 0; i <= strA.length; i++) { memo[i] = []; } } if (!memo[strA.length] || !memo[strA.length][strB.length]) { if (strA.length === 0 || strB.length === 0) { memo[strA.length][strB.length] = Math.max(strA.length, strB.length); } else { memo[strA.length][strB.length] = Math.min( stringDistance(strA.slice(0, -1), strB, memo) + 1, stringDistance(strA, strB.slice(0, -1), memo) + 1, stringDistance(strA.slice(0, -1), strB.slice(0, -1), memo) + (strA.slice(-1) === strB.slice(-1) ? 0 : 1) ); } } return memo[strA.length][strB.length]; } /***/ }), /* 199 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {// Generated by CoffeeScript 2.2.3 (function() { // This file contains the common helper functions that we'd like to share among // the **Lexer**, **Rewriter**, and the **Nodes**. Merge objects, flatten // arrays, count characters, that sort of thing. // Peek at the beginning of a given string to see if it matches a sequence. var attachCommentsToNode, buildLocationData, buildLocationHash, extend, flatten, ref, repeat, syntaxErrorToString; exports.starts = function(string, literal, start) { return literal === string.substr(start, literal.length); }; // Peek at the end of a given string to see if it matches a sequence. exports.ends = function(string, literal, back) { var len; len = literal.length; return literal === string.substr(string.length - len - (back || 0), len); }; // Repeat a string `n` times. exports.repeat = repeat = function(str, n) { var res; // Use clever algorithm to have O(log(n)) string concatenation operations. res = ''; while (n > 0) { if (n & 1) { res += str; } n >>>= 1; str += str; } return res; }; // Trim out all falsy values from an array. exports.compact = function(array) { var i, item, len1, results; results = []; for (i = 0, len1 = array.length; i < len1; i++) { item = array[i]; if (item) { results.push(item); } } return results; }; // Count the number of occurrences of a string in a string. exports.count = function(string, substr) { var num, pos; num = pos = 0; if (!substr.length) { return 1 / 0; } while (pos = 1 + string.indexOf(substr, pos)) { num++; } return num; }; // Merge objects, returning a fresh copy with attributes from both sides. // Used every time `Base#compile` is called, to allow properties in the // options hash to propagate down the tree without polluting other branches. exports.merge = function(options, overrides) { return extend(extend({}, options), overrides); }; // Extend a source object with the properties of another object (shallow copy). extend = exports.extend = function(object, properties) { var key, val; for (key in properties) { val = properties[key]; object[key] = val; } return object; }; // Return a flattened version of an array. // Handy for getting a list of `children` from the nodes. exports.flatten = flatten = function(array) { var element, flattened, i, len1; flattened = []; for (i = 0, len1 = array.length; i < len1; i++) { element = array[i]; if ('[object Array]' === Object.prototype.toString.call(element)) { flattened = flattened.concat(flatten(element)); } else { flattened.push(element); } } return flattened; }; // Delete a key from an object, returning the value. Useful when a node is // looking for a particular method in an options hash. exports.del = function(obj, key) { var val; val = obj[key]; delete obj[key]; return val; }; // Typical Array::some exports.some = (ref = Array.prototype.some) != null ? ref : function(fn) { var e, i, len1, ref1; ref1 = this; for (i = 0, len1 = ref1.length; i < len1; i++) { e = ref1[i]; if (fn(e)) { return true; } } return false; }; // Helper function for extracting code from Literate CoffeeScript by stripping // out all non-code blocks, producing a string of CoffeeScript code that can // be compiled “normally.” exports.invertLiterate = function(code) { var blankLine, i, indented, insideComment, len1, line, listItemStart, out, ref1; out = []; blankLine = /^\s*$/; indented = /^[\t ]/; listItemStart = /^(?:\t?| {0,3})(?:[\*\-\+]|[0-9]{1,9}\.)[ \t]/; // Up to one tab, or up to three spaces, or neither; // followed by `*`, `-` or `+`; // or by an integer up to 9 digits long, followed by a period; // followed by a space or a tab. insideComment = false; ref1 = code.split('\n'); for (i = 0, len1 = ref1.length; i < len1; i++) { line = ref1[i]; if (blankLine.test(line)) { insideComment = false; out.push(line); } else if (insideComment || listItemStart.test(line)) { insideComment = true; out.push(`# ${line}`); } else if (!insideComment && indented.test(line)) { out.push(line); } else { insideComment = true; out.push(`# ${line}`); } } return out.join('\n'); }; // Merge two jison-style location data objects together. // If `last` is not provided, this will simply return `first`. buildLocationData = function(first, last) { if (!last) { return first; } else { return { first_line: first.first_line, first_column: first.first_column, last_line: last.last_line, last_column: last.last_column }; } }; buildLocationHash = function(loc) { return `${loc.first_line}x${loc.first_column}-${loc.last_line}x${loc.last_column}`; }; // This returns a function which takes an object as a parameter, and if that // object is an AST node, updates that object's locationData. // The object is returned either way. exports.addDataToNode = function(parserState, first, last) { return function(obj) { var i, len1, objHash, ref1, token, tokenHash; // Add location data if (((obj != null ? obj.updateLocationDataIfMissing : void 0) != null) && (first != null)) { obj.updateLocationDataIfMissing(buildLocationData(first, last)); } // Add comments data if (!parserState.tokenComments) { parserState.tokenComments = {}; ref1 = parserState.parser.tokens; for (i = 0, len1 = ref1.length; i < len1; i++) { token = ref1[i]; if (!token.comments) { continue; } tokenHash = buildLocationHash(token[2]); if (parserState.tokenComments[tokenHash] == null) { parserState.tokenComments[tokenHash] = token.comments; } else { parserState.tokenComments[tokenHash].push(...token.comments); } } } if (obj.locationData != null) { objHash = buildLocationHash(obj.locationData); if (parserState.tokenComments[objHash] != null) { attachCommentsToNode(parserState.tokenComments[objHash], obj); } } return obj; }; }; exports.attachCommentsToNode = attachCommentsToNode = function(comments, node) { if ((comments == null) || comments.length === 0) { return; } if (node.comments == null) { node.comments = []; } return node.comments.push(...comments); }; // Convert jison location data to a string. // `obj` can be a token, or a locationData. exports.locationDataToString = function(obj) { var locationData; if (("2" in obj) && ("first_line" in obj[2])) { locationData = obj[2]; } else if ("first_line" in obj) { locationData = obj; } if (locationData) { return `${locationData.first_line + 1}:${locationData.first_column + 1}-` + `${locationData.last_line + 1}:${locationData.last_column + 1}`; } else { return "No location data"; } }; // A `.coffee.md` compatible version of `basename`, that returns the file sans-extension. exports.baseFileName = function(file, stripExt = false, useWinPathSep = false) { var parts, pathSep; pathSep = useWinPathSep ? /\\|\// : /\//; parts = file.split(pathSep); file = parts[parts.length - 1]; if (!(stripExt && file.indexOf('.') >= 0)) { return file; } parts = file.split('.'); parts.pop(); if (parts[parts.length - 1] === 'coffee' && parts.length > 1) { parts.pop(); } return parts.join('.'); }; // Determine if a filename represents a CoffeeScript file. exports.isCoffee = function(file) { return /\.((lit)?coffee|coffee\.md)$/.test(file); }; // Determine if a filename represents a Literate CoffeeScript file. exports.isLiterate = function(file) { return /\.(litcoffee|coffee\.md)$/.test(file); }; // Throws a SyntaxError from a given location. // The error's `toString` will return an error message following the "standard" // format `::: ` plus the line with the error and a // marker showing where the error is. exports.throwSyntaxError = function(message, location) { var error; error = new SyntaxError(message); error.location = location; error.toString = syntaxErrorToString; // Instead of showing the compiler's stacktrace, show our custom error message // (this is useful when the error bubbles up in Node.js applications that // compile CoffeeScript for example). error.stack = error.toString(); throw error; }; // Update a compiler SyntaxError with source code information if it didn't have // it already. exports.updateSyntaxError = function(error, code, filename) { // Avoid screwing up the `stack` property of other errors (i.e. possible bugs). if (error.toString === syntaxErrorToString) { error.code || (error.code = code); error.filename || (error.filename = filename); error.stack = error.toString(); } return error; }; syntaxErrorToString = function() { var codeLine, colorize, colorsEnabled, end, filename, first_column, first_line, last_column, last_line, marker, ref1, ref2, ref3, start; if (!(this.code && this.location)) { return Error.prototype.toString.call(this); } ({first_line, first_column, last_line, last_column} = this.location); if (last_line == null) { last_line = first_line; } if (last_column == null) { last_column = first_column; } filename = this.filename || '[stdin]'; codeLine = this.code.split('\n')[first_line]; start = first_column; // Show only the first line on multi-line errors. end = first_line === last_line ? last_column + 1 : codeLine.length; marker = codeLine.slice(0, start).replace(/[^\s]/g, ' ') + repeat('^', end - start); // Check to see if we're running on a color-enabled TTY. if (typeof process !== "undefined" && process !== null) { colorsEnabled = ((ref1 = process.stdout) != null ? ref1.isTTY : void 0) && !((ref2 = process.env) != null ? ref2.NODE_DISABLE_COLORS : void 0); } if ((ref3 = this.colorful) != null ? ref3 : colorsEnabled) { colorize = function(str) { return `\x1B[1;31m${str}\x1B[0m`; }; codeLine = codeLine.slice(0, start) + colorize(codeLine.slice(start, end)) + codeLine.slice(end); marker = colorize(marker); } return `${filename}:${first_line + 1}:${first_column + 1}: error: ${this.message}\n${codeLine}\n${marker}`; }; exports.nameWhitespaceCharacter = function(string) { switch (string) { case ' ': return 'space'; case '\n': return 'newline'; case '\r': return 'carriage return'; case '\t': return 'tab'; default: return string; } }; }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }), /* 200 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** * @license * Lodash * Copyright JS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.11'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** 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')(); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); return result; } if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * 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 && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array == null ? 0 : array.length, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : 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; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * 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.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Gets the value at `key`, unless `key` is "__proto__". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key == '__proto__') { return; } return object[key]; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '

' + func(text) + '

'; * }); * * p('fred, barney, & pebbles'); * // => '

fred, barney, & pebbles

' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement(''); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * 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; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * 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'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, & pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<%- value %>'); * compiled({ 'value': '