var OrbitDB = /******/ (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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // 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 = 198); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports) { "use strict"; "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { "use strict"; "use strict"; exports.__esModule = true; var _defineProperty = __webpack_require__(56); var _defineProperty2 = _interopRequireDefault(_defineProperty); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = 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; (0, _defineProperty2.default)(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /***/ }, /* 2 */ /***/ function(module, exports) { var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var store = __webpack_require__(45)('wks') , uid = __webpack_require__(35) , Symbol = __webpack_require__(4).Symbol , 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; /***/ }, /* 4 */ /***/ 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 : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 5 */ /***/ 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; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(107), __esModule: true }; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(19); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(18)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , core = __webpack_require__(2) , ctx = __webpack_require__(23) , hide = __webpack_require__(12) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)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; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var anObject = __webpack_require__(7) , IE8_DOM_DEFINE = __webpack_require__(62) , toPrimitive = __webpack_require__(47) , dP = Object.defineProperty; exports.f = __webpack_require__(8) ? 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; }; /***/ }, /* 11 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(10) , createDesc = __webpack_require__(32); module.exports = __webpack_require__(8) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(63) , defined = __webpack_require__(38); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(112), __esModule: true }; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(111), __esModule: true }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { "use strict"; "use strict"; exports.__esModule = true; var _setPrototypeOf = __webpack_require__(101); var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); var _create = __webpack_require__(99); var _create2 = _interopRequireDefault(_create); var _typeof2 = __webpack_require__(59); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); } subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { "use strict"; "use strict"; exports.__esModule = true; var _typeof2 = __webpack_require__(59); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; }; /***/ }, /* 18 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 19 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(69) , enumBugKeys = __webpack_require__(40); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; /***/ }, /* 21 */ /***/ 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 */ 'use strict' var base64 = __webpack_require__(104) var ieee754 = __webpack_require__(155) var isArray = __webpack_require__(158) 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__(5))) /***/ }, /* 22 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(37); 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); }; }; /***/ }, /* 24 */ /***/ function(module, exports) { module.exports = {}; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { exports.nextTick = function nextTick(fn) { setTimeout(fn, 0); }; exports.platform = exports.arch = exports.execPath = exports.title = 'browser'; exports.pid = 1; exports.browser = true; exports.env = {}; exports.argv = []; exports.binding = function (name) { throw new Error('No such module. (Possibly not yet loaded)') }; (function () { var cwd = '/'; var path; exports.cwd = function () { return cwd }; exports.chdir = function (dir) { if (!path) path = __webpack_require__(166); cwd = path.resolve(dir, cwd); }; })(); exports.exit = exports.kill = exports.umask = exports.dlopen = exports.uptime = exports.memoryUsage = exports.uvCounters = function() {}; exports.features = {}; /***/ }, /* 26 */ /***/ function(module, exports) { "use strict"; 'use strict' module.exports = function drain (op, done) { var read, abort function sink (_read) { read = _read if(abort) return sink.abort() //this function is much simpler to write if you //just use recursion, but by using a while loop //we do not blow the stack if the stream happens to be sync. ;(function next() { var loop = true, cbed = false while(loop) { cbed = false read(null, function (end, data) { cbed = true if(end = end || abort) { loop = false if(done) done(end === true ? null : end) else if(end && end !== true) throw end } else if(op && false === op(data) || abort) { loop = false read(abort || true, done || function () {}) } else if(!loop){ next() } }) if(!cbed) { loop = false return } } })() } sink.abort = function (err, cb) { if('function' == typeof err) cb = err, err = true abort = err || true if(read) return read(abort, cb || function () {}) } return sink } /***/ }, /* 27 */ /***/ function(module, exports) { module.exports = function prop (key) { return key && ( 'string' == typeof key ? function (data) { return data[key] } : 'object' === typeof key && 'function' === typeof key.exec //regexp ? function (data) { var v = key.exec(data); return v && v[0] } : key ) } /***/ }, /* 28 */ /***/ 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; } /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _promise = __webpack_require__(57); var _promise2 = _interopRequireDefault(_promise); var _assign = __webpack_require__(6); var _assign2 = _interopRequireDefault(_assign); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EventEmitter = __webpack_require__(28).EventEmitter; var Log = __webpack_require__(91); var Index = __webpack_require__(98); var DefaultOptions = { Index: Index, maxHistory: 256 }; var Store = function () { function Store(ipfs, id, dbname) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; (0, _classCallCheck3.default)(this, Store); this.id = id; this.dbname = dbname; this.events = new EventEmitter(); var opts = (0, _assign2.default)({}, DefaultOptions); (0, _assign2.default)(opts, options); this.options = opts; this._ipfs = ipfs; this._index = new this.options.Index(this.id); this._oplog = new Log(this._ipfs, this.id, this.options); this._lastWrite = []; this._oplog.events.on('history', this._onLoadHistory.bind(this)); this._oplog.events.on('progress', this._onLoadProgress.bind(this)); } (0, _createClass3.default)(Store, [{ key: '_onLoadHistory', value: function _onLoadHistory(amount) { this.events.emit('load.start', this.dbname, amount); } }, { key: '_onLoadProgress', value: function _onLoadProgress(amount) { this.events.emit('load.progress', this.dbname, amount); } }, { key: 'loadHistory', value: function loadHistory(hash) { var _this = this; if (this._lastWrite.includes(hash)) return _promise2.default.resolve([]); if (hash) this._lastWrite.push(hash); if (hash && this.options.maxHistory > 0) { this.events.emit('load', this.dbname, hash); return Log.fromIpfsHash(this._ipfs, hash, this.options).then(function (log) { // this._oplog.events.on('history', this._onLoadHistory.bind(this)) // this._oplog.events.on('progress', this._onLoadProgress.bind(this)) return _this._oplog.join(log); }).then(function (merged) { // this._oplog.events.removeListener('history', this._onLoadHistory) // this._oplog.events.removeListener('progress', this._onLoadProgress) _this._index.updateIndex(_this._oplog, merged); _this.events.emit('history', _this.dbname, merged); _this.events.emit('load.end', _this.dbname, merged); }).then(function () { return _this.events.emit('ready', _this.dbname); }).then(function () { return _this; }); } else { this.events.emit('ready', this.dbname); return _promise2.default.resolve(this); } } }, { key: 'sync', value: function sync(hash) { var _this2 = this; if (!hash || this._lastWrite.includes(hash)) return _promise2.default.resolve([]); var newItems = []; if (hash) this._lastWrite.push(hash); this.events.emit('sync', this.dbname); var startTime = new Date().getTime(); return Log.fromIpfsHash(this._ipfs, hash, this.options).then(function (log) { // this._oplog.events.on('history', this._onLoadHistory.bind(this)) // this._oplog.events.on('progress', this._onLoadProgress.bind(this)) return _this2._oplog.join(log); }).then(function (merged) { // this._oplog.events.removeListener('history', this._onLoadHistory) // this._oplog.events.removeListener('progress', this._onLoadProgress) newItems = merged; _this2._index.updateIndex(_this2._oplog, newItems); _this2.events.emit('load.end', _this2.dbname, newItems); }) // .then((log) => this._oplog.join(log)) // .then((merged) => newItems = merged) // .then(() => this._index.updateIndex(this._oplog, newItems)) .then(function () { _this2.events.emit('history', _this2.dbname, newItems); // newItems.reverse() // .forEach((e) => this.events.emit('data', this.dbname, e)) }).then(function () { return newItems; }); } }, { key: 'close', value: function close() { this.delete(); this.events.emit('close', this.dbname); } // TODO: should make private? }, { key: 'delete', value: function _delete() { this._index = new this.options.Index(this.id); this._oplog = new Log(this._ipfs, this.id, this.options); } }, { key: '_addOperation', value: function _addOperation(data) { var _this3 = this; var result = void 0, logHash = void 0; if (this._oplog) { return this._oplog.add(data).then(function (res) { return result = res; }).then(function () { return Log.getIpfsHash(_this3._ipfs, _this3._oplog); }).then(function (hash) { return logHash = hash; }).then(function () { return _this3._lastWrite.push(logHash); }).then(function () { return _this3._index.updateIndex(_this3._oplog, [result]); }).then(function () { return _this3.events.emit('write', _this3.dbname, logHash); }).then(function () { return _this3.events.emit('data', _this3.dbname, result); }).then(function () { return result.hash; }); } } }]); return Store; }(); module.exports = Store; /***/ }, /* 30 */ /***/ function(module, exports) { module.exports = true; /***/ }, /* 31 */ /***/ function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }, /* 32 */ /***/ function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var def = __webpack_require__(10).f , has = __webpack_require__(11) , TAG = __webpack_require__(3)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(38); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 35 */ /***/ function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(106), __esModule: true }; /***/ }, /* 37 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 38 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(19) , document = __webpack_require__(4).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }, /* 40 */ /***/ function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(7) , dPs = __webpack_require__(133) , enumBugKeys = __webpack_require__(40) , IE_PROTO = __webpack_require__(44)('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(39)('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; __webpack_require__(61).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }, /* 42 */ /***/ function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(9) , core = __webpack_require__(2) , fails = __webpack_require__(18); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var shared = __webpack_require__(45)('keys') , uid = __webpack_require__(35); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }, /* 46 */ /***/ function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(19); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , core = __webpack_require__(2) , LIBRARY = __webpack_require__(30) , wksExt = __webpack_require__(49) , defineProperty = __webpack_require__(10).f; module.exports = function(name){ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); }; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { exports.f = __webpack_require__(3); /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var drain = __webpack_require__(26) module.exports = function reduce (reducer, acc, cb ) { if(!cb) cb = acc, acc = null var sink = drain(function (data) { acc = reducer(acc, data) }, function (err) { cb(err, acc) }) if (arguments.length === 2) return function (source) { source(null, function (end, data) { //if ended immediately, and no initial... if(end) return cb(end === true ? null : end) acc = data; sink(source) }) } else return sink } /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var abortCb = __webpack_require__(80) module.exports = function values (array, onAbort) { if(!array) return function (abort, cb) { if(abort) return abortCb(cb, abort, onAbort) return cb(true) } if(!Array.isArray(array)) array = Object.keys(array).map(function (k) { return array[k] }) var i = 0 return function (abort, cb) { if(abort) return abortCb(cb, abort, onAbort) if(i >= array.length) cb(true) else cb(null, array[i++]) } } /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var tester = __webpack_require__(81) module.exports = function filter (test) { //regexp test = tester(test) return function (read) { return function next (end, cb) { var sync, loop = true while(loop) { loop = false sync = true read(end, function (end, data) { if(!end && !test(data)) return sync ? loop = true : next(end, cb) cb(end, data) }) sync = false } } } } /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var apply = Function.prototype.apply; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { if (timeout) { timeout.close(); } }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // setimmediate attaches itself to the global object __webpack_require__(192); exports.setImmediate = setImmediate; exports.clearImmediate = clearImmediate; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _defineProperty2 = __webpack_require__(103); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _iterator2 = __webpack_require__(58); var _iterator3 = _interopRequireDefault(_iterator2); var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _assign = __webpack_require__(6); var _assign2 = _interopRequireDefault(_assign); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(17); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(16); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var slice = __webpack_require__(163); var take = __webpack_require__(76); var findIndex = __webpack_require__(161); var Store = __webpack_require__(29); var EventIndex = __webpack_require__(55); var EventStore = function (_Store) { (0, _inherits3.default)(EventStore, _Store); function EventStore(ipfs, id, dbname) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; (0, _classCallCheck3.default)(this, EventStore); if (options.Index === undefined) (0, _assign2.default)(options, { Index: EventIndex }); return (0, _possibleConstructorReturn3.default)(this, (EventStore.__proto__ || (0, _getPrototypeOf2.default)(EventStore)).call(this, ipfs, id, dbname, options)); } (0, _createClass3.default)(EventStore, [{ key: 'add', value: function add(data) { return this._addOperation({ op: 'ADD', key: null, value: data, meta: { ts: new Date().getTime() } }); } }, { key: 'get', value: function get(hash) { return this.iterator({ gte: hash, limit: 1 }).collect()[0]; } }, { key: 'iterator', value: function iterator(options) { var _iterator; var messages = this._query(options); var currentIndex = 0; var iterator = (_iterator = {}, (0, _defineProperty3.default)(_iterator, _iterator3.default, function () { return this; }), (0, _defineProperty3.default)(_iterator, 'next', function next() { var item = { value: null, done: true }; if (currentIndex < messages.length) { item = { value: messages[currentIndex], done: false }; currentIndex++; } return item; }), (0, _defineProperty3.default)(_iterator, 'collect', function collect() { return messages; }), _iterator); return iterator; } }, { key: '_query', value: function _query(opts) { if (!opts) opts = {}; var amount = opts.limit ? opts.limit > -1 ? opts.limit : this._index.get().length : 1; // Return 1 if no limit is provided var events = this._index.get(); var result = []; if (opts.gt || opts.gte) { // Greater than case result = this._read(events, opts.gt ? opts.gt : opts.gte, amount, opts.gte ? true : false); } else { // Lower than and lastN case, search latest first by reversing the sequence result = this._read(events.reverse(), opts.lt ? opts.lt : opts.lte, amount, opts.lte || !opts.lt).reverse(); } return result; } }, { key: '_read', value: function _read(ops, hash, amount, inclusive) { // Find the index of the gt/lt hash, or start from the beginning of the array if not found var startIndex = Math.max(findIndex(ops, function (e) { return e.hash === hash; }), 0); // If gte/lte is set, we include the given hash, if not, start from the next element startIndex += inclusive ? 0 : 1; // Slice the array to its requested size return take(ops.slice(startIndex), amount); } }]); return EventStore; }(Store); module.exports = EventStore; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _keys = __webpack_require__(14); var _keys2 = _interopRequireDefault(_keys); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EventIndex = function () { function EventIndex() { (0, _classCallCheck3.default)(this, EventIndex); this._index = {}; } (0, _createClass3.default)(EventIndex, [{ key: 'get', value: function get() { var _this = this; return (0, _keys2.default)(this._index).map(function (f) { return _this._index[f]; }); } }, { key: 'updateIndex', value: function updateIndex(oplog, added) { var _this2 = this; added.reduce(function (handled, item) { if (!handled.includes(item.hash)) { handled.push(item.hash); if (item.payload.op === 'ADD') _this2._index[item.hash] = item; } return handled; }, []); } }]); return EventIndex; }(); module.exports = EventIndex; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(109), __esModule: true }; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(114), __esModule: true }; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(116), __esModule: true }; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { "use strict"; "use strict"; exports.__esModule = true; var _iterator = __webpack_require__(58); var _iterator2 = _interopRequireDefault(_iterator); var _symbol = __webpack_require__(102); 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); }; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(22) , TAG = __webpack_require__(3)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(4).document && document.documentElement; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(8) && !__webpack_require__(18)(function(){ return Object.defineProperty(__webpack_require__(39)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(22); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var LIBRARY = __webpack_require__(30) , $export = __webpack_require__(9) , redefine = __webpack_require__(70) , hide = __webpack_require__(12) , has = __webpack_require__(11) , Iterators = __webpack_require__(24) , $iterCreate = __webpack_require__(126) , setToStringTag = __webpack_require__(33) , getPrototypeOf = __webpack_require__(68) , ITERATOR = __webpack_require__(3)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { var pIE = __webpack_require__(31) , createDesc = __webpack_require__(32) , toIObject = __webpack_require__(13) , toPrimitive = __webpack_require__(47) , has = __webpack_require__(11) , IE8_DOM_DEFINE = __webpack_require__(62) , gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(8) ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { return gOPD(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(13) , gOPN = __webpack_require__(67).f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN(it); } catch(e){ return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it){ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(69) , hiddenKeys = __webpack_require__(40).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(11) , toObject = __webpack_require__(34) , IE_PROTO = __webpack_require__(44)('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { var has = __webpack_require__(11) , toIObject = __webpack_require__(13) , arrayIndexOf = __webpack_require__(119)(false) , IE_PROTO = __webpack_require__(44)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(12); /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(23) , invoke = __webpack_require__(122) , html = __webpack_require__(61) , cel = __webpack_require__(39) , global = __webpack_require__(4) , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; var run = function(){ var id = +this; if(queue.hasOwnProperty(id)){ var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function(event){ run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!setTask || !clearTask){ setTask = function setImmediate(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id){ delete queue[id]; }; // Node.js 0.8- if(__webpack_require__(22)(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if(MessageChannel){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ defer = function(id){ global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if(ONREADYSTATECHANGE in cel('script')){ defer = function(id){ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(46) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }, /* 73 */ /***/ function(module, exports) { /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var $at = __webpack_require__(138)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(64)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(141); var global = __webpack_require__(4) , hide = __webpack_require__(12) , Iterators = __webpack_require__(24) , TO_STRING_TAG = __webpack_require__(3)('toStringTag'); for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype; if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }, /* 76 */ /***/ function(module, exports) { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** 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 octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * 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; } /** * 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); } /** * 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 && (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 && typeof value == 'object'; } /** * 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) && objectToString.call(value) == symbolTag); } /** * 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 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); } module.exports = take; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var sources = __webpack_require__(179) var sinks = __webpack_require__(173) var throughs = __webpack_require__(185) exports = module.exports = __webpack_require__(169) for(var k in sources) exports[k] = sources[k] for(var k in throughs) exports[k] = throughs[k] for(var k in sinks) exports[k] = sinks[k] /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var abortCb = __webpack_require__(80) module.exports = function once (value, onAbort) { return function (abort, cb) { if(abort) return abortCb(cb, abort, onAbort) if(value != null) { var _value = value; value = null cb(null, _value) } else cb(true) } } /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' function id (e) { return e } var prop = __webpack_require__(27) var filter = __webpack_require__(52) //drop items you have already seen. module.exports = function unique (field, invert) { field = prop(field) || id var seen = {} return filter(function (data) { var key = field(data) if(seen[key]) return !!invert //false, by default else seen[key] = true return !invert //true by default }) } /***/ }, /* 80 */ /***/ function(module, exports) { module.exports = function abortCb(cb, abort, onAbort) { cb(abort) onAbort && onAbort(abort === true ? null: abort) return } /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { var prop = __webpack_require__(27) function id (e) { return e } module.exports = function tester (test) { return ( 'object' === typeof test && 'function' === typeof test.test //regexp ? function (data) { return test.test(data) } : prop (test) || id ) } /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _assign = __webpack_require__(6); var _assign2 = _interopRequireDefault(_assign); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(17); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(16); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Store = __webpack_require__(29); var CounterIndex = __webpack_require__(93); var CounterStore = function (_Store) { (0, _inherits3.default)(CounterStore, _Store); function CounterStore(ipfs, id, dbname) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; (0, _classCallCheck3.default)(this, CounterStore); if (!options.Index) (0, _assign2.default)(options, { Index: CounterIndex }); return (0, _possibleConstructorReturn3.default)(this, (CounterStore.__proto__ || (0, _getPrototypeOf2.default)(CounterStore)).call(this, ipfs, id, dbname, options)); } (0, _createClass3.default)(CounterStore, [{ key: 'inc', value: function inc(amount) { var counter = this._index.get(); if (counter) { counter.increment(amount); return this._addOperation({ op: 'COUNTER', key: null, value: counter.payload, meta: { ts: new Date().getTime() } }); } } }, { key: 'value', get: function get() { return this._index.get().value; } }]); return CounterStore; }(Store); module.exports = CounterStore; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _keys = __webpack_require__(14); var _keys2 = _interopRequireDefault(_keys); var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _assign = __webpack_require__(6); var _assign2 = _interopRequireDefault(_assign); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(17); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(16); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Store = __webpack_require__(29); var DocumentIndex = __webpack_require__(94); var DocumentStore = function (_Store) { (0, _inherits3.default)(DocumentStore, _Store); function DocumentStore(ipfs, id, dbname, options) { (0, _classCallCheck3.default)(this, DocumentStore); if (!options) options = {}; if (!options.indexBy) (0, _assign2.default)(options, { indexBy: '_id' }); if (!options.Index) (0, _assign2.default)(options, { Index: DocumentIndex }); return (0, _possibleConstructorReturn3.default)(this, (DocumentStore.__proto__ || (0, _getPrototypeOf2.default)(DocumentStore)).call(this, ipfs, id, dbname, options)); } (0, _createClass3.default)(DocumentStore, [{ key: 'get', value: function get(key) { var _this2 = this; return (0, _keys2.default)(this._index._index).filter(function (e) { return e.indexOf(key) !== -1; }).map(function (e) { return _this2._index.get(e); }); } }, { key: 'query', value: function query(mapper) { var _this3 = this; return (0, _keys2.default)(this._index._index).map(function (e) { return _this3._index.get(e); }).filter(function (e) { return mapper(e); }); } }, { key: 'put', value: function put(doc) { return this._addOperation({ op: 'PUT', key: doc[this.options.indexBy], value: doc, meta: { ts: new Date().getTime() } }); } }, { key: 'del', value: function del(key) { return this._addOperation({ op: 'DEL', key: key, value: null, meta: { ts: new Date().getTime() } }); } }]); return DocumentStore; }(Store); module.exports = DocumentStore; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _assign = __webpack_require__(6); var _assign2 = _interopRequireDefault(_assign); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(17); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(16); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EventStore = __webpack_require__(54); var FeedIndex = __webpack_require__(95); var FeedStore = function (_EventStore) { (0, _inherits3.default)(FeedStore, _EventStore); function FeedStore(ipfs, id, dbname, options) { (0, _classCallCheck3.default)(this, FeedStore); if (!options) options = {}; if (!options.Index) (0, _assign2.default)(options, { Index: FeedIndex }); return (0, _possibleConstructorReturn3.default)(this, (FeedStore.__proto__ || (0, _getPrototypeOf2.default)(FeedStore)).call(this, ipfs, id, dbname, options)); } (0, _createClass3.default)(FeedStore, [{ key: 'remove', value: function remove(hash) { var operation = { op: 'DEL', key: null, value: hash, meta: { ts: new Date().getTime() } }; return this._addOperation(operation); } }]); return FeedStore; }(EventStore); module.exports = FeedStore; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _assign = __webpack_require__(6); var _assign2 = _interopRequireDefault(_assign); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(17); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(16); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Store = __webpack_require__(29); var KeyValueIndex = __webpack_require__(96); var KeyValueStore = function (_Store) { (0, _inherits3.default)(KeyValueStore, _Store); function KeyValueStore(ipfs, id, dbname, options) { (0, _classCallCheck3.default)(this, KeyValueStore); var opts = (0, _assign2.default)({}, { Index: KeyValueIndex }); (0, _assign2.default)(opts, options); return (0, _possibleConstructorReturn3.default)(this, (KeyValueStore.__proto__ || (0, _getPrototypeOf2.default)(KeyValueStore)).call(this, ipfs, id, dbname, opts)); } (0, _createClass3.default)(KeyValueStore, [{ key: 'get', value: function get(key) { return this._index.get(key); } }, { key: 'set', value: function set(key, data) { this.put(key, data); } }, { key: 'put', value: function put(key, data) { return this._addOperation({ op: 'PUT', key: key, value: data, meta: { ts: new Date().getTime() } }); } }, { key: 'del', value: function del(key) { return this._addOperation({ op: 'DEL', key: key, value: null, meta: { ts: new Date().getTime() } }); } }]); return KeyValueStore; }(Store); module.exports = KeyValueStore; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; module.exports = __webpack_require__(97); /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; var _stringify = __webpack_require__(36); var _stringify2 = _interopRequireDefault(_stringify); var _promise = __webpack_require__(57); var _promise2 = _interopRequireDefault(_promise); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var pull = __webpack_require__(77); var BlobStore = __webpack_require__(154); var Lock = __webpack_require__(159); var filePath = void 0; var store = void 0; var cache = {}; var lock = new Lock(); var Cache = function () { function Cache() { (0, _classCallCheck3.default)(this, Cache); } (0, _createClass3.default)(Cache, null, [{ key: 'set', value: function set(key, value) { return new _promise2.default(function (resolve, reject) { if (cache[key] === value) return resolve(); cache[key] = value; if (filePath && store) { lock(filePath, function (release) { // console.log("write cache:", filePath, JSON.stringify(cache, null, 2)) pull(pull.values([cache]), pull.map(function (v) { return (0, _stringify2.default)(v, null, 2); }), store.write(filePath, release(function (err) { if (err) { return reject(err); } resolve(); }))); }); } else { resolve(); } }); } }, { key: 'get', value: function get(key) { return cache[key]; } }, { key: 'loadCache', value: function loadCache(cachePath) { var cacheFile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'orbit-db.cache'; cache = {}; if (!cachePath) return _promise2.default.resolve(); // console.log("cache data:", cachePath) store = new BlobStore(cachePath); filePath = cacheFile; return new _promise2.default(function (resolve, reject) { // console.log("load cache:", cacheFile) store.exists(cacheFile, function (err, exists) { if (err || !exists) { return resolve(); } lock(cacheFile, function (release) { pull(store.read(cacheFile), pull.collect(release(function (err, res) { if (err) { return reject(err); } cache = JSON.parse(Buffer.concat(res).toString() || '{}'); resolve(); }))); }); }); }); } }, { key: 'reset', value: function reset() { cache = {}; store = null; } }]); return Cache; }(); module.exports = Cache; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21).Buffer)) /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _keys = __webpack_require__(14); var _keys2 = _interopRequireDefault(_keys); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var isEqual = __webpack_require__(89).isEqual; var GCounter = function () { function GCounter(id, payload) { (0, _classCallCheck3.default)(this, GCounter); this.id = id; this._counters = payload ? payload : {}; this._counters[this.id] = this._counters[this.id] ? this._counters[this.id] : 0; } (0, _createClass3.default)(GCounter, [{ key: 'increment', value: function increment(amount) { if (!amount) amount = 1; this._counters[this.id] = this._counters[this.id] + amount; } }, { key: 'compare', value: function compare(other) { if (other.id !== this.id) return false; return isEqual(other._counters, this._counters); } }, { key: 'merge', value: function merge(other) { var _this = this; (0, _keys2.default)(other._counters).forEach(function (f) { _this._counters[f] = Math.max(_this._counters[f] ? _this._counters[f] : 0, other._counters[f]); }); } }, { key: 'value', get: function get() { var _this2 = this; return (0, _keys2.default)(this._counters).map(function (f) { return _this2._counters[f]; }).reduce(function (previousValue, currentValue) { return previousValue + currentValue; }, 0); } }, { key: 'payload', get: function get() { return { id: this.id, counters: this._counters }; } }], [{ key: 'from', value: function from(payload) { return new GCounter(payload.id, payload.counters); } }]); return GCounter; }(); module.exports = GCounter; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _getOwnPropertyNames = __webpack_require__(100); var _getOwnPropertyNames2 = _interopRequireDefault(_getOwnPropertyNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.isEqual = function (a, b) { var propsA = (0, _getOwnPropertyNames2.default)(a); var propsB = (0, _getOwnPropertyNames2.default)(b); if (propsA.length !== propsB.length) return false; for (var i = 0; i < propsA.length; i++) { var prop = propsA[i]; if (a[prop] !== b[prop]) return false; } return true; }; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; var _stringify = __webpack_require__(36); var _stringify2 = _interopRequireDefault(_stringify); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = function () { function Entry() { (0, _classCallCheck3.default)(this, Entry); } (0, _createClass3.default)(Entry, null, [{ key: "create", // Returns a Promise // Example: // Entry.create(ipfs, "hello") // .then((entry) => console.log(entry)) // { hash: "Qm...Foo", payload: "hello", next: null } value: function create(ipfs, data) { var next = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; if (!ipfs) throw new Error("Entry requires ipfs instance"); // convert single objects to an array and entry objects to single hashes var nexts = next !== null && next instanceof Array ? next.map(function (e) { return e.hash ? e.hash : e; }) : [next !== null && next.hash ? next.hash : next]; var entry = { hash: null, // "Qm...Foo", we'll set the hash after ipfsfying the data structure, payload: data, // Can be any JSON.stringifyable data next: nexts // Array of IPFS hashes }; return Entry.toIpfsHash(ipfs, entry).then(function (hash) { entry.hash = hash; return entry; }); } // Returns a Promise // Example: // Entry.toIpfsHash(ipfs, entry) // .then((hash) => console.log(hash)) // "Qm...Foo" }, { key: "toIpfsHash", value: function toIpfsHash(ipfs, entry) { if (!ipfs) throw new Error("Entry requires ipfs instance"); var data = new Buffer((0, _stringify2.default)(entry)); return ipfs.object.put(data).then(function (res) { return res.toJSON().multihash; }); } // Returns a Promise // Example: // Entry.fromIpfsHash(ipfs, "Qm...Foo") // .then((entry) => console.log(entry)) // { hash: "Qm...Foo", payload: "hello", next: null } }, { key: "fromIpfsHash", value: function fromIpfsHash(ipfs, hash) { if (!ipfs) throw new Error("Entry requires ipfs instance"); if (!hash) throw new Error("Invalid hash: " + hash); return ipfs.object.get(hash, { enc: 'base58' }).then(function (obj) { var data = JSON.parse(obj.toJSON().data); var entry = { hash: hash, payload: data.payload, next: data.next }; return entry; }); } // Returns a boolean // Example: // const hasChild = Entry.hasChild(entry1, entry2) // true|false }, { key: "hasChild", value: function hasChild(entry1, entry2) { return entry1.next.includes(entry2.hash); } // Returns a boolean // Example: // const equal = Entry.compare(entry1, entry2) // true|false }, { key: "compare", value: function compare(a, b) { return a.hash === b.hash; } }]); return Entry; }(); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21).Buffer)) /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; var _stringify = __webpack_require__(36); var _stringify2 = _interopRequireDefault(_stringify); var _assign = __webpack_require__(6); var _assign2 = _interopRequireDefault(_assign); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EventEmitter = __webpack_require__(28).EventEmitter; var unionWith = __webpack_require__(164); var differenceWith = __webpack_require__(160); var flatten = __webpack_require__(162); var take = __webpack_require__(76); var Promise = __webpack_require__(105); var Entry = __webpack_require__(90); var MaxBatchSize = 10; // How many items to keep per local batch var MaxHistory = 256; // How many items to fetch on join var Log = function () { function Log(ipfs, id, opts) { (0, _classCallCheck3.default)(this, Log); this.id = id; this._ipfs = ipfs; this._items = opts && opts.items ? opts.items : []; this.options = { maxHistory: MaxHistory }; (0, _assign2.default)(this.options, opts); delete this.options.items; this._currentBatch = []; this._heads = []; this.events = new EventEmitter(); } (0, _createClass3.default)(Log, [{ key: 'add', value: function add(data) { var _this = this; if (this._currentBatch.length >= MaxBatchSize) this._commit(); return Entry.create(this._ipfs, data, this._heads).then(function (entry) { _this._heads = [entry.hash]; _this._currentBatch.push(entry); return entry; }); } }, { key: 'join', value: function join(other) { var _this2 = this; if (!other.items) throw new Error("The log to join must be an instance of Log"); var newItems = other.items.slice(-Math.max(this.options.maxHistory, 1)); // const newItems = take(other.items.reverse(), Math.max(this.options.maxHistory, 1)) var diff = differenceWith(newItems, this.items, Entry.compare); // TODO: need deterministic sorting for the union var final = unionWith(this._currentBatch, diff, Entry.compare); this._items = this._items.concat(final); this._currentBatch = []; var nexts = take(flatten(diff.map(function (f) { return f.next; })), this.options.maxHistory); // Fetch history if (final.length > 0) this.events.emit('history', this.options.maxHistory); return Promise.map(nexts, function (f) { var all = _this2.items.map(function (a) { return a.hash; }); return _this2._fetchRecursive(_this2._ipfs, f, all, _this2.options.maxHistory - nexts.length, 0).then(function (history) { history.forEach(function (b) { return _this2._insert(b); }); return history; }); }, { concurrency: 1 }).then(function (res) { _this2._heads = Log.findHeads(_this2); return flatten(res).concat(diff); }); } }, { key: '_insert', value: function _insert(entry) { var _this3 = this; var indices = entry.next.map(function (next) { return _this3._items.map(function (f) { return f.hash; }).indexOf(next); }); // Find the item's parent's indices var index = indices.length > 0 ? Math.max(Math.max.apply(null, indices) + 1, 0) : 0; // find the largest index (latest parent) this._items.splice(index, 0, entry); return entry; } }, { key: '_commit', value: function _commit() { this._items = this._items.concat(this._currentBatch); this._currentBatch = []; } }, { key: '_fetchRecursive', value: function _fetchRecursive(ipfs, hash, all, amount, depth) { var _this4 = this; var isReferenced = function isReferenced(list, item) { return list.reverse().find(function (f) { return f === item; }) !== undefined; }; var result = []; this.events.emit('progress', 1); // If the given hash is in the given log (all) or if we're at maximum depth, return if (isReferenced(all, hash) || depth >= amount) return Promise.resolve(result); // Create the entry and add it to the result return Entry.fromIpfsHash(ipfs, hash).then(function (entry) { result.push(entry); all.push(hash); depth++; return Promise.map(entry.next, function (f) { return _this4._fetchRecursive(ipfs, f, all, amount, depth); }, { concurrency: 1 }).then(function (res) { return flatten(res.concat(result)); }); }); } }, { key: 'items', get: function get() { return this._items.concat(this._currentBatch); } }, { key: 'snapshot', get: function get() { return { id: this.id, items: this._currentBatch.map(function (f) { return f.hash; }) }; } }], [{ key: 'getIpfsHash', value: function getIpfsHash(ipfs, log) { if (!ipfs) throw new Error("Ipfs instance not defined"); var data = new Buffer((0, _stringify2.default)(log.snapshot)); return ipfs.object.put(data).then(function (res) { return res.toJSON().multihash; }); } }, { key: 'fromIpfsHash', value: function fromIpfsHash(ipfs, hash, options) { if (!ipfs) throw new Error("Ipfs instance not defined"); if (!hash) throw new Error("Invalid hash: " + hash); if (!options) options = {}; var logData = void 0; return ipfs.object.get(hash, { enc: 'base58' }).then(function (res) { return logData = JSON.parse(res.toJSON().data); }).then(function (res) { if (!logData.items) throw new Error("Not a Log instance"); return Promise.all(logData.items.map(function (f) { return Entry.fromIpfsHash(ipfs, f); })); }).then(function (items) { return (0, _assign2.default)(options, { items: items }); }).then(function (items) { return new Log(ipfs, logData.id, options); }); } }, { key: 'findHeads', value: function findHeads(log) { return log.items.reverse().filter(function (f) { return !Log.isReferencedInChain(log, f); }).map(function (f) { return f.hash; }); } }, { key: 'isReferencedInChain', value: function isReferencedInChain(log, item) { return log.items.reverse().find(function (e) { return Entry.hasChild(e, item); }) !== undefined; } }, { key: 'batchSize', get: function get() { return MaxBatchSize; } }]); return Log; }(); module.exports = Log; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21).Buffer)) /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) {'use strict'; var _keys = __webpack_require__(14); var _keys2 = _interopRequireDefault(_keys); var _assign = __webpack_require__(6); var _assign2 = _interopRequireDefault(_assign); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var fs = __webpack_require__(197); var format = __webpack_require__(195).format; var EventEmitter = __webpack_require__(28).EventEmitter; var isNodejs = process.version ? true : false; var LogLevels = { 'DEBUG': 'DEBUG', 'INFO': 'INFO', 'WARN': 'WARN', 'ERROR': 'ERROR', 'NONE': 'NONE' }; // Global log level var GlobalLogLevel = LogLevels.DEBUG; // Global log file name var GlobalLogfile = null; var GlobalEvents = new EventEmitter(); // ANSI colors var Colors = { 'Black': 0, 'Red': 1, 'Green': 2, 'Yellow': 3, 'Blue': 4, 'Magenta': 5, 'Cyan': 6, 'Grey': 7, 'White': 9, 'Default': 9 }; // CSS colors if (!isNodejs) { Colors = { 'Black': 'Black', 'Red': 'IndianRed', 'Green': 'LimeGreen', 'Yellow': 'Orange', 'Blue': 'RoyalBlue', 'Magenta': 'Orchid', 'Cyan': 'SkyBlue', 'Grey': 'DimGrey', 'White': 'White', 'Default': 'Black' }; } var loglevelColors = [Colors.Cyan, Colors.Green, Colors.Yellow, Colors.Red, Colors.Default]; var defaultOptions = { useColors: true, color: Colors.Default, showTimestamp: true, showLevel: true, filename: GlobalLogfile, appendFile: true }; var Logger = function () { function Logger(category, options) { (0, _classCallCheck3.default)(this, Logger); this.category = category; var opts = {}; (0, _assign2.default)(opts, defaultOptions); (0, _assign2.default)(opts, options); this.options = opts; } (0, _createClass3.default)(Logger, [{ key: 'debug', value: function debug() { this._write(LogLevels.DEBUG, format.apply(null, arguments)); } }, { key: 'log', value: function log() { this.debug.apply(this, arguments); } }, { key: 'info', value: function info() { this._write(LogLevels.INFO, format.apply(null, arguments)); } }, { key: 'warn', value: function warn() { this._write(LogLevels.WARN, format.apply(null, arguments)); } }, { key: 'error', value: function error() { this._write(LogLevels.ERROR, format.apply(null, arguments)); } }, { key: '_write', value: function _write(level, text) { if (!this._shouldLog(level)) return; if ((this.options.filename || GlobalLogfile) && !this.fileWriter && isNodejs) this.fileWriter = fs.openSync(this.options.filename || GlobalLogfile, this.options.appendFile ? 'a+' : 'w+'); var format = this._format(level, text); var unformattedText = this._createLogMessage(level, text); var formattedText = this._createLogMessage(level, text, format.timestamp, format.level, format.category, format.text); if (this.fileWriter && isNodejs) fs.writeSync(this.fileWriter, unformattedText + '\n', null, 'utf-8'); if (isNodejs || !this.options.useColors) { console.log(formattedText); GlobalEvents.emit('data', this.category, level, text); } else { // TODO: clean this up if (level === LogLevels.ERROR) { if (this.options.showTimestamp && this.options.showLevel) { console.error(formattedText, format.timestamp, format.level, format.category, format.text); } else if (this.options.showTimestamp && !this.options.showLevel) { console.error(formattedText, format.timestamp, format.category, format.text); } else if (!this.options.showTimestamp && this.options.showLevel) { console.error(formattedText, format.level, format.category, format.text); } else { console.error(formattedText, format.category, format.text); } } else { if (this.options.showTimestamp && this.options.showLevel) { console.log(formattedText, format.timestamp, format.level, format.category, format.text); } else if (this.options.showTimestamp && !this.options.showLevel) { console.log(formattedText, format.timestamp, format.category, format.text); } else if (!this.options.showTimestamp && this.options.showLevel) { console.log(formattedText, format.level, format.category, format.text); } else { console.log(formattedText, format.category, format.text); } } } } }, { key: '_format', value: function _format(level, text) { var timestampFormat = ''; var levelFormat = ''; var categoryFormat = ''; var textFormat = ': '; if (this.options.useColors) { var levelColor = (0, _keys2.default)(LogLevels).map(function (f) { return LogLevels[f]; }).indexOf(level); var categoryColor = this.options.color; if (isNodejs) { if (this.options.showTimestamp) timestampFormat = '\x1B[3' + Colors.Grey + 'm'; if (this.options.showLevel) levelFormat = '\x1B[3' + loglevelColors[levelColor] + ';22m'; categoryFormat = '\x1B[3' + categoryColor + ';1m'; textFormat = '\x1B[0m: '; } else { if (this.options.showTimestamp) timestampFormat = 'color:' + Colors.Grey; if (this.options.showLevel) levelFormat = 'color:' + loglevelColors[levelColor]; categoryFormat = 'color:' + categoryColor + '; font-weight: bold'; } } return { timestamp: timestampFormat, level: levelFormat, category: categoryFormat, text: textFormat }; } }, { key: '_createLogMessage', value: function _createLogMessage(level, text, timestampFormat, levelFormat, categoryFormat, textFormat) { timestampFormat = timestampFormat || ''; levelFormat = levelFormat || ''; categoryFormat = categoryFormat || ''; textFormat = textFormat || ': '; if (!isNodejs && this.options.useColors) { if (this.options.showTimestamp) timestampFormat = '%c'; if (this.options.showLevel) levelFormat = '%c'; categoryFormat = '%c'; textFormat = ': %c'; } var result = ''; if (this.options.showTimestamp) result += '' + new Date().toISOString() + ' '; result = timestampFormat + result; if (this.options.showLevel) result += levelFormat + '[' + level + ']' + (level === LogLevels.INFO || level === LogLevels.WARN ? ' ' : '') + ' '; result += categoryFormat + this.category; result += textFormat + text; return result; } }, { key: '_shouldLog', value: function _shouldLog(level) { var envLogLevel = typeof process !== "undefined" && process.env !== undefined && process.env.LOG !== undefined ? process.env.LOG.toUpperCase() : null; envLogLevel = typeof window !== "undefined" && window.LOG ? window.LOG.toUpperCase() : envLogLevel; var logLevel = envLogLevel || GlobalLogLevel; var levels = (0, _keys2.default)(LogLevels).map(function (f) { return LogLevels[f]; }); var index = levels.indexOf(level); var levelIdx = levels.indexOf(logLevel); return index >= levelIdx; } }]); return Logger; }(); ; /* Public API */ module.exports = { Colors: Colors, LogLevels: LogLevels, setLogLevel: function setLogLevel(level) { GlobalLogLevel = level; }, setLogfile: function setLogfile(filename) { GlobalLogfile = filename; }, create: function create(category, options) { var logger = new Logger(category, options); return logger; }, forceBrowserMode: function forceBrowserMode(force) { return isNodejs = !force; }, // for testing, events: GlobalEvents }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25))) /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Counter = __webpack_require__(88); var CounterIndex = function () { function CounterIndex(id) { (0, _classCallCheck3.default)(this, CounterIndex); this._counter = new Counter(id); } (0, _createClass3.default)(CounterIndex, [{ key: 'get', value: function get() { return this._counter; } }, { key: 'updateIndex', value: function updateIndex(oplog, added) { var _this = this; if (this._counter) { added.filter(function (f) { return f && f.payload.op === 'COUNTER'; }).map(function (f) { return Counter.from(f.payload.value); }).forEach(function (f) { return _this._counter.merge(f); }); } } }]); return CounterIndex; }(); module.exports = CounterIndex; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DocumentIndex = function () { function DocumentIndex() { (0, _classCallCheck3.default)(this, DocumentIndex); this._index = {}; } (0, _createClass3.default)(DocumentIndex, [{ key: 'get', value: function get(key) { return this._index[key]; } }, { key: 'updateIndex', value: function updateIndex(oplog, added) { var _this = this; added.reverse().reduce(function (handled, item) { if (handled.indexOf(item.payload.key) === -1) { handled.push(item.payload.key); if (item.payload.op === 'PUT') { _this._index[item.payload.key] = item.payload.value; } else if (item.payload.op === 'DEL') { delete _this._index[item.payload.key]; } } return handled; }, []); } }]); return DocumentIndex; }(); module.exports = DocumentIndex; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _getPrototypeOf = __webpack_require__(15); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = __webpack_require__(17); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(16); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EventIndex = __webpack_require__(55); var FeedIndex = function (_EventIndex) { (0, _inherits3.default)(FeedIndex, _EventIndex); function FeedIndex() { (0, _classCallCheck3.default)(this, FeedIndex); return (0, _possibleConstructorReturn3.default)(this, (FeedIndex.__proto__ || (0, _getPrototypeOf2.default)(FeedIndex)).apply(this, arguments)); } (0, _createClass3.default)(FeedIndex, [{ key: 'updateIndex', value: function updateIndex(oplog, added) { var _this2 = this; added.reduce(function (handled, item) { if (!handled.includes(item.hash)) { handled.push(item.hash); if (item.payload.op === 'ADD') { _this2._index[item.hash] = item; } else if (item.payload.op === 'DEL') { delete _this2._index[item.payload.value]; } } return handled; }, []); } }]); return FeedIndex; }(EventIndex); module.exports = FeedIndex; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var KeyValueIndex = function () { function KeyValueIndex() { (0, _classCallCheck3.default)(this, KeyValueIndex); this._index = {}; } (0, _createClass3.default)(KeyValueIndex, [{ key: 'get', value: function get(key) { return this._index[key]; } }, { key: 'updateIndex', value: function updateIndex(oplog, added) { var _this = this; added.reverse().reduce(function (handled, item) { if (!handled.includes(item.payload.key)) { handled.push(item.payload.key); if (item.payload.op === 'PUT') { _this._index[item.payload.key] = item.payload.value; } else if (item.payload.op === 'DEL') { delete _this._index[item.payload.key]; } } return handled; }, []); } }]); return KeyValueIndex; }(); module.exports = KeyValueIndex; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; var _keys = __webpack_require__(14); var _keys2 = _interopRequireDefault(_keys); var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Logger = __webpack_require__(92); var logger = Logger.create("orbit-db.ipfs-pubsub"); Logger.setLogLevel('ERROR'); var IPFSPubsub = function () { function IPFSPubsub(ipfs) { (0, _classCallCheck3.default)(this, IPFSPubsub); this._ipfs = ipfs; this._subscriptions = {}; if (this._ipfs.pubsub === null) logger.error("The provided version of ipfs doesn't have pubsub support. Messages will not be exchanged."); } (0, _createClass3.default)(IPFSPubsub, [{ key: 'subscribe', value: function subscribe(hash, onMessageCallback) { if (!this._subscriptions[hash]) { this._subscriptions[hash] = { onMessage: onMessageCallback }; if (this._ipfs.pubsub) this._ipfs.pubsub.subscribe(hash, { discover: true }, this._handleMessage.bind(this)); } } }, { key: 'unsubscribe', value: function unsubscribe(hash) { if (this._subscriptions[hash]) { this._ipfs.pubsub.unsubscribe(hash, this._handleMessage); delete this._subscriptions[hash]; logger.debug('Unsubscribed from \'' + hash + '\''); } } }, { key: 'publish', value: function publish(hash, message) { if (this._subscriptions[hash] && this._ipfs.pubsub) this._ipfs.pubsub.publish(hash, new Buffer(message)); } }, { key: 'disconnect', value: function disconnect() { var _this = this; (0, _keys2.default)(this._subscriptions).forEach(function (e) { return _this.unsubscribe(e); }); } }, { key: '_handleMessage', value: function _handleMessage(message) { var hash = message.topicCIDs[0]; var data = message.data.toString(); var subscription = this._subscriptions[hash]; if (subscription && subscription.onMessage && data) subscription.onMessage(hash, data); } }]); return IPFSPubsub; }(); module.exports = IPFSPubsub; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21).Buffer)) /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; /* Index Index contains the state of a datastore, ie. what data we currently have. Index receives a call from a Store when the operations log for the Store was updated, ie. new operations were added. In updateIndex, the Index implements its CRDT logic: add, remove or update items in the data structure. Each new operation received from the operations log is applied in order onto the current state, ie. each new operation changes the data and the state changes. Implementing each CRDT as an Index, we can implement both operation-based and state-based CRDTs with the same higher level abstractions. To read the current state of the database, Index provides a single public function: `get()`. It is up to the Store to decide what kind of query capabilities it provides to the consumer. Usage: ```javascript const Index = new Index(userId) ``` */ var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Index = function () { /* @param id - unique identifier of this index, eg. a user id or a hash */ function Index(id) { (0, _classCallCheck3.default)(this, Index); this.id = id; this._index = []; } /* Returns the state of the datastore, ie. most up-to-date data @return - current state */ (0, _createClass3.default)(Index, [{ key: 'get', value: function get() { return this._index; } /* Applies operations to the Index and updates the state @param oplog - the source operations log that called updateIndex @param entries - operations that were added to the log */ }, { key: 'updateIndex', value: function updateIndex(oplog, entries) { this._index = oplog.ops; } }]); return Index; }(); module.exports = Index; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(108), __esModule: true }; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(110), __esModule: true }; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(113), __esModule: true }; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(115), __esModule: true }; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { "use strict"; "use strict"; exports.__esModule = true; var _defineProperty = __webpack_require__(56); var _defineProperty2 = _interopRequireDefault(_defineProperty); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (obj, key, value) { if (key in obj) { (0, _defineProperty2.default)(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) var PLUS_URL_SAFE = '-'.charCodeAt(0) var SLASH_URL_SAFE = '_'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+' if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }( false ? (this.base64js = {}) : exports)) /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global, setImmediate) {/* @preserve * The MIT License (MIT) * * Copyright (c) 2013-2015 Petka Antonov * * 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. * */ /** * bluebird build version 3.4.7 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ !function(e){if(true)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { var fn = queue.shift(); if (typeof fn !== "function") { fn._settlePromises(); continue; } var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } }; Async.prototype._drainQueues = function () { this._drainQueue(this._normalQueue); this._reset(); this._haveDrainedQueues = true; this._drainQueue(this._lateQueue); }; Async.prototype._queueTick = function () { if (!this._isTickUsed) { this._isTickUsed = true; this._schedule(this.drainQueues); } }; Async.prototype._reset = function () { this._isTickUsed = false; }; module.exports = Async; module.exports.firstLineError = firstLineError; },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { var calledBind = false; var rejectThis = function(_, e) { this._reject(e); }; var targetRejected = function(e, context) { context.promiseRejectionQueued = true; context.bindingPromise._then(rejectThis, rejectThis, null, this, e); }; var bindingResolved = function(thisArg, context) { if (((this._bitField & 50397184) === 0)) { this._resolveCallback(context.target); } }; var bindingRejected = function(e, context) { if (!context.promiseRejectionQueued) this._reject(e); }; Promise.prototype.bind = function (thisArg) { if (!calledBind) { calledBind = true; Promise.prototype._propagateFrom = debug.propagateFromFunction(); Promise.prototype._boundValue = debug.boundValueFunction(); } var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, promise: ret, target: target, bindingPromise: maybePromise }; target._then(INTERNAL, targetRejected, undefined, ret, context); maybePromise._then( bindingResolved, bindingRejected, undefined, ret, context); ret._setOnCancel(maybePromise); } else { ret._resolveCallback(target); } return ret; }; Promise.prototype._setBoundTo = function (obj) { if (obj !== undefined) { this._bitField = this._bitField | 2097152; this._boundTo = obj; } else { this._bitField = this._bitField & (~2097152); } }; Promise.prototype._isBound = function () { return (this._bitField & 2097152) === 2097152; }; Promise.bind = function (thisArg, value) { return Promise.resolve(value).bind(thisArg); }; }; },{}],4:[function(_dereq_,module,exports){ "use strict"; var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = _dereq_("./promise")(); bluebird.noConflict = noConflict; module.exports = bluebird; },{"./promise":22}],5:[function(_dereq_,module,exports){ "use strict"; var cr = Object.create; if (cr) { var callerCache = cr(null); var getterCache = cr(null); callerCache[" size"] = getterCache[" size"] = 0; } module.exports = function(Promise) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; var getMethodCaller; var getGetter; if (false) { var makeMethodCaller = function (methodName) { return new Function("ensureMethod", " \n\ return function(obj) { \n\ 'use strict' \n\ var len = this.length; \n\ ensureMethod(obj, 'methodName'); \n\ switch(len) { \n\ case 1: return obj.methodName(this[0]); \n\ case 2: return obj.methodName(this[0], this[1]); \n\ case 3: return obj.methodName(this[0], this[1], this[2]); \n\ case 0: return obj.methodName(); \n\ default: \n\ return obj.methodName.apply(obj, this); \n\ } \n\ }; \n\ ".replace(/methodName/g, methodName))(ensureMethod); }; var makeGetter = function (propertyName) { return new Function("obj", " \n\ 'use strict'; \n\ return obj.propertyName; \n\ ".replace("propertyName", propertyName)); }; var getCompiled = function(name, compiler, cache) { var ret = cache[name]; if (typeof ret !== "function") { if (!isIdentifier(name)) { return null; } ret = compiler(name); cache[name] = ret; cache[" size"]++; if (cache[" size"] > 512) { var keys = Object.keys(cache); for (var i = 0; i < 256; ++i) delete cache[keys[i]]; cache[" size"] = keys.length - 256; } } return ret; }; getMethodCaller = function(name) { return getCompiled(name, makeMethodCaller, callerCache); }; getGetter = function(name) { return getCompiled(name, makeGetter, getterCache); }; } function ensureMethod(obj, methodName) { var fn; if (obj != null) fn = obj[methodName]; if (typeof fn !== "function") { var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; throw new Promise.TypeError(message); } return fn; } function caller(obj) { var methodName = this.pop(); var fn = ensureMethod(obj, methodName); return fn.apply(obj, this); } Promise.prototype.call = function (methodName) { var args = [].slice.call(arguments, 1);; if (false) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); if (maybeCaller !== null) { return this._then( maybeCaller, undefined, undefined, args, undefined); } } } args.push(methodName); return this._then(caller, undefined, undefined, args, undefined); }; function namedGetter(obj) { return obj[this]; } function indexedGetter(obj) { var index = +this; if (index < 0) index = Math.max(0, index + obj.length); return obj[index]; } Promise.prototype.get = function (propertyName) { var isIndex = (typeof propertyName === "number"); var getter; if (!isIndex) { if (canEvaluate) { var maybeGetter = getGetter(propertyName); getter = maybeGetter !== null ? maybeGetter : namedGetter; } else { getter = namedGetter; } } else { getter = indexedGetter; } return this._then(getter, undefined, undefined, propertyName, undefined); }; }; },{"./util":36}],6:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; Promise.prototype["break"] = Promise.prototype.cancel = function() { if (!debug.cancellation()) return this._warn("cancellation is disabled"); var promise = this; var child = promise; while (promise._isCancellable()) { if (!promise._cancelBy(child)) { if (child._isFollowing()) { child._followee().cancel(); } else { child._cancelBranched(); } break; } var parent = promise._cancellationParent; if (parent == null || !parent._isCancellable()) { if (promise._isFollowing()) { promise._followee().cancel(); } else { promise._cancelBranched(); } break; } else { if (promise._isFollowing()) promise._followee().cancel(); promise._setWillBeCancelled(); child = promise; promise = parent; } } }; Promise.prototype._branchHasCancelled = function() { this._branchesRemainingToCancel--; }; Promise.prototype._enoughBranchesHaveCancelled = function() { return this._branchesRemainingToCancel === undefined || this._branchesRemainingToCancel <= 0; }; Promise.prototype._cancelBy = function(canceller) { if (canceller === this) { this._branchesRemainingToCancel = 0; this._invokeOnCancel(); return true; } else { this._branchHasCancelled(); if (this._enoughBranchesHaveCancelled()) { this._invokeOnCancel(); return true; } } return false; }; Promise.prototype._cancelBranched = function() { if (this._enoughBranchesHaveCancelled()) { this._cancel(); } }; Promise.prototype._cancel = function() { if (!this._isCancellable()) return; this._setCancelled(); async.invoke(this._cancelPromises, this, undefined); }; Promise.prototype._cancelPromises = function() { if (this._length() > 0) this._settlePromises(); }; Promise.prototype._unsetOnCancel = function() { this._onCancelField = undefined; }; Promise.prototype._isCancellable = function() { return this.isPending() && !this._isCancelled(); }; Promise.prototype.isCancellable = function() { return this.isPending() && !this.isCancelled(); }; Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { if (util.isArray(onCancelCallback)) { for (var i = 0; i < onCancelCallback.length; ++i) { this._doInvokeOnCancel(onCancelCallback[i], internalOnly); } } else if (onCancelCallback !== undefined) { if (typeof onCancelCallback === "function") { if (!internalOnly) { var e = tryCatch(onCancelCallback).call(this._boundValue()); if (e === errorObj) { this._attachExtraTrace(e.e); async.throwLater(e.e); } } } else { onCancelCallback._resultCancelled(this); } } }; Promise.prototype._invokeOnCancel = function() { var onCancelCallback = this._onCancel(); this._unsetOnCancel(); async.invoke(this._doInvokeOnCancel, this, onCancelCallback); }; Promise.prototype._invokeInternalOnCancel = function() { if (this._isCancellable()) { this._doInvokeOnCancel(this._onCancel(), true); this._unsetOnCancel(); } }; Promise.prototype._resultCancelled = function() { this.cancel(); }; }; },{"./util":36}],7:[function(_dereq_,module,exports){ "use strict"; module.exports = function(NEXT_FILTER) { var util = _dereq_("./util"); var getKeys = _dereq_("./es5").keys; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function catchFilter(instances, cb, promise) { return function(e) { var boundTo = promise._boundValue(); predicateLoop: for (var i = 0; i < instances.length; ++i) { var item = instances[i]; if (item === Error || (item != null && item.prototype instanceof Error)) { if (e instanceof item) { return tryCatch(cb).call(boundTo, e); } } else if (typeof item === "function") { var matchesPredicate = tryCatch(item).call(boundTo, e); if (matchesPredicate === errorObj) { return matchesPredicate; } else if (matchesPredicate) { return tryCatch(cb).call(boundTo, e); } } else if (util.isObject(e)) { var keys = getKeys(item); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; if (item[key] != e[key]) { continue predicateLoop; } } return tryCatch(cb).call(boundTo, e); } } return NEXT_FILTER; }; } return catchFilter; }; },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var longStackTraces = false; var contextStack = []; Promise.prototype._promiseCreated = function() {}; Promise.prototype._pushContext = function() {}; Promise.prototype._popContext = function() {return null;}; Promise._peekContext = Promise.prototype._peekContext = function() {}; function Context() { this._trace = new Context.CapturedTrace(peekContext()); } Context.prototype._pushContext = function () { if (this._trace !== undefined) { this._trace._promiseCreated = null; contextStack.push(this._trace); } }; Context.prototype._popContext = function () { if (this._trace !== undefined) { var trace = contextStack.pop(); var ret = trace._promiseCreated; trace._promiseCreated = null; return ret; } return null; }; function createContext() { if (longStackTraces) return new Context(); } function peekContext() { var lastIndex = contextStack.length - 1; if (lastIndex >= 0) { return contextStack[lastIndex]; } return undefined; } Context.CapturedTrace = null; Context.create = createContext; Context.deactivateLongStackTraces = function() {}; Context.activateLongStackTraces = function() { var Promise_pushContext = Promise.prototype._pushContext; var Promise_popContext = Promise.prototype._popContext; var Promise_PeekContext = Promise._peekContext; var Promise_peekContext = Promise.prototype._peekContext; var Promise_promiseCreated = Promise.prototype._promiseCreated; Context.deactivateLongStackTraces = function() { Promise.prototype._pushContext = Promise_pushContext; Promise.prototype._popContext = Promise_popContext; Promise._peekContext = Promise_PeekContext; Promise.prototype._peekContext = Promise_peekContext; Promise.prototype._promiseCreated = Promise_promiseCreated; longStackTraces = false; }; longStackTraces = true; Promise.prototype._pushContext = Context.prototype._pushContext; Promise.prototype._popContext = Context.prototype._popContext; Promise._peekContext = Promise.prototype._peekContext = peekContext; Promise.prototype._promiseCreated = function() { var ctx = this._peekContext(); if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; }; }; return Context; }; },{}],9:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, Context) { var getDomain = Promise._getDomain; var async = Promise._async; var Warning = _dereq_("./errors").Warning; var util = _dereq_("./util"); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; var stackFramePattern = null; var formatStack = null; var indentStackFrames = false; var printWarning; var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && (true || util.env("BLUEBIRD_DEBUG") || util.env("NODE_ENV") === "development")); var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && (debugging || util.env("BLUEBIRD_WARNINGS"))); var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); Promise.prototype.suppressUnhandledRejections = function() { var target = this._target(); target._bitField = ((target._bitField & (~1048576)) | 524288); }; Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 524288) !== 0) return; this._setRejectionIsUnhandled(); async.invokeLater(this._notifyUnhandledRejection, this, undefined); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); }; Promise.prototype._setReturnedNonUndefined = function() { this._bitField = this._bitField | 268435456; }; Promise.prototype._returnedNonUndefined = function() { return (this._bitField & 268435456) !== 0; }; Promise.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var reason = this._settledValue(); this._setUnhandledRejectionIsNotified(); fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); } }; Promise.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = this._bitField | 262144; }; Promise.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = this._bitField & (~262144); }; Promise.prototype._isUnhandledRejectionNotified = function () { return (this._bitField & 262144) > 0; }; Promise.prototype._setRejectionIsUnhandled = function () { this._bitField = this._bitField | 1048576; }; Promise.prototype._unsetRejectionIsUnhandled = function () { this._bitField = this._bitField & (~1048576); if (this._isUnhandledRejectionNotified()) { this._unsetUnhandledRejectionIsNotified(); this._notifyUnhandledRejectionIsHandled(); } }; Promise.prototype._isRejectionUnhandled = function () { return (this._bitField & 1048576) > 0; }; Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { return warn(message, shouldUseOwnTrace, promise || this); }; Promise.onPossiblyUnhandledRejection = function (fn) { var domain = getDomain(); possiblyUnhandledRejection = typeof fn === "function" ? (domain === null ? fn : util.domainBind(domain, fn)) : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { var domain = getDomain(); unhandledRejectionHandled = typeof fn === "function" ? (domain === null ? fn : util.domainBind(domain, fn)) : undefined; }; var disableLongStackTraces = function() {}; Promise.longStackTraces = function () { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (!config.longStackTraces && longStackTracesIsSupported()) { var Promise_captureStackTrace = Promise.prototype._captureStackTrace; var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; config.longStackTraces = true; disableLongStackTraces = function() { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } Promise.prototype._captureStackTrace = Promise_captureStackTrace; Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; Context.deactivateLongStackTraces(); async.enableTrampoline(); config.longStackTraces = false; }; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Context.activateLongStackTraces(); async.disableTrampolineIfNecessary(); } }; Promise.hasLongStackTraces = function () { return config.longStackTraces && longStackTracesIsSupported(); }; var fireDomEvent = (function() { try { if (typeof CustomEvent === "function") { var event = new CustomEvent("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { var domEvent = new CustomEvent(name.toLowerCase(), { detail: event, cancelable: true }); return !util.global.dispatchEvent(domEvent); }; } else if (typeof Event === "function") { var event = new Event("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { var domEvent = new Event(name.toLowerCase(), { cancelable: true }); domEvent.detail = event; return !util.global.dispatchEvent(domEvent); }; } else { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); util.global.dispatchEvent(event); return function(name, event) { var domEvent = document.createEvent("CustomEvent"); domEvent.initCustomEvent(name.toLowerCase(), false, true, event); return !util.global.dispatchEvent(domEvent); }; } } catch (e) {} return function() { return false; }; })(); var fireGlobalEvent = (function() { if (util.isNode) { return function() { return process.emit.apply(process, arguments); }; } else { if (!util.global) { return function() { return false; }; } return function(name) { var methodName = "on" + name.toLowerCase(); var method = util.global[methodName]; if (!method) return false; method.apply(util.global, [].slice.call(arguments, 1)); return true; }; } })(); function generatePromiseLifecycleEventObject(name, promise) { return {promise: promise}; } var eventToObjectGenerator = { promiseCreated: generatePromiseLifecycleEventObject, promiseFulfilled: generatePromiseLifecycleEventObject, promiseRejected: generatePromiseLifecycleEventObject, promiseResolved: generatePromiseLifecycleEventObject, promiseCancelled: generatePromiseLifecycleEventObject, promiseChained: function(name, promise, child) { return {promise: promise, child: child}; }, warning: function(name, warning) { return {warning: warning}; }, unhandledRejection: function (name, reason, promise) { return {reason: reason, promise: promise}; }, rejectionHandled: generatePromiseLifecycleEventObject }; var activeFireEvent = function (name) { var globalEventFired = false; try { globalEventFired = fireGlobalEvent.apply(null, arguments); } catch (e) { async.throwLater(e); globalEventFired = true; } var domEventFired = false; try { domEventFired = fireDomEvent(name, eventToObjectGenerator[name].apply(null, arguments)); } catch (e) { async.throwLater(e); domEventFired = true; } return domEventFired || globalEventFired; }; Promise.config = function(opts) { opts = Object(opts); if ("longStackTraces" in opts) { if (opts.longStackTraces) { Promise.longStackTraces(); } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { disableLongStackTraces(); } } if ("warnings" in opts) { var warningsOption = opts.warnings; config.warnings = !!warningsOption; wForgottenReturn = config.warnings; if (util.isObject(warningsOption)) { if ("wForgottenReturn" in warningsOption) { wForgottenReturn = !!warningsOption.wForgottenReturn; } } } if ("cancellation" in opts && opts.cancellation && !config.cancellation) { if (async.haveItemsQueued()) { throw new Error( "cannot enable cancellation after promises are in use"); } Promise.prototype._clearCancellationData = cancellationClearCancellationData; Promise.prototype._propagateFrom = cancellationPropagateFrom; Promise.prototype._onCancel = cancellationOnCancel; Promise.prototype._setOnCancel = cancellationSetOnCancel; Promise.prototype._attachCancellationCallback = cancellationAttachCancellationCallback; Promise.prototype._execute = cancellationExecute; propagateFromFunction = cancellationPropagateFrom; config.cancellation = true; } if ("monitoring" in opts) { if (opts.monitoring && !config.monitoring) { config.monitoring = true; Promise.prototype._fireEvent = activeFireEvent; } else if (!opts.monitoring && config.monitoring) { config.monitoring = false; Promise.prototype._fireEvent = defaultFireEvent; } } return Promise; }; function defaultFireEvent() { return false; } Promise.prototype._fireEvent = defaultFireEvent; Promise.prototype._execute = function(executor, resolve, reject) { try { executor(resolve, reject); } catch (e) { return e; } }; Promise.prototype._onCancel = function () {}; Promise.prototype._setOnCancel = function (handler) { ; }; Promise.prototype._attachCancellationCallback = function(onCancel) { ; }; Promise.prototype._captureStackTrace = function () {}; Promise.prototype._attachExtraTrace = function () {}; Promise.prototype._clearCancellationData = function() {}; Promise.prototype._propagateFrom = function (parent, flags) { ; ; }; function cancellationExecute(executor, resolve, reject) { var promise = this; try { executor(resolve, reject, function(onCancel) { if (typeof onCancel !== "function") { throw new TypeError("onCancel must be a function, got: " + util.toString(onCancel)); } promise._attachCancellationCallback(onCancel); }); } catch (e) { return e; } } function cancellationAttachCancellationCallback(onCancel) { if (!this._isCancellable()) return this; var previousOnCancel = this._onCancel(); if (previousOnCancel !== undefined) { if (util.isArray(previousOnCancel)) { previousOnCancel.push(onCancel); } else { this._setOnCancel([previousOnCancel, onCancel]); } } else { this._setOnCancel(onCancel); } } function cancellationOnCancel() { return this._onCancelField; } function cancellationSetOnCancel(onCancel) { this._onCancelField = onCancel; } function cancellationClearCancellationData() { this._cancellationParent = undefined; this._onCancelField = undefined; } function cancellationPropagateFrom(parent, flags) { if ((flags & 1) !== 0) { this._cancellationParent = parent; var branchesRemainingToCancel = parent._branchesRemainingToCancel; if (branchesRemainingToCancel === undefined) { branchesRemainingToCancel = 0; } parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; } if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } function bindingPropagateFrom(parent, flags) { if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } var propagateFromFunction = bindingPropagateFrom; function boundValueFunction() { var ret = this._boundTo; if (ret !== undefined) { if (ret instanceof Promise) { if (ret.isFulfilled()) { return ret.value(); } else { return undefined; } } } return ret; } function longStackTracesCaptureStackTrace() { this._trace = new CapturedTrace(this._peekContext()); } function longStackTracesAttachExtraTrace(error, ignoreSelf) { if (canAttachTrace(error)) { var trace = this._trace; if (trace !== undefined) { if (ignoreSelf) trace = trace._parent; } if (trace !== undefined) { trace.attachExtraTrace(error); } else if (!error.__stackCleaned__) { var parsed = parseStackAndMessage(error); util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); util.notEnumerableProp(error, "__stackCleaned__", true); } } } function checkForgottenReturns(returnValue, promiseCreated, name, promise, parent) { if (returnValue === undefined && promiseCreated !== null && wForgottenReturn) { if (parent !== undefined && parent._returnedNonUndefined()) return; if ((promise._bitField & 65535) === 0) return; if (name) name = name + " "; var handlerLine = ""; var creatorLine = ""; if (promiseCreated._trace) { var traceLines = promiseCreated._trace.stack.split("\n"); var stack = cleanStack(traceLines); for (var i = stack.length - 1; i >= 0; --i) { var line = stack[i]; if (!nodeFramePattern.test(line)) { var lineMatches = line.match(parseLinePattern); if (lineMatches) { handlerLine = "at " + lineMatches[1] + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; } break; } } if (stack.length > 0) { var firstUserLine = stack[0]; for (var i = 0; i < traceLines.length; ++i) { if (traceLines[i] === firstUserLine) { if (i > 0) { creatorLine = "\n" + traceLines[i - 1]; } break; } } } } var msg = "a promise was created in a " + name + "handler " + handlerLine + "but was not returned from it, " + "see http://goo.gl/rRqMUw" + creatorLine; promise._warn(msg, true, promiseCreated); } } function deprecated(name, replacement) { var message = name + " is deprecated and will be removed in a future version."; if (replacement) message += " Use " + replacement + " instead."; return warn(message); } function warn(message, shouldUseOwnTrace, promise) { if (!config.warnings) return; var warning = new Warning(message); var ctx; if (shouldUseOwnTrace) { promise._attachExtraTrace(warning); } else if (config.longStackTraces && (ctx = Promise._peekContext())) { ctx.attachExtraTrace(warning); } else { var parsed = parseStackAndMessage(warning); warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); } if (!activeFireEvent("warning", warning)) { formatAndLogError(warning, "", true); } } function reconstructStack(message, stacks) { for (var i = 0; i < stacks.length - 1; ++i) { stacks[i].push("From previous event:"); stacks[i] = stacks[i].join("\n"); } if (i < stacks.length) { stacks[i] = stacks[i].join("\n"); } return message + "\n" + stacks.join("\n"); } function removeDuplicateOrEmptyJumps(stacks) { for (var i = 0; i < stacks.length; ++i) { if (stacks[i].length === 0 || ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { stacks.splice(i, 1); i--; } } } function removeCommonRoots(stacks) { var current = stacks[0]; for (var i = 1; i < stacks.length; ++i) { var prev = stacks[i]; var currentLastIndex = current.length - 1; var currentLastLine = current[currentLastIndex]; var commonRootMeetPoint = -1; for (var j = prev.length - 1; j >= 0; --j) { if (prev[j] === currentLastLine) { commonRootMeetPoint = j; break; } } for (var j = commonRootMeetPoint; j >= 0; --j) { var line = prev[j]; if (current[currentLastIndex] === line) { current.pop(); currentLastIndex--; } else { break; } } current = prev; } } function cleanStack(stack) { var ret = []; for (var i = 0; i < stack.length; ++i) { var line = stack[i]; var isTraceLine = " (No stack trace)" === line || stackFramePattern.test(line); var isInternalFrame = isTraceLine && shouldIgnore(line); if (isTraceLine && !isInternalFrame) { if (indentStackFrames && line.charAt(0) !== " ") { line = " " + line; } ret.push(line); } } return ret; } function stackFramesAsArray(error) { var stack = error.stack.replace(/\s+$/g, "").split("\n"); for (var i = 0; i < stack.length; ++i) { var line = stack[i]; if (" (No stack trace)" === line || stackFramePattern.test(line)) { break; } } if (i > 0 && error.name != "SyntaxError") { stack = stack.slice(i); } return stack; } function parseStackAndMessage(error) { var stack = error.stack; var message = error.toString(); stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"]; return { message: message, stack: error.name == "SyntaxError" ? stack : cleanStack(stack) }; } function formatAndLogError(error, title, isSoft) { if (typeof console !== "undefined") { var message; if (util.isObject(error)) { var stack = error.stack; message = title + formatStack(stack, error); } else { message = title + String(error); } if (typeof printWarning === "function") { printWarning(message, isSoft); } else if (typeof console.log === "function" || typeof console.log === "object") { console.log(message); } } } function fireRejectionEvent(name, localHandler, reason, promise) { var localEventFired = false; try { if (typeof localHandler === "function") { localEventFired = true; if (name === "rejectionHandled") { localHandler(promise); } else { localHandler(reason, promise); } } } catch (e) { async.throwLater(e); } if (name === "unhandledRejection") { if (!activeFireEvent(name, reason, promise) && !localEventFired) { formatAndLogError(reason, "Unhandled rejection "); } } else { activeFireEvent(name, promise); } } function formatNonError(obj) { var str; if (typeof obj === "function") { str = "[function " + (obj.name || "anonymous") + "]"; } else { str = obj && typeof obj.toString === "function" ? obj.toString() : util.toString(obj); var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; if (ruselessToString.test(str)) { try { var newStr = JSON.stringify(obj); str = newStr; } catch(e) { } } if (str.length === 0) { str = "(empty array)"; } } return ("(<" + snip(str) + ">, no stack trace)"); } function snip(str) { var maxChars = 41; if (str.length < maxChars) { return str; } return str.substr(0, maxChars - 3) + "..."; } function longStackTracesIsSupported() { return typeof captureStackTrace === "function"; } var shouldIgnore = function() { return false; }; var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; function parseLineInfo(line) { var matches = line.match(parseLineInfoRegex); if (matches) { return { fileName: matches[1], line: parseInt(matches[2], 10) }; } } function setBounds(firstLineError, lastLineError) { if (!longStackTracesIsSupported()) return; var firstStackLines = firstLineError.stack.split("\n"); var lastStackLines = lastLineError.stack.split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; var lastFileName; for (var i = 0; i < firstStackLines.length; ++i) { var result = parseLineInfo(firstStackLines[i]); if (result) { firstFileName = result.fileName; firstIndex = result.line; break; } } for (var i = 0; i < lastStackLines.length; ++i) { var result = parseLineInfo(lastStackLines[i]); if (result) { lastFileName = result.fileName; lastIndex = result.line; break; } } if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) { return; } shouldIgnore = function(line) { if (bluebirdFramePattern.test(line)) return true; var info = parseLineInfo(line); if (info) { if (info.fileName === firstFileName && (firstIndex <= info.line && info.line <= lastIndex)) { return true; } } return false; }; } function CapturedTrace(parent) { this._parent = parent; this._promisesCreated = 0; var length = this._length = 1 + (parent === undefined ? 0 : parent._length); captureStackTrace(this, CapturedTrace); if (length > 32) this.uncycle(); } util.inherits(CapturedTrace, Error); Context.CapturedTrace = CapturedTrace; CapturedTrace.prototype.uncycle = function() { var length = this._length; if (length < 2) return; var nodes = []; var stackToIndex = {}; for (var i = 0, node = this; node !== undefined; ++i) { nodes.push(node); node = node._parent; } length = this._length = i; for (var i = length - 1; i >= 0; --i) { var stack = nodes[i].stack; if (stackToIndex[stack] === undefined) { stackToIndex[stack] = i; } } for (var i = 0; i < length; ++i) { var currentStack = nodes[i].stack; var index = stackToIndex[currentStack]; if (index !== undefined && index !== i) { if (index > 0) { nodes[index - 1]._parent = undefined; nodes[index - 1]._length = 1; } nodes[i]._parent = undefined; nodes[i]._length = 1; var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; if (index < length - 1) { cycleEdgeNode._parent = nodes[index + 1]; cycleEdgeNode._parent.uncycle(); cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; } else { cycleEdgeNode._parent = undefined; cycleEdgeNode._length = 1; } var currentChildLength = cycleEdgeNode._length + 1; for (var j = i - 2; j >= 0; --j) { nodes[j]._length = currentChildLength; currentChildLength++; } return; } } }; CapturedTrace.prototype.attachExtraTrace = function(error) { if (error.__stackCleaned__) return; this.uncycle(); var parsed = parseStackAndMessage(error); var message = parsed.message; var stacks = [parsed.stack]; var trace = this; while (trace !== undefined) { stacks.push(cleanStack(trace.stack.split("\n"))); trace = trace._parent; } removeCommonRoots(stacks); removeDuplicateOrEmptyJumps(stacks); util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); util.notEnumerableProp(error, "__stackCleaned__", true); }; var captureStackTrace = (function stackDetection() { var v8stackFramePattern = /^\s*at\s*/; var v8stackFormatter = function(stack, error) { if (typeof stack === "string") return stack; if (error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { Error.stackTraceLimit += 6; stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; var captureStackTrace = Error.captureStackTrace; shouldIgnore = function(line) { return bluebirdFramePattern.test(line); }; return function(receiver, ignoreUntil) { Error.stackTraceLimit += 6; captureStackTrace(receiver, ignoreUntil); Error.stackTraceLimit -= 6; }; } var err = new Error(); if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { stackFramePattern = /@/; formatStack = v8stackFormatter; indentStackFrames = true; return function captureStackTrace(o) { o.stack = new Error().stack; }; } var hasStackAfterThrow; try { throw new Error(); } catch(e) { hasStackAfterThrow = ("stack" in e); } if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { Error.stackTraceLimit += 6; try { throw new Error(); } catch(e) { o.stack = e.stack; } Error.stackTraceLimit -= 6; }; } formatStack = function(stack, error) { if (typeof stack === "string") return stack; if ((typeof error === "object" || typeof error === "function") && error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; return null; })([]); if (typeof console !== "undefined" && typeof console.warn !== "undefined") { printWarning = function (message) { console.warn(message); }; if (util.isNode && process.stderr.isTTY) { printWarning = function(message, isSoft) { var color = isSoft ? "\u001b[33m" : "\u001b[31m"; console.warn(color + message + "\u001b[0m\n"); }; } else if (!util.isNode && typeof (new Error().stack) === "string") { printWarning = function(message, isSoft) { console.warn("%c" + message, isSoft ? "color: darkorange" : "color: red"); }; } } var config = { warnings: warnings, longStackTraces: false, cancellation: false, monitoring: false }; if (longStackTraces) Promise.longStackTraces(); return { longStackTraces: function() { return config.longStackTraces; }, warnings: function() { return config.warnings; }, cancellation: function() { return config.cancellation; }, monitoring: function() { return config.monitoring; }, propagateFromFunction: function() { return propagateFromFunction; }, boundValueFunction: function() { return boundValueFunction; }, checkForgottenReturns: checkForgottenReturns, setBounds: setBounds, warn: warn, deprecated: deprecated, CapturedTrace: CapturedTrace, fireDomEvent: fireDomEvent, fireGlobalEvent: fireGlobalEvent }; }; },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function returner() { return this.value; } function thrower() { throw this.reason; } Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( returner, undefined, undefined, {value: value}, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { return this._then( thrower, undefined, undefined, {reason: reason}, undefined); }; Promise.prototype.catchThrow = function (reason) { if (arguments.length <= 1) { return this._then( undefined, thrower, undefined, {reason: reason}, undefined); } else { var _reason = arguments[1]; var handler = function() {throw _reason;}; return this.caught(reason, handler); } }; Promise.prototype.catchReturn = function (value) { if (arguments.length <= 1) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( undefined, returner, undefined, {value: value}, undefined); } else { var _value = arguments[1]; if (_value instanceof Promise) _value.suppressUnhandledRejections(); var handler = function() {return _value;}; return this.caught(value, handler); } }; }; },{}],11:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; var PromiseAll = Promise.all; function promiseAllThis() { return PromiseAll(this); } function PromiseMapSeries(promises, fn) { return PromiseReduce(promises, fn, INTERNAL, INTERNAL); } Promise.prototype.each = function (fn) { return PromiseReduce(this, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, this, undefined); }; Promise.prototype.mapSeries = function (fn) { return PromiseReduce(this, fn, INTERNAL, INTERNAL); }; Promise.each = function (promises, fn) { return PromiseReduce(promises, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, promises, undefined); }; Promise.mapSeries = PromiseMapSeries; }; },{}],12:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var Objectfreeze = es5.freeze; var util = _dereq_("./util"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage); notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Error.call(this); } } inherits(SubError, Error); return SubError; } var _TypeError, _RangeError; var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); var AggregateError = subError("AggregateError", "aggregate error"); try { _TypeError = TypeError; _RangeError = RangeError; } catch(e) { _TypeError = subError("TypeError", "type error"); _RangeError = subError("RangeError", "range error"); } var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); for (var i = 0; i < methods.length; ++i) { if (typeof Array.prototype[methods[i]] === "function") { AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; } } es5.defineProperty(AggregateError.prototype, "length", { value: 0, configurable: false, writable: true, enumerable: true }); AggregateError.prototype["isOperational"] = true; var level = 0; AggregateError.prototype.toString = function() { var indent = Array(level * 4 + 1).join(" "); var ret = "\n" + indent + "AggregateError of:" + "\n"; level++; indent = Array(level * 4 + 1).join(" "); for (var i = 0; i < this.length; ++i) { var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; var lines = str.split("\n"); for (var j = 0; j < lines.length; ++j) { lines[j] = indent + lines[j]; } str = lines.join("\n"); ret += str + "\n"; } level--; return ret; }; function OperationalError(message) { if (!(this instanceof OperationalError)) return new OperationalError(message); notEnumerableProp(this, "name", "OperationalError"); notEnumerableProp(this, "message", message); this.cause = message; this["isOperational"] = true; if (message instanceof Error) { notEnumerableProp(this, "message", message.message); notEnumerableProp(this, "stack", message.stack); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } inherits(OperationalError, Error); var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, TimeoutError: TimeoutError, OperationalError: OperationalError, RejectionError: OperationalError, AggregateError: AggregateError }); es5.defineProperty(Error, "__BluebirdErrorTypes__", { value: errorTypes, writable: false, enumerable: false, configurable: false }); } module.exports = { Error: Error, TypeError: _TypeError, RangeError: _RangeError, CancellationError: errorTypes.CancellationError, OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, AggregateError: errorTypes.AggregateError, Warning: Warning }; },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; return this === undefined; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5, propertyIsWritable: function(obj, prop) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); return !!(!descriptor || descriptor.writable || descriptor.set); } }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; var ObjectKeys = function (o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; }; var ObjectGetDescriptor = function(o, key) { return {value: o[key]}; }; var ObjectDefineProperty = function (o, key, desc) { o[key] = desc.value; return o; }; var ObjectFreeze = function (obj) { return obj; }; var ObjectGetPrototypeOf = function (obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } }; var ArrayIsArray = function (obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } }; module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, names: ObjectKeys, defineProperty: ObjectDefineProperty, getDescriptor: ObjectGetDescriptor, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5, propertyIsWritable: function() { return true; } }; } },{}],14:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseMap = Promise.map; Promise.prototype.filter = function (fn, options) { return PromiseMap(this, fn, options, INTERNAL); }; Promise.filter = function (promises, fn, options) { return PromiseMap(promises, fn, options, INTERNAL); }; }; },{}],15:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, tryConvertToPromise) { var util = _dereq_("./util"); var CancellationError = Promise.CancellationError; var errorObj = util.errorObj; function PassThroughHandlerContext(promise, type, handler) { this.promise = promise; this.type = type; this.handler = handler; this.called = false; this.cancelPromise = null; } PassThroughHandlerContext.prototype.isFinallyHandler = function() { return this.type === 0; }; function FinallyHandlerCancelReaction(finallyHandler) { this.finallyHandler = finallyHandler; } FinallyHandlerCancelReaction.prototype._resultCancelled = function() { checkCancel(this.finallyHandler); }; function checkCancel(ctx, reason) { if (ctx.cancelPromise != null) { if (arguments.length > 1) { ctx.cancelPromise._reject(reason); } else { ctx.cancelPromise._cancel(); } ctx.cancelPromise = null; return true; } return false; } function succeed() { return finallyHandler.call(this, this.promise._target()._settledValue()); } function fail(reason) { if (checkCancel(this, reason)) return; errorObj.e = reason; return errorObj; } function finallyHandler(reasonOrValue) { var promise = this.promise; var handler = this.handler; if (!this.called) { this.called = true; var ret = this.isFinallyHandler() ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue); if (ret !== undefined) { promise._setReturnedNonUndefined(); var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { if (this.cancelPromise != null) { if (maybePromise._isCancelled()) { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); errorObj.e = reason; return errorObj; } else if (maybePromise.isPending()) { maybePromise._attachCancellationCallback( new FinallyHandlerCancelReaction(this)); } } return maybePromise._then( succeed, fail, undefined, this, undefined); } } } if (promise.isRejected()) { checkCancel(this); errorObj.e = reasonOrValue; return errorObj; } else { checkCancel(this); return reasonOrValue; } } Promise.prototype._passThrough = function(handler, type, success, fail) { if (typeof handler !== "function") return this.then(); return this._then(success, fail, undefined, new PassThroughHandlerContext(this, type, handler), undefined); }; Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { return this._passThrough(handler, 0, finallyHandler, finallyHandler); }; Promise.prototype.tap = function (handler) { return this._passThrough(handler, 1, finallyHandler); }; return PassThroughHandlerContext; }; },{"./util":36}],16:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) { var errors = _dereq_("./errors"); var TypeError = errors.TypeError; var util = _dereq_("./util"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var yieldHandlers = []; function promiseFromYieldHandler(value, yieldHandlers, traceParent) { for (var i = 0; i < yieldHandlers.length; ++i) { traceParent._pushContext(); var result = tryCatch(yieldHandlers[i])(value); traceParent._popContext(); if (result === errorObj) { traceParent._pushContext(); var ret = Promise.reject(errorObj.e); traceParent._popContext(); return ret; } var maybePromise = tryConvertToPromise(result, traceParent); if (maybePromise instanceof Promise) return maybePromise; } return null; } function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { if (debug.cancellation()) { var internal = new Promise(INTERNAL); var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); this._promise = internal.lastly(function() { return _finallyPromise; }); internal._captureStackTrace(); internal._setOnCancel(this); } else { var promise = this._promise = new Promise(INTERNAL); promise._captureStackTrace(); } this._stack = stack; this._generatorFunction = generatorFunction; this._receiver = receiver; this._generator = undefined; this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; this._yieldedPromise = null; this._cancellationPhase = false; } util.inherits(PromiseSpawn, Proxyable); PromiseSpawn.prototype._isResolved = function() { return this._promise === null; }; PromiseSpawn.prototype._cleanup = function() { this._promise = this._generator = null; if (debug.cancellation() && this._finallyPromise !== null) { this._finallyPromise._fulfill(); this._finallyPromise = null; } }; PromiseSpawn.prototype._promiseCancelled = function() { if (this._isResolved()) return; var implementsReturn = typeof this._generator["return"] !== "undefined"; var result; if (!implementsReturn) { var reason = new Promise.CancellationError( "generator .return() sentinel"); Promise.coroutine.returnSentinel = reason; this._promise._attachExtraTrace(reason); this._promise._pushContext(); result = tryCatch(this._generator["throw"]).call(this._generator, reason); this._promise._popContext(); } else { this._promise._pushContext(); result = tryCatch(this._generator["return"]).call(this._generator, undefined); this._promise._popContext(); } this._cancellationPhase = true; this._yieldedPromise = null; this._continue(result); }; PromiseSpawn.prototype._promiseFulfilled = function(value) { this._yieldedPromise = null; this._promise._pushContext(); var result = tryCatch(this._generator.next).call(this._generator, value); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._promiseRejected = function(reason) { this._yieldedPromise = null; this._promise._attachExtraTrace(reason); this._promise._pushContext(); var result = tryCatch(this._generator["throw"]) .call(this._generator, reason); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._resultCancelled = function() { if (this._yieldedPromise instanceof Promise) { var promise = this._yieldedPromise; this._yieldedPromise = null; promise.cancel(); } }; PromiseSpawn.prototype.promise = function () { return this._promise; }; PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; this._promiseFulfilled(undefined); }; PromiseSpawn.prototype._continue = function (result) { var promise = this._promise; if (result === errorObj) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._rejectCallback(result.e, false); } } var value = result.value; if (result.done === true) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._resolveCallback(value); } } else { var maybePromise = tryConvertToPromise(value, this._promise); if (!(maybePromise instanceof Promise)) { maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise); if (maybePromise === null) { this._promiseRejected( new TypeError( "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) ); return; } } maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { this._yieldedPromise = maybePromise; maybePromise._proxy(this, null); } else if (((bitField & 33554432) !== 0)) { Promise._async.invoke( this._promiseFulfilled, this, maybePromise._value() ); } else if (((bitField & 16777216) !== 0)) { Promise._async.invoke( this._promiseRejected, this, maybePromise._reason() ); } else { this._promiseCancelled(); } } }; Promise.coroutine = function (generatorFunction, options) { if (typeof generatorFunction !== "function") { throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var yieldHandler = Object(options).yieldHandler; var PromiseSpawn$ = PromiseSpawn; var stack = new Error().stack; return function () { var generator = generatorFunction.apply(this, arguments); var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); var ret = spawn.promise(); spawn._generator = generator; spawn._promiseFulfilled(undefined); return ret; }; }; Promise.coroutine.addYieldHandler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { debug.deprecated("Promise.spawn()", "Promise.coroutine()"); if (typeof generatorFunction !== "function") { return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); spawn._run(Promise.spawn); return ret; }; }; },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; var errorObj = util.errorObj; var reject; if (false) { if (canEvaluate) { var thenCallback = function(i) { return new Function("value", "holder", " \n\ 'use strict'; \n\ holder.pIndex = value; \n\ holder.checkFulfillment(this); \n\ ".replace(/Index/g, i)); }; var promiseSetter = function(i) { return new Function("promise", "holder", " \n\ 'use strict'; \n\ holder.pIndex = promise; \n\ ".replace(/Index/g, i)); }; var generateHolderClass = function(total) { var props = new Array(total); for (var i = 0; i < props.length; ++i) { props[i] = "this.p" + (i+1); } var assignment = props.join(" = ") + " = null;"; var cancellationCode= "var promise;\n" + props.map(function(prop) { return " \n\ promise = " + prop + "; \n\ if (promise instanceof Promise) { \n\ promise.cancel(); \n\ } \n\ "; }).join("\n"); var passedArguments = props.join(", "); var name = "Holder$" + total; var code = "return function(tryCatch, errorObj, Promise, async) { \n\ 'use strict'; \n\ function [TheName](fn) { \n\ [TheProperties] \n\ this.fn = fn; \n\ this.asyncNeeded = true; \n\ this.now = 0; \n\ } \n\ \n\ [TheName].prototype._callFunction = function(promise) { \n\ promise._pushContext(); \n\ var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ promise._popContext(); \n\ if (ret === errorObj) { \n\ promise._rejectCallback(ret.e, false); \n\ } else { \n\ promise._resolveCallback(ret); \n\ } \n\ }; \n\ \n\ [TheName].prototype.checkFulfillment = function(promise) { \n\ var now = ++this.now; \n\ if (now === [TheTotal]) { \n\ if (this.asyncNeeded) { \n\ async.invoke(this._callFunction, this, promise); \n\ } else { \n\ this._callFunction(promise); \n\ } \n\ \n\ } \n\ }; \n\ \n\ [TheName].prototype._resultCancelled = function() { \n\ [CancellationCode] \n\ }; \n\ \n\ return [TheName]; \n\ }(tryCatch, errorObj, Promise, async); \n\ "; code = code.replace(/\[TheName\]/g, name) .replace(/\[TheTotal\]/g, total) .replace(/\[ThePassedArguments\]/g, passedArguments) .replace(/\[TheProperties\]/g, assignment) .replace(/\[CancellationCode\]/g, cancellationCode); return new Function("tryCatch", "errorObj", "Promise", "async", code) (tryCatch, errorObj, Promise, async); }; var holderClasses = []; var thenCallbacks = []; var promiseSetters = []; for (var i = 0; i < 8; ++i) { holderClasses.push(generateHolderClass(i + 1)); thenCallbacks.push(thenCallback(i + 1)); promiseSetters.push(promiseSetter(i + 1)); } reject = function (reason) { this._reject(reason); }; }} Promise.join = function () { var last = arguments.length - 1; var fn; if (last > 0 && typeof arguments[last] === "function") { fn = arguments[last]; if (false) { if (last <= 8 && canEvaluate) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var HolderClass = holderClasses[last - 1]; var holder = new HolderClass(fn); var callbacks = thenCallbacks; for (var i = 0; i < last; ++i) { var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { maybePromise._then(callbacks[i], reject, undefined, ret, holder); promiseSetters[i](maybePromise, holder); holder.asyncNeeded = false; } else if (((bitField & 33554432) !== 0)) { callbacks[i].call(ret, maybePromise._value(), holder); } else if (((bitField & 16777216) !== 0)) { ret._reject(maybePromise._reason()); } else { ret._cancel(); } } else { callbacks[i].call(ret, maybePromise, holder); } } if (!ret._isFateSealed()) { if (holder.asyncNeeded) { var domain = getDomain(); if (domain !== null) { holder.fn = util.domainBind(domain, holder.fn); } } ret._setAsyncGuaranteed(); ret._setOnCancel(holder); } return ret; } } } var args = [].slice.call(arguments);; if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; }; }; },{"./util":36}],18:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); var domain = getDomain(); this._callback = domain === null ? fn : util.domainBind(domain, fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = []; async.invoke(this._asyncInit, this, undefined); } util.inherits(MappingPromiseArray, PromiseArray); MappingPromiseArray.prototype._asyncInit = function() { this._init$(undefined, -2); }; MappingPromiseArray.prototype._init = function () {}; MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; if (index < 0) { index = (index * -1) - 1; values[index] = value; if (limit >= 1) { this._inFlight--; this._drainQueue(); if (this._isResolved()) return true; } } else { if (limit >= 1 && this._inFlight >= limit) { values[index] = value; this._queue.push(index); return false; } if (preservedValues !== null) preservedValues[index] = value; var promise = this._promise; var callback = this._callback; var receiver = promise._boundValue(); promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, preservedValues !== null ? "Promise.filter" : "Promise.map", promise ); if (ret === errorObj) { this._reject(ret.e); return true; } var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { if (limit >= 1) this._inFlight++; values[index] = maybePromise; maybePromise._proxy(this, (index + 1) * -1); return false; } else if (((bitField & 33554432) !== 0)) { ret = maybePromise._value(); } else if (((bitField & 16777216) !== 0)) { this._reject(maybePromise._reason()); return true; } else { this._cancel(); return true; } } values[index] = ret; } var totalResolved = ++this._totalResolved; if (totalResolved >= length) { if (preservedValues !== null) { this._filter(values, preservedValues); } else { this._resolve(values); } return true; } return false; }; MappingPromiseArray.prototype._drainQueue = function () { var queue = this._queue; var limit = this._limit; var values = this._values; while (queue.length > 0 && this._inFlight < limit) { if (this._isResolved()) return; var index = queue.pop(); this._promiseFulfilled(values[index], index); } }; MappingPromiseArray.prototype._filter = function (booleans, values) { var len = values.length; var ret = new Array(len); var j = 0; for (var i = 0; i < len; ++i) { if (booleans[i]) ret[j++] = values[i]; } ret.length = j; this._resolve(ret); }; MappingPromiseArray.prototype.preservedValues = function () { return this._preservedValues; }; function map(promises, fn, options, _filter) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var limit = 0; if (options !== undefined) { if (typeof options === "object" && options !== null) { if (typeof options.concurrency !== "number") { return Promise.reject( new TypeError("'concurrency' must be a number but it is " + util.classString(options.concurrency))); } limit = options.concurrency; } else { return Promise.reject(new TypeError( "options argument must be an object but it is " + util.classString(options))); } } limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0; return new MappingPromiseArray(promises, fn, limit, _filter).promise(); } Promise.prototype.map = function (fn, options) { return map(this, fn, options, null); }; Promise.map = function (promises, fn, options, _filter) { return map(promises, fn, options, _filter); }; }; },{"./util":36}],19:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; Promise.method = function (fn) { if (typeof fn !== "function") { throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); } return function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }; }; Promise.attempt = Promise["try"] = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value; if (arguments.length > 1) { debug.deprecated("calling Promise.try with more than 1 argument"); var arg = arguments[1]; var ctx = arguments[2]; value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) : tryCatch(fn).call(ctx, arg); } else { value = tryCatch(fn)(); } var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.try", ret); ret._resolveFromSyncValue(value); return ret; }; Promise.prototype._resolveFromSyncValue = function (value) { if (value === util.errorObj) { this._rejectCallback(value.e, false); } else { this._resolveCallback(value, true); } }; }; },{"./util":36}],20:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var maybeWrapAsError = util.maybeWrapAsError; var errors = _dereq_("./errors"); var OperationalError = errors.OperationalError; var es5 = _dereq_("./es5"); function isUntypedError(obj) { return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; } var rErrorKey = /^(?:name|message|stack|cause)$/; function wrapAsOperationalError(obj) { var ret; if (isUntypedError(obj)) { ret = new OperationalError(obj); ret.name = obj.name; ret.message = obj.message; ret.stack = obj.stack; var keys = es5.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!rErrorKey.test(key)) { ret[key] = obj[key]; } } return ret; } util.markAsOriginatingFromRejection(obj); return obj; } function nodebackForPromise(promise, multiArgs) { return function(err, value) { if (promise === null) return; if (err) { var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); promise._attachExtraTrace(wrapped); promise._reject(wrapped); } else if (!multiArgs) { promise._fulfill(value); } else { var args = [].slice.call(arguments, 1);; promise._fulfill(args); } promise = null; }; } module.exports = nodebackForPromise; },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var util = _dereq_("./util"); var async = Promise._async; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); if (ret === errorObj) { async.throwLater(ret.e); } } function successAdapter(val, nodeback) { var promise = this; var receiver = promise._boundValue(); var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); if (ret === errorObj) { async.throwLater(ret.e); } } function errorAdapter(reason, nodeback) { var promise = this; if (!reason) { var newReason = new Error(reason + ""); newReason.cause = reason; reason = newReason; } var ret = tryCatch(nodeback).call(promise._boundValue(), reason); if (ret === errorObj) { async.throwLater(ret.e); } } Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { if (typeof nodeback == "function") { var adapter = successAdapter; if (options !== undefined && Object(options).spread) { adapter = spreadAdapter; } this._then( adapter, errorAdapter, undefined, this, nodeback ); } return this; }; }; },{"./util":36}],22:[function(_dereq_,module,exports){ "use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var reflectHandler = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; function Proxyable() {} var UNDEFINED_BINDING = {}; var util = _dereq_("./util"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var es5 = _dereq_("./es5"); var Async = _dereq_("./async"); var async = new Async(); es5.defineProperty(Promise, "_async", {value: async}); var errors = _dereq_("./errors"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); var PromiseArray = _dereq_("./promise_array")(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); var Context = _dereq_("./context")(Promise); /*jshint unused:false*/ var createContext = Context.create; var debug = _dereq_("./debuggability")(Promise, Context); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = _dereq_("./finally")(Promise, tryConvertToPromise); var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); var nodebackForPromise = _dereq_("./nodeback"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; function check(self, executor) { if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util.classString(executor)); } if (self.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } } function Promise(executor) { this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; if (executor !== INTERNAL) { check(this, executor); this._resolveFromExecutor(executor); } this._promiseCreated(); this._fireEvent("promiseCreated", this); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return apiRejection("expecting an object but got " + "A catch statement predicate " + util.classString(item)); } } catchInstances.length = j; fn = arguments[i]; return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); }; Promise.prototype.reflect = function () { return this._then(reflectHandler, reflectHandler, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject) { if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, undefined, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject) { var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { if (arguments.length > 0) { this._warn(".all() was passed arguments but it does not take any"); } return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.getNewLibraryCopy = module.exports; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } return async.setScheduler(fn); }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } this._fireEvent("promiseChained", this, promise); } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && util.domainBind(domain, handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; this._fireEvent("promiseFulfilled", this); }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; this._fireEvent("promiseRejected", this); }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; this._fireEvent("promiseResolved", this); }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; this._fireEvent("promiseCancelled", this); }; Promise.prototype._setWillBeCancelled = function() { this._bitField = this._bitField | 8388608; }; Promise.prototype._setAsyncGuaranteed = function() { if (async.hasCustomScheduler()) return; this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : util.domainBind(domain, reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : util.domainBind(domain, reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); if (promise === this) { this._reject(makeSelfResolutionError()); return; } var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous, ignoreNonErrorWarnings) { var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj) { promise._rejectCallback(x.e, false); } else { debug.checkForgottenReturns(x, promiseCreated, "", promise, this); promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util.isNode); } if ((bitField & 65535) > 0) { async.settlePromises(this); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); _dereq_("./direct_resolve")(Promise); _dereq_("./synchronous_inspection")(Promise); _dereq_("./join")( Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); Promise.Promise = Promise; Promise.version = "3.4.7"; _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./call_get.js')(Promise); _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); _dereq_('./timers.js')(Promise, INTERNAL, debug); _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); _dereq_('./nodeify.js')(Promise); _dereq_('./promisify.js')(Promise, INTERNAL); _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./settle.js')(Promise, PromiseArray, debug); _dereq_('./some.js')(Promise, PromiseArray, apiRejection); _dereq_('./filter.js')(Promise, INTERNAL); _dereq_('./each.js')(Promise, INTERNAL); _dereq_('./any.js')(Promise); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util.lastLineError); return Promise; }; },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { var util = _dereq_("./util"); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { case -2: return []; case -3: return {}; } } function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); if (values instanceof Promise) { promise._propagateFrom(values, 3); } promise._setOnCancel(this); this._values = values; this._length = 0; this._totalResolved = 0; this._init(undefined, -2); } util.inherits(PromiseArray, Proxyable); PromiseArray.prototype.length = function () { return this._length; }; PromiseArray.prototype.promise = function () { return this._promise; }; PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { var values = tryConvertToPromise(this._values, this._promise); if (values instanceof Promise) { values = values._target(); var bitField = values._bitField; ; this._values = values; if (((bitField & 50397184) === 0)) { this._promise._setAsyncGuaranteed(); return values._then( init, this._reject, undefined, this, resolveValueIfEmpty ); } else if (((bitField & 33554432) !== 0)) { values = values._value(); } else if (((bitField & 16777216) !== 0)) { return this._reject(values._reason()); } else { return this._cancel(); } } values = util.asArray(values); if (values === null) { var err = apiRejection( "expecting an array or an iterable object but got " + util.classString(values)).reason(); this._promise._rejectCallback(err, false); return; } if (values.length === 0) { if (resolveValueIfEmpty === -5) { this._resolveEmptyArray(); } else { this._resolve(toResolutionValue(resolveValueIfEmpty)); } return; } this._iterate(values); }; PromiseArray.prototype._iterate = function(values) { var len = this.getActualLength(values.length); this._length = len; this._values = this.shouldCopyValues() ? new Array(len) : this._values; var result = this._promise; var isResolved = false; var bitField = null; for (var i = 0; i < len; ++i) { var maybePromise = tryConvertToPromise(values[i], result); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); bitField = maybePromise._bitField; } else { bitField = null; } if (isResolved) { if (bitField !== null) { maybePromise.suppressUnhandledRejections(); } } else if (bitField !== null) { if (((bitField & 50397184) === 0)) { maybePromise._proxy(this, i); this._values[i] = maybePromise; } else if (((bitField & 33554432) !== 0)) { isResolved = this._promiseFulfilled(maybePromise._value(), i); } else if (((bitField & 16777216) !== 0)) { isResolved = this._promiseRejected(maybePromise._reason(), i); } else { isResolved = this._promiseCancelled(i); } } else { isResolved = this._promiseFulfilled(maybePromise, i); } } if (!isResolved) result._setAsyncGuaranteed(); }; PromiseArray.prototype._isResolved = function () { return this._values === null; }; PromiseArray.prototype._resolve = function (value) { this._values = null; this._promise._fulfill(value); }; PromiseArray.prototype._cancel = function() { if (this._isResolved() || !this._promise._isCancellable()) return; this._values = null; this._promise._cancel(); }; PromiseArray.prototype._reject = function (reason) { this._values = null; this._promise._rejectCallback(reason, false); }; PromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; PromiseArray.prototype._promiseCancelled = function() { this._cancel(); return true; }; PromiseArray.prototype._promiseRejected = function (reason) { this._totalResolved++; this._reject(reason); return true; }; PromiseArray.prototype._resultCancelled = function() { if (this._isResolved()) return; var values = this._values; this._cancel(); if (values instanceof Promise) { values.cancel(); } else { for (var i = 0; i < values.length; ++i) { if (values[i] instanceof Promise) { values[i].cancel(); } } } }; PromiseArray.prototype.shouldCopyValues = function () { return true; }; PromiseArray.prototype.getActualLength = function (len) { return len; }; return PromiseArray; }; },{"./util":36}],24:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; var util = _dereq_("./util"); var nodebackForPromise = _dereq_("./nodeback"); var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var TypeError = _dereq_("./errors").TypeError; var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; var noCopyProps = [ "arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__" ]; var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor"; }; function propsFilter(key) { return !noCopyPropsPattern.test(key); } function isPromisified(fn) { try { return fn.__isPromisified__ === true; } catch (e) { return false; } } function hasPromisified(obj, key, suffix) { var val = util.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified); return val ? isPromisified(val) : false; } function checkValid(ret, suffix, suffixRegexp) { for (var i = 0; i < ret.length; i += 2) { var key = ret[i]; if (suffixRegexp.test(key)) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); for (var j = 0; j < ret.length; j += 2) { if (ret[j] === keyWithoutAsyncSuffix) { throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" .replace("%s", suffix)); } } } } } function promisifiableMethods(obj, suffix, suffixRegexp, filter) { var keys = util.inheritedDataKeys(obj); var ret = []; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var value = obj[key]; var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj); if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) { ret.push(key, value); } } checkValid(ret, suffix, suffixRegexp); return ret; } var escapeIdentRegex = function(str) { return str.replace(/([$])/, "\\$"); }; var makeNodePromisifiedEval; if (false) { var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { ret.push(i); } for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; }; var argumentSequence = function(argumentCount) { return util.filledRange(argumentCount, "_arg", ""); }; var parameterDeclaration = function(parameterCount) { return util.filledRange( Math.max(parameterCount, 3), "_arg", ""); }; var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; }; makeNodePromisifiedEval = function(callback, receiver, originalName, fn, _, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { var args = argumentSequence(count).join(", "); var comma = count > 0 ? ", " : ""; var ret; if (shouldProxyThis) { ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; } else { ret = receiver === undefined ? "ret = callback({{args}}, nodeback); break;\n" : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } ret += " \n\ default: \n\ var args = new Array(len + 1); \n\ var i = 0; \n\ for (var i = 0; i < len; ++i) { \n\ args[i] = arguments[i]; \n\ } \n\ args[i] = nodeback; \n\ [CodeForCall] \n\ break; \n\ ".replace("[CodeForCall]", (shouldProxyThis ? "ret = callback.apply(this, args);\n" : "ret = callback.apply(receiver, args);\n")); return ret; } var getFunctionCode = typeof callback === "string" ? ("this != null ? this['"+callback+"'] : fn") : "fn"; var body = "'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ promise._captureStackTrace(); \n\ var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ var ret; \n\ var callback = tryCatch([GetFunctionCode]); \n\ switch(len) { \n\ [CodeForSwitchCase] \n\ } \n\ if (ret === errorObj) { \n\ promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ } \n\ if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ return promise; \n\ }; \n\ notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) .replace("[GetFunctionCode]", getFunctionCode); body = body.replace("Parameters", parameterDeclaration(newParameterCount)); return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL", body)( Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util.tryCatch, util.errorObj, util.notEnumerableProp, INTERNAL); }; } function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { var defaultThis = (function() {return this;})(); var method = callback; if (typeof method === "string") { callback = fn; } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; var promise = new Promise(INTERNAL); promise._captureStackTrace(); var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; var fn = nodebackForPromise(promise, multiArgs); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true, true); } if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); return promise; } util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); for (var i = 0, len = methods.length; i < len; i+= 2) { var key = methods[i]; var fn = methods[i+1]; var promisifiedKey = key + suffix; if (promisifier === makeNodePromisified) { obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); } else { var promisified = promisifier(fn, function() { return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); }); util.notEnumerableProp(promisified, "__isPromisified__", true); obj[promisifiedKey] = promisified; } } util.toFastProperties(obj); return obj; } function promisify(callback, receiver, multiArgs) { return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs); } Promise.promisify = function (fn, options) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } if (isPromisified(fn)) { return fn; } options = Object(options); var receiver = options.context === undefined ? THIS : options.context; var multiArgs = !!options.multiArgs; var ret = promisify(fn, receiver, multiArgs); util.copyDescriptors(fn, ret, propsFilter); return ret; }; Promise.promisifyAll = function (target, options) { if (typeof target !== "function" && typeof target !== "object") { throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } options = Object(options); var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; var filter = options.filter; if (typeof filter !== "function") filter = defaultFilter; var promisifier = options.promisifier; if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util.isIdentifier(suffix)) { throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var keys = util.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util.isClass(value)) { promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs); promisifyAll(value, suffix, filter, promisifier, multiArgs); } } return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var isObject = util.isObject; var es5 = _dereq_("./es5"); var Es6Map; if (typeof Map === "function") Es6Map = Map; var mapToEntries = (function() { var index = 0; var size = 0; function extractEntry(value, key) { this[index] = value; this[index + size] = key; index++; } return function mapToEntries(map) { size = map.size; index = 0; var ret = new Array(map.size * 2); map.forEach(extractEntry, ret); return ret; }; })(); var entriesToMap = function(entries) { var ret = new Es6Map(); var length = entries.length / 2 | 0; for (var i = 0; i < length; ++i) { var key = entries[length + i]; var value = entries[i]; ret.set(key, value); } return ret; }; function PropertiesPromiseArray(obj) { var isMap = false; var entries; if (Es6Map !== undefined && obj instanceof Es6Map) { entries = mapToEntries(obj); isMap = true; } else { var keys = es5.keys(obj); var len = keys.length; entries = new Array(len * 2); for (var i = 0; i < len; ++i) { var key = keys[i]; entries[i] = obj[key]; entries[i + len] = key; } } this.constructor$(entries); this._isMap = isMap; this._init$(undefined, -3); } util.inherits(PropertiesPromiseArray, PromiseArray); PropertiesPromiseArray.prototype._init = function () {}; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { var val; if (this._isMap) { val = entriesToMap(this._values); } else { val = {}; var keyOffset = this.length(); for (var i = 0, len = this.length(); i < len; ++i) { val[this._values[i + keyOffset]] = this._values[i]; } } this._resolve(val); return true; } return false; }; PropertiesPromiseArray.prototype.shouldCopyValues = function () { return false; }; PropertiesPromiseArray.prototype.getActualLength = function (len) { return len >> 1; }; function props(promises) { var ret; var castValue = tryConvertToPromise(promises); if (!isObject(castValue)) { return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } else if (castValue instanceof Promise) { ret = castValue._then( Promise.props, undefined, undefined, undefined, undefined); } else { ret = new PropertiesPromiseArray(castValue).promise(); } if (castValue instanceof Promise) { ret._propagateFrom(castValue, 2); } return ret; } Promise.prototype.props = function () { return props(this); }; Promise.props = function (promises) { return props(promises); }; }; },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } function Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; Queue.prototype.push = function (fn, receiver, arg) { var length = this.length() + 3; if (this._willBeOverCapacity(length)) { this._pushOne(fn); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; },{}],27:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var raceLater = function (promise) { return promise.then(function(array) { return race(array, promise); }); }; function race(promises, parent) { var maybePromise = tryConvertToPromise(promises); if (maybePromise instanceof Promise) { return raceLater(maybePromise); } else { promises = util.asArray(promises); if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); } var ret = new Promise(INTERNAL); if (parent !== undefined) { ret._propagateFrom(parent, 3); } var fulfill = ret._fulfill; var reject = ret._reject; for (var i = 0, len = promises.length; i < len; ++i) { var val = promises[i]; if (val === undefined && !(i in promises)) { continue; } Promise.cast(val)._then(fulfill, reject, undefined, ret, null); } return ret; } Promise.race = function (promises) { return race(promises, undefined); }; Promise.prototype.race = function () { return race(this, undefined); }; }; },{"./util":36}],28:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); var domain = getDomain(); this._fn = domain === null ? fn : util.domainBind(domain, fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); } this._initialValue = initialValue; this._currentCancellable = null; if(_each === INTERNAL) { this._eachValues = Array(this._length); } else if (_each === 0) { this._eachValues = null; } else { this._eachValues = undefined; } this._promise._captureStackTrace(); this._init$(undefined, -5); } util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { if (this._eachValues !== undefined && this._eachValues !== null && accum !== INTERNAL) { this._eachValues.push(accum); } }; ReductionPromiseArray.prototype._eachComplete = function(value) { if (this._eachValues !== null) { this._eachValues.push(value); } return this._eachValues; }; ReductionPromiseArray.prototype._init = function() {}; ReductionPromiseArray.prototype._resolveEmptyArray = function() { this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue); }; ReductionPromiseArray.prototype.shouldCopyValues = function () { return false; }; ReductionPromiseArray.prototype._resolve = function(value) { this._promise._resolveCallback(value); this._values = null; }; ReductionPromiseArray.prototype._resultCancelled = function(sender) { if (sender === this._initialValue) return this._cancel(); if (this._isResolved()) return; this._resultCancelled$(); if (this._currentCancellable instanceof Promise) { this._currentCancellable.cancel(); } if (this._initialValue instanceof Promise) { this._initialValue.cancel(); } }; ReductionPromiseArray.prototype._iterate = function (values) { this._values = values; var value; var i; var length = values.length; if (this._initialValue !== undefined) { value = this._initialValue; i = 0; } else { value = Promise.resolve(values[0]); i = 1; } this._currentCancellable = value; if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { accum: null, value: values[i], index: i, length: length, array: this }; value = value._then(gotAccum, undefined, undefined, ctx, undefined); } } if (this._eachValues !== undefined) { value = value ._then(this._eachComplete, undefined, undefined, this, undefined); } value._then(completed, completed, undefined, value, this); }; Promise.prototype.reduce = function (fn, initialValue) { return reduce(this, fn, initialValue, null); }; Promise.reduce = function (promises, fn, initialValue, _each) { return reduce(promises, fn, initialValue, _each); }; function completed(valueOrReason, array) { if (this.isFulfilled()) { array._resolve(valueOrReason); } else { array._reject(valueOrReason); } } function reduce(promises, fn, initialValue, _each) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var array = new ReductionPromiseArray(promises, fn, initialValue, _each); return array.promise(); } function gotAccum(accum) { this.accum = accum; this.array._gotAccum(accum); var value = tryConvertToPromise(this.value, this.array._promise); if (value instanceof Promise) { this.array._currentCancellable = value; return value._then(gotValue, undefined, undefined, this, undefined); } else { return gotValue.call(this, value); } } function gotValue(value) { var array = this.array; var promise = array._promise; var fn = tryCatch(array._fn); promise._pushContext(); var ret; if (array._eachValues !== undefined) { ret = fn.call(promise._boundValue(), value, this.index, this.length); } else { ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length); } if (ret instanceof Promise) { array._currentCancellable = ret; } var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise ); return ret; } }; },{"./util":36}],29:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var schedule; var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var NativePromise = util.getNativePromise(); if (util.isNode && typeof MutationObserver === "undefined") { var GlobalSetImmediate = global.setImmediate; var ProcessNextTick = process.nextTick; schedule = util.isRecentNode ? function(fn) { GlobalSetImmediate.call(global, fn); } : function(fn) { ProcessNextTick.call(process, fn); }; } else if (typeof NativePromise === "function" && typeof NativePromise.resolve === "function") { var nativePromise = NativePromise.resolve(); schedule = function(fn) { nativePromise.then(fn); }; } else if ((typeof MutationObserver !== "undefined") && !(typeof window !== "undefined" && window.navigator && (window.navigator.standalone || window.cordova))) { schedule = (function() { var div = document.createElement("div"); var opts = {attributes: true}; var toggleScheduled = false; var div2 = document.createElement("div"); var o2 = new MutationObserver(function() { div.classList.toggle("foo"); toggleScheduled = false; }); o2.observe(div2, opts); var scheduleToggle = function() { if (toggleScheduled) return; toggleScheduled = true; div2.classList.toggle("foo"); }; return function schedule(fn) { var o = new MutationObserver(function() { o.disconnect(); fn(); }); o.observe(div, opts); scheduleToggle(); }; })(); } else if (typeof setImmediate !== "undefined") { schedule = function (fn) { setImmediate(fn); }; } else if (typeof setTimeout !== "undefined") { schedule = function (fn) { setTimeout(fn, 0); }; } else { schedule = noAsyncScheduler; } module.exports = schedule; },{"./util":36}],30:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; var util = _dereq_("./util"); function SettledPromiseArray(values) { this.constructor$(values); } util.inherits(SettledPromiseArray, PromiseArray); SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { this._values[index] = inspection; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 33554432; ret._settledValueField = value; return this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 16777216; ret._settledValueField = reason; return this._promiseResolved(index, ret); }; Promise.settle = function (promises) { debug.deprecated(".settle()", ".reflect()"); return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { return Promise.settle(this); }; }; },{"./util":36}],31:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection) { var util = _dereq_("./util"); var RangeError = _dereq_("./errors").RangeError; var AggregateError = _dereq_("./errors").AggregateError; var isArray = util.isArray; var CANCELLATION = {}; function SomePromiseArray(values) { this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } util.inherits(SomePromiseArray, PromiseArray); SomePromiseArray.prototype._init = function () { if (!this._initialized) { return; } if (this._howMany === 0) { this._resolve([]); return; } this._init$(undefined, -5); var isArrayResolved = isArray(this._values); if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { this._reject(this._getRangeError(this.length())); } }; SomePromiseArray.prototype.init = function () { this._initialized = true; this._init(); }; SomePromiseArray.prototype.setUnwrap = function () { this._unwrap = true; }; SomePromiseArray.prototype.howMany = function () { return this._howMany; }; SomePromiseArray.prototype.setHowMany = function (count) { this._howMany = count; }; SomePromiseArray.prototype._promiseFulfilled = function (value) { this._addFulfilled(value); if (this._fulfilled() === this.howMany()) { this._values.length = this.howMany(); if (this.howMany() === 1 && this._unwrap) { this._resolve(this._values[0]); } else { this._resolve(this._values); } return true; } return false; }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); return this._checkOutcome(); }; SomePromiseArray.prototype._promiseCancelled = function () { if (this._values instanceof Promise || this._values == null) { return this._cancel(); } this._addRejected(CANCELLATION); return this._checkOutcome(); }; SomePromiseArray.prototype._checkOutcome = function() { if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { if (this._values[i] !== CANCELLATION) { e.push(this._values[i]); } } if (e.length > 0) { this._reject(e); } else { this._cancel(); } return true; } return false; }; SomePromiseArray.prototype._fulfilled = function () { return this._totalResolved; }; SomePromiseArray.prototype._rejected = function () { return this._values.length - this.length(); }; SomePromiseArray.prototype._addRejected = function (reason) { this._values.push(reason); }; SomePromiseArray.prototype._addFulfilled = function (value) { this._values[this._totalResolved++] = value; }; SomePromiseArray.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected(); }; SomePromiseArray.prototype._getRangeError = function (count) { var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items"; return new RangeError(message); }; SomePromiseArray.prototype._resolveEmptyArray = function () { this._reject(this._getRangeError(0)); }; function some(promises, howMany) { if ((howMany | 0) !== howMany || howMany < 0) { return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(howMany); ret.init(); return promise; } Promise.some = function (promises, howMany) { return some(promises, howMany); }; Promise.prototype.some = function (howMany) { return some(this, howMany); }; Promise._SomePromiseArray = SomePromiseArray; }; },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function PromiseInspection(promise) { if (promise !== undefined) { promise = promise._target(); this._bitField = promise._bitField; this._settledValueField = promise._isFateSealed() ? promise._settledValue() : undefined; } else { this._bitField = 0; this._settledValueField = undefined; } } PromiseInspection.prototype._settledValue = function() { return this._settledValueField; }; var value = PromiseInspection.prototype.value = function () { if (!this.isFulfilled()) { throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var reason = PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () { if (!this.isRejected()) { throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { return (this._bitField & 33554432) !== 0; }; var isRejected = PromiseInspection.prototype.isRejected = function () { return (this._bitField & 16777216) !== 0; }; var isPending = PromiseInspection.prototype.isPending = function () { return (this._bitField & 50397184) === 0; }; var isResolved = PromiseInspection.prototype.isResolved = function () { return (this._bitField & 50331648) !== 0; }; PromiseInspection.prototype.isCancelled = function() { return (this._bitField & 8454144) !== 0; }; Promise.prototype.__isCancelled = function() { return (this._bitField & 65536) === 65536; }; Promise.prototype._isCancelled = function() { return this._target().__isCancelled(); }; Promise.prototype.isCancelled = function() { return (this._target()._bitField & 8454144) !== 0; }; Promise.prototype.isPending = function() { return isPending.call(this._target()); }; Promise.prototype.isRejected = function() { return isRejected.call(this._target()); }; Promise.prototype.isFulfilled = function() { return isFulfilled.call(this._target()); }; Promise.prototype.isResolved = function() { return isResolved.call(this._target()); }; Promise.prototype.value = function() { return value.call(this._target()); }; Promise.prototype.reason = function() { var target = this._target(); target._unsetRejectionIsUnhandled(); return reason.call(target); }; Promise.prototype._value = function() { return this._settledValue(); }; Promise.prototype._reason = function() { this._unsetRejectionIsUnhandled(); return this._settledValue(); }; Promise.PromiseInspection = PromiseInspection; }; },{}],33:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util"); var errorObj = util.errorObj; var isObject = util.isObject; function tryConvertToPromise(obj, context) { if (isObject(obj)) { if (obj instanceof Promise) return obj; var then = getThen(obj); if (then === errorObj) { if (context) context._pushContext(); var ret = Promise.reject(then.e); if (context) context._popContext(); return ret; } else if (typeof then === "function") { if (isAnyBluebirdPromise(obj)) { var ret = new Promise(INTERNAL); obj._then( ret._fulfill, ret._reject, undefined, ret, null ); return ret; } return doThenable(obj, then, context); } } return obj; } function doGetThen(obj) { return obj.then; } function getThen(obj) { try { return doGetThen(obj); } catch (e) { errorObj.e = e; return errorObj; } } var hasProp = {}.hasOwnProperty; function isAnyBluebirdPromise(obj) { try { return hasProp.call(obj, "_promise0"); } catch (e) { return false; } } function doThenable(x, then, context) { var promise = new Promise(INTERNAL); var ret = promise; if (context) context._pushContext(); promise._captureStackTrace(); if (context) context._popContext(); var synchronous = true; var result = util.tryCatch(then).call(x, resolve, reject); synchronous = false; if (promise && result === errorObj) { promise._rejectCallback(result.e, true, true); promise = null; } function resolve(value) { if (!promise) return; promise._resolveCallback(value); promise = null; } function reject(reason) { if (!promise) return; promise._rejectCallback(reason, synchronous, true); promise = null; } return ret; } return tryConvertToPromise; }; },{"./util":36}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, debug) { var util = _dereq_("./util"); var TimeoutError = Promise.TimeoutError; function HandleWrapper(handle) { this.handle = handle; } HandleWrapper.prototype._resultCancelled = function() { clearTimeout(this.handle); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; var delay = Promise.delay = function (ms, value) { var ret; var handle; if (value !== undefined) { ret = Promise.resolve(value) ._then(afterValue, null, null, ms, undefined); if (debug.cancellation() && value instanceof Promise) { ret._setOnCancel(value); } } else { ret = new Promise(INTERNAL); handle = setTimeout(function() { ret._fulfill(); }, +ms); if (debug.cancellation()) { ret._setOnCancel(new HandleWrapper(handle)); } ret._captureStackTrace(); } ret._setAsyncGuaranteed(); return ret; }; Promise.prototype.delay = function (ms) { return delay(ms, this); }; var afterTimeout = function (promise, message, parent) { var err; if (typeof message !== "string") { if (message instanceof Error) { err = message; } else { err = new TimeoutError("operation timed out"); } } else { err = new TimeoutError(message); } util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._reject(err); if (parent != null) { parent.cancel(); } }; function successClear(value) { clearTimeout(this.handle); return value; } function failureClear(reason) { clearTimeout(this.handle); throw reason; } Promise.prototype.timeout = function (ms, message) { ms = +ms; var ret, parent; var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { if (ret.isPending()) { afterTimeout(ret, message, parent); } }, ms)); if (debug.cancellation()) { parent = this.then(); ret = parent._then(successClear, failureClear, undefined, handleWrapper, undefined); ret._setOnCancel(handleWrapper); } else { ret = this._then(successClear, failureClear, undefined, handleWrapper, undefined); } return ret; }; }; },{"./util":36}],35:[function(_dereq_,module,exports){ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) { var util = _dereq_("./util"); var TypeError = _dereq_("./errors").TypeError; var inherits = _dereq_("./util").inherits; var errorObj = util.errorObj; var tryCatch = util.tryCatch; var NULL = {}; function thrower(e) { setTimeout(function(){throw e;}, 0); } function castPreservingDisposable(thenable) { var maybePromise = tryConvertToPromise(thenable); if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) { maybePromise._setDisposable(thenable._getDisposer()); } return maybePromise; } function dispose(resources, inspection) { var i = 0; var len = resources.length; var ret = new Promise(INTERNAL); function iterator() { if (i >= len) return ret._fulfill(); var maybePromise = castPreservingDisposable(resources[i++]); if (maybePromise instanceof Promise && maybePromise._isDisposable()) { try { maybePromise = tryConvertToPromise( maybePromise._getDisposer().tryDispose(inspection), resources.promise); } catch (e) { return thrower(e); } if (maybePromise instanceof Promise) { return maybePromise._then(iterator, thrower, null, null, null); } } iterator(); } iterator(); return ret; } function Disposer(data, promise, context) { this._data = data; this._promise = promise; this._context = context; } Disposer.prototype.data = function () { return this._data; }; Disposer.prototype.promise = function () { return this._promise; }; Disposer.prototype.resource = function () { if (this.promise().isFulfilled()) { return this.promise().value(); } return NULL; }; Disposer.prototype.tryDispose = function(inspection) { var resource = this.resource(); var context = this._context; if (context !== undefined) context._pushContext(); var ret = resource !== NULL ? this.doDispose(resource, inspection) : null; if (context !== undefined) context._popContext(); this._promise._unsetDisposable(); this._data = null; return ret; }; Disposer.isDisposer = function (d) { return (d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"); }; function FunctionDisposer(fn, promise, context) { this.constructor$(fn, promise, context); } inherits(FunctionDisposer, Disposer); FunctionDisposer.prototype.doDispose = function (resource, inspection) { var fn = this.data(); return fn.call(resource, resource, inspection); }; function maybeUnwrapDisposer(value) { if (Disposer.isDisposer(value)) { this.resources[this.index]._setDisposable(value); return value.promise(); } return value; } function ResourceList(length) { this.length = length; this.promise = null; this[length-1] = null; } ResourceList.prototype._resultCancelled = function() { var len = this.length; for (var i = 0; i < len; ++i) { var item = this[i]; if (item instanceof Promise) { item.cancel(); } } }; Promise.using = function () { var len = arguments.length; if (len < 2) return apiRejection( "you must pass at least 2 arguments to Promise.using"); var fn = arguments[len - 1]; if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var input; var spreadArgs = true; if (len === 2 && Array.isArray(arguments[0])) { input = arguments[0]; len = input.length; spreadArgs = false; } else { input = arguments; len--; } var resources = new ResourceList(len); for (var i = 0; i < len; ++i) { var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); resource._setDisposable(disposer); } else { var maybePromise = tryConvertToPromise(resource); if (maybePromise instanceof Promise) { resource = maybePromise._then(maybeUnwrapDisposer, null, null, { resources: resources, index: i }, undefined); } } resources[i] = resource; } var reflectedResources = new Array(resources.length); for (var i = 0; i < reflectedResources.length; ++i) { reflectedResources[i] = Promise.resolve(resources[i]).reflect(); } var resultPromise = Promise.all(reflectedResources) .then(function(inspections) { for (var i = 0; i < inspections.length; ++i) { var inspection = inspections[i]; if (inspection.isRejected()) { errorObj.e = inspection.error(); return errorObj; } else if (!inspection.isFulfilled()) { resultPromise.cancel(); return; } inspections[i] = inspection.value(); } promise._pushContext(); fn = tryCatch(fn); var ret = spreadArgs ? fn.apply(undefined, inspections) : fn(inspections); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, "Promise.using", promise); return ret; }); var promise = resultPromise.lastly(function() { var inspection = new Promise.PromiseInspection(resultPromise); return dispose(resources, inspection); }); resources.promise = promise; promise._setOnCancel(resources); return promise; }; Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 131072; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { return (this._bitField & 131072) > 0; }; Promise.prototype._getDisposer = function () { return this._disposer; }; Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~131072); this._disposer = undefined; }; Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; }; },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var canEvaluate = typeof navigator == "undefined"; var errorObj = {e: {}}; var tryCatchTarget; var globalObject = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : this !== undefined ? this : null; function tryCatcher() { try { var target = tryCatchTarget; tryCatchTarget = null; return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { tryCatchTarget = fn; return tryCatcher; } var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }; function isPrimitive(val) { return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; } function isObject(value) { return typeof value === "function" || typeof value === "object" && value !== null; } function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; return new Error(safeToString(maybeError)); } function withAppended(target, appendee) { var len = target.length; var ret = new Array(len + 1); var i; for (i = 0; i < len; ++i) { ret[i] = target[i]; } ret[i] = appendee; return ret; } function getDataPropertyOrDefault(obj, key, defaultValue) { if (es5.isES5) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null) { return desc.get == null && desc.set == null ? desc.value : defaultValue; } } else { return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; } } function notEnumerableProp(obj, name, value) { if (isPrimitive(obj)) return obj; var descriptor = { value: value, configurable: true, enumerable: false, writable: true }; es5.defineProperty(obj, name, descriptor); return obj; } function thrower(r) { throw r; } var inheritedDataKeys = (function() { var excludedPrototypes = [ Array.prototype, Object.prototype, Function.prototype ]; var isExcludedProto = function(val) { for (var i = 0; i < excludedPrototypes.length; ++i) { if (excludedPrototypes[i] === val) { return true; } } return false; }; if (es5.isES5) { var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); } catch (e) { return ret; } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (visitedKeys[key]) continue; visitedKeys[key] = true; var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null && desc.get == null && desc.set == null) { ret.push(key); } } obj = es5.getPrototypeOf(obj); } return ret; }; } else { var hasProp = {}.hasOwnProperty; return function(obj) { if (isExcludedProto(obj)) return []; var ret = []; /*jshint forin:false */ enumeration: for (var key in obj) { if (hasProp.call(obj, key)) { ret.push(key); } else { for (var i = 0; i < excludedPrototypes.length; ++i) { if (hasProp.call(excludedPrototypes[i], key)) { continue enumeration; } } ret.push(key); } } return ret; }; } })(); var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); var hasMethods = es5.isES5 && keys.length > 1; var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor"); var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) { return true; } } return false; } catch (e) { return false; } } function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ function FakeConstructor() {} FakeConstructor.prototype = obj; var l = 8; while (l--) new FakeConstructor(); return obj; eval(obj); } var rident = /^[a-z$_][a-z$_0-9]*$/i; function isIdentifier(str) { return rident.test(str); } function filledRange(count, prefix, suffix) { var ret = new Array(count); for(var i = 0; i < count; ++i) { ret[i] = prefix + i + suffix; } return ret; } function safeToString(obj) { try { return obj + ""; } catch (e) { return "[no string representation]"; } } function isError(obj) { return obj !== null && typeof obj === "object" && typeof obj.message === "string" && typeof obj.name === "string"; } function markAsOriginatingFromRejection(e) { try { notEnumerableProp(e, "isOperational", true); } catch(ignore) {} } function originatesFromRejection(e) { if (e == null) return false; return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || e["isOperational"] === true); } function canAttachTrace(obj) { return isError(obj) && es5.propertyIsWritable(obj, "stack"); } var ensureErrorObject = (function() { if (!("stack" in new Error())) { return function(value) { if (canAttachTrace(value)) return value; try {throw new Error(safeToString(value));} catch(err) {return err;} }; } else { return function(value) { if (canAttachTrace(value)) return value; return new Error(safeToString(value)); }; } })(); function classString(obj) { return {}.toString.call(obj); } function copyDescriptors(from, to, filter) { var keys = es5.names(from); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { try { es5.defineProperty(to, key, es5.getDescriptor(from, key)); } catch (ignore) {} } } } var asArray = function(v) { if (es5.isArray(v)) { return v; } return null; }; if (typeof Symbol !== "undefined" && Symbol.iterator) { var ArrayFrom = typeof Array.from === "function" ? function(v) { return Array.from(v); } : function(v) { var ret = []; var it = v[Symbol.iterator](); var itResult; while (!((itResult = it.next()).done)) { ret.push(itResult.value); } return ret; }; asArray = function(v) { if (es5.isArray(v)) { return v; } else if (v != null && typeof v[Symbol.iterator] === "function") { return ArrayFrom(v); } return null; }; } var isNode = typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]"; var hasEnvVariables = typeof process !== "undefined" && typeof process.env !== "undefined"; function env(key) { return hasEnvVariables ? process.env[key] : undefined; } function getNativePromise() { if (typeof Promise === "function") { try { var promise = new Promise(function(){}); if ({}.toString.call(promise) === "[object Promise]") { return Promise; } } catch (e) {} } } function domainBind(self, cb) { return self.bind(cb); } var ret = { isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, asArray: asArray, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, isError: isError, canEvaluate: canEvaluate, errorObj: errorObj, tryCatch: tryCatch, inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, canAttachTrace: canAttachTrace, ensureErrorObject: ensureErrorObject, originatesFromRejection: originatesFromRejection, markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function", isNode: isNode, hasEnvVariables: hasEnvVariables, env: env, global: globalObject, getNativePromise: getNativePromise, domainBind: domainBind }; ret.isRecentNode = ret.isNode && (function() { var version = process.versions.node.split(".").map(Number); return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); if (ret.isNode) ret.toFastProperties(process); try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25), __webpack_require__(5), __webpack_require__(53).setImmediate)) /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { var core = __webpack_require__(2) , $JSON = core.JSON || (core.JSON = {stringify: JSON.stringify}); module.exports = function stringify(it){ // eslint-disable-line no-unused-vars return $JSON.stringify.apply($JSON, arguments); }; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(142); module.exports = __webpack_require__(2).Object.assign; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(143); var $Object = __webpack_require__(2).Object; module.exports = function create(P, D){ return $Object.create(P, D); }; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(144); var $Object = __webpack_require__(2).Object; module.exports = function defineProperty(it, key, desc){ return $Object.defineProperty(it, key, desc); }; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(145); var $Object = __webpack_require__(2).Object; module.exports = function getOwnPropertyNames(it){ return $Object.getOwnPropertyNames(it); }; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(146); module.exports = __webpack_require__(2).Object.getPrototypeOf; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(147); module.exports = __webpack_require__(2).Object.keys; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(148); module.exports = __webpack_require__(2).Object.setPrototypeOf; /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(73); __webpack_require__(74); __webpack_require__(75); __webpack_require__(149); module.exports = __webpack_require__(2).Promise; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(150); __webpack_require__(73); __webpack_require__(151); __webpack_require__(152); module.exports = __webpack_require__(2).Symbol; /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(74); __webpack_require__(75); module.exports = __webpack_require__(49).f('iterator'); /***/ }, /* 117 */ /***/ function(module, exports) { module.exports = function(){ /* empty */ }; /***/ }, /* 118 */ /***/ function(module, exports) { module.exports = function(it, Constructor, name, forbiddenField){ if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ throw TypeError(name + ': incorrect invocation!'); } return it; }; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(13) , toLength = __webpack_require__(72) , toIndex = __webpack_require__(139); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__(20) , gOPS = __webpack_require__(42) , pIE = __webpack_require__(31); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = pIE.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(23) , call = __webpack_require__(125) , isArrayIter = __webpack_require__(123) , anObject = __webpack_require__(7) , toLength = __webpack_require__(72) , getIterFn = __webpack_require__(140) , BREAK = {} , RETURN = {}; var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) , f = ctx(fn, that, entries ? 2 : 1) , index = 0 , 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; /***/ }, /* 122 */ /***/ function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(24) , ITERATOR = __webpack_require__(3)('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(22); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(7); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var create = __webpack_require__(41) , descriptor = __webpack_require__(32) , setToStringTag = __webpack_require__(33) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(12)(IteratorPrototype, __webpack_require__(3)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(3)('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ return {done: safe = true}; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }, /* 128 */ /***/ function(module, exports) { module.exports = function(done, value){ return {value: value, done: !!done}; }; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var getKeys = __webpack_require__(20) , toIObject = __webpack_require__(13); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { var META = __webpack_require__(35)('meta') , isObject = __webpack_require__(19) , has = __webpack_require__(11) , setDesc = __webpack_require__(10).f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !__webpack_require__(18)(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 }; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , macrotask = __webpack_require__(71).set , Observer = global.MutationObserver || global.WebKitMutationObserver , process = global.process , Promise = global.Promise , isNode = __webpack_require__(22)(process) == 'process'; module.exports = function(){ var head, last, notify; var flush = function(){ var parent, fn; if(isNode && (parent = process.domain))parent.exit(); while(head){ fn = head.fn; head = head.next; try { fn(); } catch(e){ if(head)notify(); else last = undefined; throw e; } } last = undefined; if(parent)parent.enter(); }; // Node.js if(isNode){ notify = function(){ process.nextTick(flush); }; // browsers with MutationObserver } else if(Observer){ var toggle = true , node = document.createTextNode(''); new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new notify = function(){ node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if(Promise && Promise.resolve){ var promise = Promise.resolve(); notify = function(){ promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function(){ // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function(fn){ var task = {fn: fn, next: undefined}; if(last)last.next = task; if(!head){ head = task; notify(); } last = task; }; }; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = __webpack_require__(20) , gOPS = __webpack_require__(42) , pIE = __webpack_require__(31) , toObject = __webpack_require__(34) , IObject = __webpack_require__(63) , $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || __webpack_require__(18)(function(){ var A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , aLen = arguments.length , index = 1 , getSymbols = gOPS.f , isEnum = pIE.f; while(aLen > index){ var S = IObject(arguments[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : $assign; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(10) , anObject = __webpack_require__(7) , getKeys = __webpack_require__(20); module.exports = __webpack_require__(8) ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { var hide = __webpack_require__(12); module.exports = function(target, src, safe){ for(var key in src){ if(safe && target[key])target[key] = src[key]; else hide(target, key, src[key]); } return target; }; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = __webpack_require__(19) , anObject = __webpack_require__(7); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = __webpack_require__(23)(Function.call, __webpack_require__(65).f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var global = __webpack_require__(4) , core = __webpack_require__(2) , dP = __webpack_require__(10) , DESCRIPTORS = __webpack_require__(8) , SPECIES = __webpack_require__(3)('species'); module.exports = function(KEY){ var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { configurable: true, get: function(){ return this; } }); }; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(7) , aFunction = __webpack_require__(37) , SPECIES = __webpack_require__(3)('species'); module.exports = function(O, D){ var C = anObject(O).constructor, S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(46) , defined = __webpack_require__(38); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(46) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(60) , ITERATOR = __webpack_require__(3)('iterator') , Iterators = __webpack_require__(24); module.exports = __webpack_require__(2).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var addToUnscopables = __webpack_require__(117) , step = __webpack_require__(128) , Iterators = __webpack_require__(24) , toIObject = __webpack_require__(13); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(64)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(9); $export($export.S + $export.F, 'Object', {assign: __webpack_require__(132)}); /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(9) // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', {create: __webpack_require__(41)}); /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(9); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !__webpack_require__(8), 'Object', {defineProperty: __webpack_require__(10).f}); /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.7 Object.getOwnPropertyNames(O) __webpack_require__(43)('getOwnPropertyNames', function(){ return __webpack_require__(66).f; }); /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 Object.getPrototypeOf(O) var toObject = __webpack_require__(34) , $getPrototypeOf = __webpack_require__(68); __webpack_require__(43)('getPrototypeOf', function(){ return function getPrototypeOf(it){ return $getPrototypeOf(toObject(it)); }; }); /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(34) , $keys = __webpack_require__(20); __webpack_require__(43)('keys', function(){ return function keys(it){ return $keys(toObject(it)); }; }); /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(9); $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(135).set}); /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; var LIBRARY = __webpack_require__(30) , global = __webpack_require__(4) , ctx = __webpack_require__(23) , classof = __webpack_require__(60) , $export = __webpack_require__(9) , isObject = __webpack_require__(19) , aFunction = __webpack_require__(37) , anInstance = __webpack_require__(118) , forOf = __webpack_require__(121) , speciesConstructor = __webpack_require__(137) , task = __webpack_require__(71).set , microtask = __webpack_require__(131)() , PROMISE = 'Promise' , TypeError = global.TypeError , process = global.process , $Promise = global[PROMISE] , process = global.process , isNode = classof(process) == 'process' , empty = function(){ /* empty */ } , Internal, GenericPromiseCapability, Wrapper; var USE_NATIVE = !!function(){ try { // correct subclassing with @@species support var promise = $Promise.resolve(1) , FakePromise = (promise.constructor = {})[__webpack_require__(3)('species')] = function(exec){ exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch(e){ /* empty */ } }(); // helpers var sameConstructor = function(a, b){ // with library wrapper special case return a === b || a === $Promise && b === Wrapper; }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var newPromiseCapability = function(C){ return sameConstructor($Promise, C) ? new PromiseCapability(C) : new GenericPromiseCapability(C); }; var PromiseCapability = GenericPromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(promise, isReject){ if(promise._n)return; promise._n = true; var chain = promise._c; microtask(function(){ var value = promise._v , ok = promise._s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , domain = reaction.domain , result, then; try { if(handler){ if(!ok){ if(promise._h == 2)onHandleUnhandled(promise); promise._h = 1; } if(handler === true)result = value; else { if(domain)domain.enter(); result = handler(value); if(domain)domain.exit(); } if(result === reaction.promise){ reject(TypeError('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if(isReject && !promise._h)onUnhandled(promise); }); }; var onUnhandled = function(promise){ task.call(global, function(){ var value = promise._v , abrupt, handler, console; if(isUnhandled(promise)){ abrupt = perform(function(){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = global.console) && console.error){ console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if(abrupt)throw abrupt.error; }); }; var isUnhandled = function(promise){ if(promise._h == 1)return false; var chain = promise._a || promise._c , i = 0 , reaction; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var onHandleUnhandled = function(promise){ task.call(global, function(){ var handler; if(isNode){ process.emit('rejectionHandled', promise); } else if(handler = global.onrejectionhandled){ handler({promise: promise, reason: promise._v}); } }); }; var $reject = function(value){ var promise = this; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if(!promise._a)promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function(value){ var promise = this , then; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap try { if(promise === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ microtask(function(){ var wrapper = {_w: promise, _d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch(e){ $reject.call({_w: promise, _d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) $Promise = function Promise(executor){ anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch(err){ $reject.call(this, err); } }; Internal = function Promise(executor){ this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = __webpack_require__(134)($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if(this._a)this._a.push(reaction); if(this._s)notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); PromiseCapability = function(){ var promise = new Internal; this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); __webpack_require__(33)($Promise, PROMISE); __webpack_require__(136)(PROMISE); Wrapper = __webpack_require__(2)[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = newPromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; var capability = newPromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(127)(function(iter){ $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = this , capability = newPromiseCapability(C) , resolve = capability.resolve , reject = capability.reject; var abrupt = perform(function(){ var values = [] , index = 0 , remaining = 1; forOf(iterable, false, function(promise){ var $index = index++ , alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = this , capability = newPromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } }); /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict'; // ECMAScript 6 symbols shim var global = __webpack_require__(4) , has = __webpack_require__(11) , DESCRIPTORS = __webpack_require__(8) , $export = __webpack_require__(9) , redefine = __webpack_require__(70) , META = __webpack_require__(130).KEY , $fails = __webpack_require__(18) , shared = __webpack_require__(45) , setToStringTag = __webpack_require__(33) , uid = __webpack_require__(35) , wks = __webpack_require__(3) , wksExt = __webpack_require__(49) , wksDefine = __webpack_require__(48) , keyOf = __webpack_require__(129) , enumKeys = __webpack_require__(120) , isArray = __webpack_require__(124) , anObject = __webpack_require__(7) , toIObject = __webpack_require__(13) , toPrimitive = __webpack_require__(47) , createDesc = __webpack_require__(32) , _create = __webpack_require__(41) , gOPNExt = __webpack_require__(66) , $GOPD = __webpack_require__(65) , $DP = __webpack_require__(10) , $keys = __webpack_require__(20) , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , PROTOTYPE = 'prototype' , HIDDEN = wks('_hidden') , TO_PRIMITIVE = wks('toPrimitive') , isEnum = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , OPSymbols = shared('op-symbols') , ObjectProto = Object[PROTOTYPE] , USE_NATIVE = typeof $Symbol == 'function' , QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(dP({}, 'a', { get: function(){ return dP(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; dP(it, key, D); if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); } : dP; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto)$defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if(has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = toPrimitive(key, true)); if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = toIObject(it); key = toPrimitive(key, true); if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; var D = gOPD(it, key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto)$set.call(OPSymbols, value); if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString(){ return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__(67).f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__(31).f = $propertyIsEnumerable; __webpack_require__(42).f = $getOwnPropertySymbols; if(DESCRIPTORS && !__webpack_require__(30)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function(name){ return wrap(wks(name)); } } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return keyOf(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(12)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(48)('asyncIterator'); /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(48)('observable'); /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, setImmediate) {(function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Dexie = factory()); }(this, (function () { 'use strict'; /* * Dexie.js - a minimalistic wrapper for IndexedDB * =============================================== * * By David Fahlander, david.fahlander@gmail.com * * Version 1.5.1, Tue Nov 01 2016 * www.dexie.com * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ */ var keys = Object.keys; var isArray = Array.isArray; var _global = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global; function extend(obj, extension) { if (typeof extension !== 'object') return obj; keys(extension).forEach(function (key) { obj[key] = extension[key]; }); return obj; } var getProto = Object.getPrototypeOf; var _hasOwn = {}.hasOwnProperty; function hasOwn(obj, prop) { return _hasOwn.call(obj, prop); } function props(proto, extension) { if (typeof extension === 'function') extension = extension(getProto(proto)); keys(extension).forEach(function (key) { setProp(proto, key, extension[key]); }); } function setProp(obj, prop, functionOrGetSet, options) { Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : { value: functionOrGetSet, configurable: true, writable: true }, options)); } function derive(Child) { return { from: function (Parent) { Child.prototype = Object.create(Parent.prototype); setProp(Child.prototype, "constructor", Child); return { extend: props.bind(null, Child.prototype) }; } }; } var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; function getPropertyDescriptor(obj, prop) { var pd = getOwnPropertyDescriptor(obj, prop), proto; return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); } var _slice = [].slice; function slice(args, start, end) { return _slice.call(args, start, end); } function override(origFunc, overridedFactory) { return overridedFactory(origFunc); } function doFakeAutoComplete(fn) { var to = setTimeout(fn, 1000); clearTimeout(to); } function assert(b) { if (!b) throw new Error("Assertion Failed"); } function asap(fn) { if (_global.setImmediate) setImmediate(fn);else setTimeout(fn, 0); } /** Generate an object (hash map) based on given array. * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to * instert on the resulting object for each item in the array. If this function returns a falsy value, the * current item wont affect the resulting object. */ function arrayToObject(array, extractor) { return array.reduce(function (result, item, i) { var nameAndValue = extractor(item, i); if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1]; return result; }, {}); } function trycatcher(fn, reject) { return function () { try { fn.apply(this, arguments); } catch (e) { reject(e); } }; } function tryCatch(fn, onerror, args) { try { fn.apply(null, args); } catch (ex) { onerror && onerror(ex); } } function getByKeyPath(obj, keyPath) { // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose. if (!keyPath) return obj; if (typeof keyPath !== 'string') { var rv = []; for (var i = 0, l = keyPath.length; i < l; ++i) { var val = getByKeyPath(obj, keyPath[i]); rv.push(val); } return rv; } var period = keyPath.indexOf('.'); if (period !== -1) { var innerObj = obj[keyPath.substr(0, period)]; return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); } return undefined; } function setByKeyPath(obj, keyPath, value) { if (!obj || keyPath === undefined) return; if ('isFrozen' in Object && Object.isFrozen(obj)) return; if (typeof keyPath !== 'string' && 'length' in keyPath) { assert(typeof value !== 'string' && 'length' in value); for (var i = 0, l = keyPath.length; i < l; ++i) { setByKeyPath(obj, keyPath[i], value[i]); } } else { var period = keyPath.indexOf('.'); if (period !== -1) { var currentKeyPath = keyPath.substr(0, period); var remainingKeyPath = keyPath.substr(period + 1); if (remainingKeyPath === "") { if (value === undefined) delete obj[currentKeyPath];else obj[currentKeyPath] = value; } else { var innerObj = obj[currentKeyPath]; if (!innerObj) innerObj = obj[currentKeyPath] = {}; setByKeyPath(innerObj, remainingKeyPath, value); } } else { if (value === undefined) delete obj[keyPath];else obj[keyPath] = value; } } } function delByKeyPath(obj, keyPath) { if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined);else if ('length' in keyPath) [].map.call(keyPath, function (kp) { setByKeyPath(obj, kp, undefined); }); } function shallowClone(obj) { var rv = {}; for (var m in obj) { if (hasOwn(obj, m)) rv[m] = obj[m]; } return rv; } function deepClone(any) { if (!any || typeof any !== 'object') return any; var rv; if (isArray(any)) { rv = []; for (var i = 0, l = any.length; i < l; ++i) { rv.push(deepClone(any[i])); } } else if (any instanceof Date) { rv = new Date(); rv.setTime(any.getTime()); } else { rv = any.constructor ? Object.create(any.constructor.prototype) : {}; for (var prop in any) { if (hasOwn(any, prop)) { rv[prop] = deepClone(any[prop]); } } } return rv; } function getObjectDiff(a, b, rv, prfx) { // Compares objects a and b and produces a diff object. rv = rv || {}; prfx = prfx || ''; keys(a).forEach(function (prop) { if (!hasOwn(b, prop)) rv[prfx + prop] = undefined; // Property removed else { var ap = a[prop], bp = b[prop]; if (typeof ap === 'object' && typeof bp === 'object' && ap && bp && ap.constructor === bp.constructor) // Same type of object but its properties may have changed getObjectDiff(ap, bp, rv, prfx + prop + ".");else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed } }); keys(b).forEach(function (prop) { if (!hasOwn(a, prop)) { rv[prfx + prop] = b[prop]; // Property added } }); return rv; } // If first argument is iterable or array-like, return it as an array var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator; var getIteratorOf = iteratorSymbol ? function (x) { var i; return x != null && (i = x[iteratorSymbol]) && i.apply(x); } : function () { return null; }; var NO_CHAR_ARRAY = {}; // Takes one or several arguments and returns an array based on the following criteras: // * If several arguments provided, return arguments converted to an array in a way that // still allows javascript engine to optimize the code. // * If single argument is an array, return a clone of it. // * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special // case to the two bullets below. // * If single argument is an iterable, convert it to an array and return the resulting array. // * If single argument is array-like (has length of type number), convert it to an array. function getArrayOf(arrayLike) { var i, a, x, it; if (arguments.length === 1) { if (isArray(arrayLike)) return arrayLike.slice(); if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike]; if (it = getIteratorOf(arrayLike)) { a = []; while (x = it.next(), !x.done) { a.push(x.value); }return a; } if (arrayLike == null) return [arrayLike]; i = arrayLike.length; if (typeof i === 'number') { a = new Array(i); while (i--) { a[i] = arrayLike[i]; }return a; } return [arrayLike]; } i = arguments.length; a = new Array(i); while (i--) { a[i] = arguments[i]; }return a; } var concat = [].concat; function flatten(a) { return concat.apply([], a); } function nop() {} function mirror(val) { return val; } function pureFunctionChain(f1, f2) { // Enables chained events that takes ONE argument and returns it to the next function in chain. // This pattern is used in the hook("reading") event. if (f1 == null || f1 === mirror) return f2; return function (val) { return f2(f1(val)); }; } function callBoth(on1, on2) { return function () { on1.apply(this, arguments); on2.apply(this, arguments); }; } function hookCreatingChain(f1, f2) { // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance. // This pattern is used in the hook("creating") event. if (f1 === nop) return f2; return function () { var res = f1.apply(this, arguments); if (res !== undefined) arguments[0] = res; var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess onerror = this.onerror; // In case event listener has set this.onerror this.onsuccess = null; this.onerror = null; var res2 = f2.apply(this, arguments); if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; return res2 !== undefined ? res2 : res; }; } function hookDeletingChain(f1, f2) { if (f1 === nop) return f2; return function () { f1.apply(this, arguments); var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess onerror = this.onerror; // In case event listener has set this.onerror this.onsuccess = this.onerror = null; f2.apply(this, arguments); if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; }; } function hookUpdatingChain(f1, f2) { if (f1 === nop) return f2; return function (modifications) { var res = f1.apply(this, arguments); extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain. var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess onerror = this.onerror; // In case event listener has set this.onerror this.onsuccess = null; this.onerror = null; var res2 = f2.apply(this, arguments); if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; return res === undefined ? res2 === undefined ? undefined : res2 : extend(res, res2); }; } function reverseStoppableEventChain(f1, f2) { if (f1 === nop) return f2; return function () { if (f2.apply(this, arguments) === false) return false; return f1.apply(this, arguments); }; } function promisableChain(f1, f2) { if (f1 === nop) return f2; return function () { var res = f1.apply(this, arguments); if (res && typeof res.then === 'function') { var thiz = this, i = arguments.length, args = new Array(i); while (i--) { args[i] = arguments[i]; }return res.then(function () { return f2.apply(thiz, args); }); } return f2.apply(this, arguments); }; } // By default, debug will be true only if platform is a web platform and its page is served from localhost. // When debug = true, error's stacks will contain asyncronic long stacks. var debug = typeof location !== 'undefined' && // By default, use debug mode if served from localhost. /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); function setDebug(value, filter) { debug = value; libraryFilter = filter; } var libraryFilter = function () { return true; }; var NEEDS_THROW_FOR_STACK = !new Error("").stack; function getErrorWithStack() { "use strict"; if (NEEDS_THROW_FOR_STACK) try { // Doing something naughty in strict mode here to trigger a specific error // that can be explicitely ignored in debugger's exception settings. // If we'd just throw new Error() here, IE's debugger's exception settings // will just consider it as "exception thrown by javascript code" which is // something you wouldn't want it to ignore. getErrorWithStack.arguments; throw new Error(); // Fallback if above line don't throw. } catch (e) { return e; } return new Error(); } function prettyStack(exception, numIgnoredFrames) { var stack = exception.stack; if (!stack) return ""; numIgnoredFrames = numIgnoredFrames || 0; if (stack.indexOf(exception.name) === 0) numIgnoredFrames += (exception.name + exception.message).split('\n').length; return stack.split('\n').slice(numIgnoredFrames).filter(libraryFilter).map(function (frame) { return "\n" + frame; }).join(''); } function deprecated(what, fn) { return function () { console.warn(what + " is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. " + prettyStack(getErrorWithStack(), 1)); return fn.apply(this, arguments); }; } var dexieErrorNames = ['Modify', 'Bulk', 'OpenFailed', 'VersionChange', 'Schema', 'Upgrade', 'InvalidTable', 'MissingAPI', 'NoSuchDatabase', 'InvalidArgument', 'SubTransaction', 'Unsupported', 'Internal', 'DatabaseClosed', 'IncompatiblePromise']; var idbDomErrorNames = ['Unknown', 'Constraint', 'Data', 'TransactionInactive', 'ReadOnly', 'Version', 'NotFound', 'InvalidState', 'InvalidAccess', 'Abort', 'Timeout', 'QuotaExceeded', 'Syntax', 'DataClone']; var errorList = dexieErrorNames.concat(idbDomErrorNames); var defaultTexts = { VersionChanged: "Database version changed by other database connection", DatabaseClosed: "Database has been closed", Abort: "Transaction aborted", TransactionInactive: "Transaction has already completed or failed" }; // // DexieError - base class of all out exceptions. // function DexieError(name, msg) { // Reason we don't use ES6 classes is because: // 1. It bloats transpiled code and increases size of minified code. // 2. It doesn't give us much in this case. // 3. It would require sub classes to call super(), which // is not needed when deriving from Error. this._e = getErrorWithStack(); this.name = name; this.message = msg; } derive(DexieError).from(Error).extend({ stack: { get: function () { return this._stack || (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2)); } }, toString: function () { return this.name + ": " + this.message; } }); function getMultiErrorMessage(msg, failures) { return msg + ". Errors: " + failures.map(function (f) { return f.toString(); }).filter(function (v, i, s) { return s.indexOf(v) === i; }) // Only unique error strings .join('\n'); } // // ModifyError - thrown in WriteableCollection.modify() // Specific constructor because it contains members failures and failedKeys. // function ModifyError(msg, failures, successCount, failedKeys) { this._e = getErrorWithStack(); this.failures = failures; this.failedKeys = failedKeys; this.successCount = successCount; } derive(ModifyError).from(DexieError); function BulkError(msg, failures) { this._e = getErrorWithStack(); this.name = "BulkError"; this.failures = failures; this.message = getMultiErrorMessage(msg, failures); } derive(BulkError).from(DexieError); // // // Dynamically generate error names and exception classes based // on the names in errorList. // // // Map of {ErrorName -> ErrorName + "Error"} var errnames = errorList.reduce(function (obj, name) { return obj[name] = name + "Error", obj; }, {}); // Need an alias for DexieError because we're gonna create subclasses with the same name. var BaseException = DexieError; // Map of {ErrorName -> exception constructor} var exceptions = errorList.reduce(function (obj, name) { // Let the name be "DexieError" because this name may // be shown in call stack and when debugging. DexieError is // the most true name because it derives from DexieError, // and we cannot change Function.name programatically without // dynamically create a Function object, which would be considered // 'eval-evil'. var fullName = name + "Error"; function DexieError(msgOrInner, inner) { this._e = getErrorWithStack(); this.name = fullName; if (!msgOrInner) { this.message = defaultTexts[name] || fullName; this.inner = null; } else if (typeof msgOrInner === 'string') { this.message = msgOrInner; this.inner = inner || null; } else if (typeof msgOrInner === 'object') { this.message = msgOrInner.name + ' ' + msgOrInner.message; this.inner = msgOrInner; } } derive(DexieError).from(BaseException); obj[name] = DexieError; return obj; }, {}); // Use ECMASCRIPT standard exceptions where applicable: exceptions.Syntax = SyntaxError; exceptions.Type = TypeError; exceptions.Range = RangeError; var exceptionMap = idbDomErrorNames.reduce(function (obj, name) { obj[name + "Error"] = exceptions[name]; return obj; }, {}); function mapError(domError, message) { if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) return domError; var rv = new exceptionMap[domError.name](message || domError.message, domError); if ("stack" in domError) { // Derive stack from inner exception if it has a stack setProp(rv, "stack", { get: function () { return this.inner.stack; } }); } return rv; } var fullNameExceptions = errorList.reduce(function (obj, name) { if (["Syntax", "Type", "Range"].indexOf(name) === -1) obj[name + "Error"] = exceptions[name]; return obj; }, {}); fullNameExceptions.ModifyError = ModifyError; fullNameExceptions.DexieError = DexieError; fullNameExceptions.BulkError = BulkError; function Events(ctx) { var evs = {}; var rv = function (eventName, subscriber) { if (subscriber) { // Subscribe. If additional arguments than just the subscriber was provided, forward them as well. var i = arguments.length, args = new Array(i - 1); while (--i) { args[i - 1] = arguments[i]; }evs[eventName].subscribe.apply(null, args); return ctx; } else if (typeof eventName === 'string') { // Return interface allowing to fire or unsubscribe from event return evs[eventName]; } }; rv.addEventType = add; for (var i = 1, l = arguments.length; i < l; ++i) { add(arguments[i]); } return rv; function add(eventName, chainFunction, defaultFunction) { if (typeof eventName === 'object') return addConfiguredEvents(eventName); if (!chainFunction) chainFunction = reverseStoppableEventChain; if (!defaultFunction) defaultFunction = nop; var context = { subscribers: [], fire: defaultFunction, subscribe: function (cb) { if (context.subscribers.indexOf(cb) === -1) { context.subscribers.push(cb); context.fire = chainFunction(context.fire, cb); } }, unsubscribe: function (cb) { context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; }); context.fire = context.subscribers.reduce(chainFunction, defaultFunction); } }; evs[eventName] = rv[eventName] = context; return context; } function addConfiguredEvents(cfg) { // events(this, {reading: [functionChain, nop]}); keys(cfg).forEach(function (eventName) { var args = cfg[eventName]; if (isArray(args)) { add(eventName, cfg[eventName][0], cfg[eventName][1]); } else if (args === 'asap') { // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten. var context = add(eventName, mirror, function fire() { // Optimazation-safe cloning of arguments into args. var i = arguments.length, args = new Array(i); while (i--) { args[i] = arguments[i]; } // All each subscriber: context.subscribers.forEach(function (fn) { asap(function fireEvent() { fn.apply(null, args); }); }); }); } else throw new exceptions.InvalidArgument("Invalid event config"); }); } } // // Promise Class for Dexie library // // I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by // https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation. // // Modifications needed to be done to support indexedDB because it wont accept setTimeout() // (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) . // This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45 // // This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since // the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise. // // In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another // tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use // another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick // engine that is used instead of setImmediate() or setTimeout(). // Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible. // Also with inspiration from bluebird, asyncronic stacks in debug mode. // // Specific non-standard features of this Promise class: // * Async static context support (Promise.PSD) // * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame // and below + all promises that those promises creates or awaits. // * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). // // David Fahlander, https://github.com/dfahlander // // Just a pointer that only this module knows about. // Used in Promise constructor to emulate a private constructor. var INTERNAL = {}; // Async stacks (long stacks) must not grow infinitely. var LONG_STACKS_CLIP_LIMIT = 100; var MAX_LONG_STACKS = 20; var stack_being_generated = false; /* The default "nextTick" function used only for the very first promise in a promise chain. As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks emulated in this module. For indexedDB compatibility, this means that every method needs to execute at least one promise before doing an indexedDB operation. Dexie will always call db.ready().then() for every operation to make sure the indexedDB event is started in an emulated micro tick. */ var schedulePhysicalTick = _global.setImmediate ? // setImmediate supported. Those modern platforms also supports Function.bind(). setImmediate.bind(null, physicalTick) : _global.MutationObserver ? // MutationObserver supported function () { var hiddenDiv = document.createElement("div"); new MutationObserver(function () { physicalTick(); hiddenDiv = null; }).observe(hiddenDiv, { attributes: true }); hiddenDiv.setAttribute('i', '1'); } : // No support for setImmediate or MutationObserver. No worry, setTimeout is only called // once time. Every tick that follows will be our emulated micro tick. // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug function () { setTimeout(physicalTick, 0); }; // Confifurable through Promise.scheduler. // Don't export because it would be unsafe to let unknown // code call it unless they do try..catch within their callback. // This function can be retrieved through getter of Promise.scheduler though, // but users must not do Promise.scheduler (myFuncThatThrows exception)! var asap$1 = function (callback, args) { microtickQueue.push([callback, args]); if (needsNewPhysicalTick) { schedulePhysicalTick(); needsNewPhysicalTick = false; } }; var isOutsideMicroTick = true; var needsNewPhysicalTick = true; var unhandledErrors = []; var rejectingErrors = []; var currentFulfiller = null; var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions var globalPSD = { global: true, ref: 0, unhandleds: [], onunhandled: globalError, //env: null, // Will be set whenever leaving a scope using wrappers.snapshot() finalize: function () { this.unhandleds.forEach(function (uh) { try { globalError(uh[0], uh[1]); } catch (e) {} }); } }; var PSD = globalPSD; var microtickQueue = []; // Callbacks to call in this or next physical tick. var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick. // Wrappers are not being used yet. Their framework is functioning and can be used // to replace environment during a PSD scope (a.k.a. 'zone'). /* **KEEP** export var wrappers = (() => { var wrappers = []; return { snapshot: () => { var i = wrappers.length, result = new Array(i); while (i--) result[i] = wrappers[i].snapshot(); return result; }, restore: values => { var i = wrappers.length; while (i--) wrappers[i].restore(values[i]); }, wrap: () => wrappers.map(w => w.wrap()), add: wrapper => { wrappers.push(wrapper); } }; })(); */ function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); this._listeners = []; this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler. // A library may set `promise._lib = true;` after promise is created to make resolve() or reject() // execute the microtask engine implicitely within the call to resolve() or reject(). // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack // only contains library code when calling resolve() or reject(). // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from // global scope (event handler, timer etc)! this._lib = false; // Current async scope var psd = this._PSD = PSD; if (debug) { this._stackHolder = getErrorWithStack(); this._prev = null; this._numPrev = 0; // Number of previous promises (for long stacks) linkToPreviousPromise(this, currentFulfiller); } if (typeof fn !== 'function') { if (fn !== INTERNAL) throw new TypeError('Not a function'); // Private constructor (INTERNAL, state, value). // Used internally by Promise.resolve() and Promise.reject(). this._state = arguments[1]; this._value = arguments[2]; if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError(). return; } this._state = null; // null (=pending), false (=rejected) or true (=resolved) this._value = null; // error or result ++psd.ref; // Refcounting current scope executePromiseTask(this, fn); } props(Promise.prototype, { then: function (onFulfilled, onRejected) { var _this = this; var rv = new Promise(function (resolve, reject) { propagateToListener(_this, new Listener(onFulfilled, onRejected, resolve, reject)); }); debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this); return rv; }, _then: function (onFulfilled, onRejected) { // A little tinier version of then() that don't have to create a resulting promise. propagateToListener(this, new Listener(null, null, onFulfilled, onRejected)); }, catch: function (onRejected) { if (arguments.length === 1) return this.then(null, onRejected); // First argument is the Error type to catch var type = arguments[0], handler = arguments[1]; return typeof type === 'function' ? this.then(null, function (err) { return ( // Catching errors by its constructor type (similar to java / c++ / c#) // Sample: promise.catch(TypeError, function (e) { ... }); err instanceof type ? handler(err) : PromiseReject(err) ); }) : this.then(null, function (err) { return ( // Catching errors by the error.name property. Makes sense for indexedDB where error type // is always DOMError but where e.name tells the actual error type. // Sample: promise.catch('ConstraintError', function (e) { ... }); err && err.name === type ? handler(err) : PromiseReject(err) ); }); }, finally: function (onFinally) { return this.then(function (value) { onFinally(); return value; }, function (err) { onFinally(); return PromiseReject(err); }); }, // Deprecate in next major. Needed only for db.on.error. uncaught: function (uncaughtHandler) { var _this2 = this; // Be backward compatible and use "onuncatched" as the event name on this. // Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops. this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler); // In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not // a previous promise. Reason: the prevous promise may lack onuncatched handler. if (this._state === false && unhandledErrors.indexOf(this) === -1) { // Replace unhandled error's destinaion promise with this one! unhandledErrors.some(function (p, i, l) { return p._value === _this2._value && (l[i] = _this2); }); // Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could // take away this piece of code as well as the onuncatched and uncaught() method. } return this; }, stack: { get: function () { if (this._stack) return this._stack; try { stack_being_generated = true; var stacks = getStack(this, [], MAX_LONG_STACKS); var stack = stacks.join("\nFrom previous: "); if (this._state !== null) this._stack = stack; // Stack may be updated on reject. return stack; } finally { stack_being_generated = false; } } } }); function Listener(onFulfilled, onRejected, resolve, reject) { this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.resolve = resolve; this.reject = reject; this.psd = PSD; } // Promise Static Properties props(Promise, { all: function () { var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like. return new Promise(function (resolve, reject) { if (values.length === 0) resolve([]); var remaining = values.length; values.forEach(function (a, i) { return Promise.resolve(a).then(function (x) { values[i] = x; if (! --remaining) resolve(values); }, reject); }); }); }, resolve: function (value) { if (value instanceof Promise) return value; if (value && typeof value.then === 'function') return new Promise(function (resolve, reject) { value.then(resolve, reject); }); return new Promise(INTERNAL, true, value); }, reject: PromiseReject, race: function () { var values = getArrayOf.apply(null, arguments); return new Promise(function (resolve, reject) { values.map(function (value) { return Promise.resolve(value).then(resolve, reject); }); }); }, PSD: { get: function () { return PSD; }, set: function (value) { return PSD = value; } }, newPSD: newScope, usePSD: usePSD, scheduler: { get: function () { return asap$1; }, set: function (value) { asap$1 = value; } }, rejectionMapper: { get: function () { return rejectionMapper; }, set: function (value) { rejectionMapper = value; } // Map reject failures }, follow: function (fn) { return new Promise(function (resolve, reject) { return newScope(function (resolve, reject) { var psd = PSD; psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize() psd.onunhandled = reject; // Triggered directly on unhandled promises of this library. psd.finalize = callBoth(function () { var _this3 = this; // Unhandled standard or 3rd part promises are put in PSD.unhandleds and // examined upon scope completion while unhandled rejections in this Promise // will trigger directly through psd.onunhandled run_at_end_of_this_or_next_physical_tick(function () { _this3.unhandleds.length === 0 ? resolve() : reject(_this3.unhandleds[0]); }); }, psd.finalize); fn(); }, resolve, reject); }); }, on: Events(null, { "error": [reverseStoppableEventChain, defaultErrorHandler] // Default to defaultErrorHandler }) }); var PromiseOnError = Promise.on.error; PromiseOnError.subscribe = deprecated("Promise.on('error')", PromiseOnError.subscribe); PromiseOnError.unsubscribe = deprecated("Promise.on('error').unsubscribe", PromiseOnError.unsubscribe); /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function executePromiseTask(promise, fn) { // Promise Resolution Procedure: // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure try { fn(function (value) { if (promise._state !== null) return; if (value === promise) throw new TypeError('A promise cannot be resolved with itself.'); var shouldExecuteTick = promise._lib && beginMicroTickScope(); if (value && typeof value.then === 'function') { executePromiseTask(promise, function (resolve, reject) { value instanceof Promise ? value._then(resolve, reject) : value.then(resolve, reject); }); } else { promise._state = true; promise._value = value; propagateAllListeners(promise); } if (shouldExecuteTick) endMicroTickScope(); }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below } catch (ex) { handleRejection(promise, ex); } } function handleRejection(promise, reason) { rejectingErrors.push(reason); if (promise._state !== null) return; var shouldExecuteTick = promise._lib && beginMicroTickScope(); reason = rejectionMapper(reason); promise._state = false; promise._value = reason; debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(function () { var origProp = getPropertyDescriptor(reason, "stack"); reason._promise = promise; setProp(reason, "stack", { get: function () { return stack_being_generated ? origProp && (origProp.get ? origProp.get.apply(reason) : origProp.value) : promise.stack; } }); }); // Add the failure to a list of possibly uncaught errors addPossiblyUnhandledError(promise); propagateAllListeners(promise); if (shouldExecuteTick) endMicroTickScope(); } function propagateAllListeners(promise) { //debug && linkToPreviousPromise(promise); var listeners = promise._listeners; promise._listeners = []; for (var i = 0, len = listeners.length; i < len; ++i) { propagateToListener(promise, listeners[i]); } var psd = promise._PSD; --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize(); if (numScheduledCalls === 0) { // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call, // and that no deferreds where listening to this rejection or success. // Since there is a risk that our stack can contain application code that may // do stuff after this code is finished that may generate new calls, we cannot // call finalizers here. ++numScheduledCalls; asap$1(function () { if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors }, []); } } function propagateToListener(promise, listener) { if (promise._state === null) { promise._listeners.push(listener); return; } var cb = promise._state ? listener.onFulfilled : listener.onRejected; if (cb === null) { // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch() return (promise._state ? listener.resolve : listener.reject)(promise._value); } var psd = listener.psd; ++psd.ref; ++numScheduledCalls; asap$1(callListener, [cb, promise, listener]); } function callListener(cb, promise, listener) { var outerScope = PSD; var psd = listener.psd; try { if (psd !== outerScope) { // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment. PSD = psd; // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. } // Set static variable currentFulfiller to the promise that is being fullfilled, // so that we connect the chain of promises (for long stacks support) currentFulfiller = promise; // Call callback and resolve our listener with it's return value. var value = promise._value, ret; if (promise._state) { ret = cb(value); } else { if (rejectingErrors.length) rejectingErrors = []; ret = cb(value); if (rejectingErrors.indexOf(value) === -1) markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise. } listener.resolve(ret); } catch (e) { // Exception thrown in callback. Reject our listener. listener.reject(e); } finally { // Restore PSD, env and currentFulfiller. if (psd !== outerScope) { PSD = outerScope; // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment } currentFulfiller = null; if (--numScheduledCalls === 0) finalizePhysicalTick(); --psd.ref || psd.finalize(); } } function getStack(promise, stacks, limit) { if (stacks.length === limit) return stacks; var stack = ""; if (promise._state === false) { var failure = promise._value, errorName, message; if (failure != null) { errorName = failure.name || "Error"; message = failure.message || failure; stack = prettyStack(failure, 0); } else { errorName = failure; // If error is undefined or null, show that. message = ""; } stacks.push(errorName + (message ? ": " + message : "") + stack); } if (debug) { stack = prettyStack(promise._stackHolder, 2); if (stack && stacks.indexOf(stack) === -1) stacks.push(stack); if (promise._prev) getStack(promise._prev, stacks, limit); } return stacks; } function linkToPreviousPromise(promise, prev) { // Support long stacks by linking to previous completed promise. var numPrev = prev ? prev._numPrev + 1 : 0; if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming "tail". promise._prev = prev; promise._numPrev = numPrev; } } /* The callback to schedule with setImmediate() or setTimeout(). It runs a virtual microtick and executes any callback registered in microtickQueue. */ function physicalTick() { beginMicroTickScope() && endMicroTickScope(); } function beginMicroTickScope() { var wasRootExec = isOutsideMicroTick; isOutsideMicroTick = false; needsNewPhysicalTick = false; return wasRootExec; } /* Executes micro-ticks without doing try..catch. This can be possible because we only use this internally and the registered functions are exception-safe (they do try..catch internally before calling any external method). If registering functions in the microtickQueue that are not exception-safe, this would destroy the framework and make it instable. So we don't export our asap method. */ function endMicroTickScope() { var callbacks, i, l; do { while (microtickQueue.length > 0) { callbacks = microtickQueue; microtickQueue = []; l = callbacks.length; for (i = 0; i < l; ++i) { var item = callbacks[i]; item[0].apply(null, item[1]); } } } while (microtickQueue.length > 0); isOutsideMicroTick = true; needsNewPhysicalTick = true; } function finalizePhysicalTick() { var unhandledErrs = unhandledErrors; unhandledErrors = []; unhandledErrs.forEach(function (p) { p._PSD.onunhandled.call(null, p._value, p); }); var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list. var i = finalizers.length; while (i) { finalizers[--i](); } } function run_at_end_of_this_or_next_physical_tick(fn) { function finalizer() { fn(); tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); } tickFinalizers.push(finalizer); ++numScheduledCalls; asap$1(function () { if (--numScheduledCalls === 0) finalizePhysicalTick(); }, []); } function addPossiblyUnhandledError(promise) { // Only add to unhandledErrors if not already there. The first one to add to this list // will be upon the first rejection so that the root cause (first promise in the // rejection chain) is the one listed. if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) unhandledErrors.push(promise); } function markErrorAsHandled(promise) { // Called when a reject handled is actually being called. // Search in unhandledErrors for any promise whos _value is this promise_value (list // contains only rejected promises, and only one item per error) var i = unhandledErrors.length; while (i) { if (unhandledErrors[--i]._value === promise._value) { // Found a promise that failed with this same error object pointer, // Remove that since there is a listener that actually takes care of it. unhandledErrors.splice(i, 1); return; } } } // By default, log uncaught errors to the console function defaultErrorHandler(e) { console.warn('Unhandled rejection: ' + (e.stack || e)); } function PromiseReject(reason) { return new Promise(INTERNAL, false, reason); } function wrap(fn, errorCatcher) { var psd = PSD; return function () { var wasRootExec = beginMicroTickScope(), outerScope = PSD; try { if (outerScope !== psd) { // **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment PSD = psd; // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. } return fn.apply(this, arguments); } catch (e) { errorCatcher && errorCatcher(e); } finally { if (outerScope !== psd) { PSD = outerScope; // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment } if (wasRootExec) endMicroTickScope(); } }; } function newScope(fn, a1, a2, a3) { var parent = PSD, psd = Object.create(parent); psd.parent = parent; psd.ref = 0; psd.global = false; // **KEEP** psd.env = wrappers.wrap(psd); // unhandleds and onunhandled should not be specifically set here. // Leave them on parent prototype. // unhandleds.push(err) will push to parent's prototype // onunhandled() will call parents onunhandled (with this scope's this-pointer though!) ++parent.ref; psd.finalize = function () { --this.parent.ref || this.parent.finalize(); }; var rv = usePSD(psd, fn, a1, a2, a3); if (psd.ref === 0) psd.finalize(); return rv; } function usePSD(psd, fn, a1, a2, a3) { var outerScope = PSD; try { if (psd !== outerScope) { // **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment. PSD = psd; // **KEEP** wrappers.restore(psd.env); // Restore PSD's environment. } return fn(a1, a2, a3); } finally { if (psd !== outerScope) { PSD = outerScope; // **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment. } } } var UNHANDLEDREJECTION = "unhandledrejection"; function globalError(err, promise) { var rv; try { rv = promise.onuncatched(err); } catch (e) {} if (rv !== false) try { var event, eventData = { promise: promise, reason: err }; if (_global.document && document.createEvent) { event = document.createEvent('Event'); event.initEvent(UNHANDLEDREJECTION, true, true); extend(event, eventData); } else if (_global.CustomEvent) { event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData }); extend(event, eventData); } if (event && _global.dispatchEvent) { dispatchEvent(event); if (!_global.PromiseRejectionEvent && _global.onunhandledrejection) // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it. try { _global.onunhandledrejection(event); } catch (_) {} } if (!event.defaultPrevented) { // Backward compatibility: fire to events registered at Promise.on.error Promise.on.error.fire(err, promise); } } catch (e) {} } /* **KEEP** export function wrapPromise(PromiseClass) { var proto = PromiseClass.prototype; var origThen = proto.then; wrappers.add({ snapshot: () => proto.then, restore: value => {proto.then = value;}, wrap: () => patchedThen }); function patchedThen (onFulfilled, onRejected) { var promise = this; var onFulfilledProxy = wrap(function(value){ var rv = value; if (onFulfilled) { rv = onFulfilled(rv); if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. } --PSD.ref || PSD.finalize(); return rv; }); var onRejectedProxy = wrap(function(err){ promise._$err = err; var unhandleds = PSD.unhandleds; var idx = unhandleds.length, rv; while (idx--) if (unhandleds[idx]._$err === err) break; if (onRejected) { if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled. rv = onRejected(err); if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well. } else { if (idx === -1) unhandleds.push(promise); rv = PromiseClass.reject(err); rv._$nointercept = true; // Prohibit eternal loop. } --PSD.ref || PSD.finalize(); return rv; }); if (this._$nointercept) return origThen.apply(this, arguments); ++PSD.ref; return origThen.call(this, onFulfilledProxy, onRejectedProxy); } } // Global Promise wrapper if (_global.Promise) wrapPromise(_global.Promise); */ doFakeAutoComplete(function () { // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie. asap$1 = function (fn, args) { setTimeout(function () { fn.apply(null, args); }, 0); }; }); function rejection(err, uncaughtHandler) { // Get the call stack and return a rejected promise. var rv = Promise.reject(err); return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv; } /* * Dexie.js - a minimalistic wrapper for IndexedDB * =============================================== * * By David Fahlander, david.fahlander@gmail.com * * Version 1.5.1, Tue Nov 01 2016 * * http://dexie.org * * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ */ var DEXIE_VERSION = '1.5.1'; var maxString = String.fromCharCode(65535); var maxKey = function () { try { IDBKeyRange.only([[]]);return [[]]; } catch (e) { return maxString; } }(); var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; var STRING_EXPECTED = "String expected."; var connections = []; var isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent); var hasIEDeleteObjectStoreBug = isIEOrEdge; var hangsOnDeleteLargeKeyRange = isIEOrEdge; var dexieStackFrameFilter = function (frame) { return !/(dexie\.js|dexie\.min\.js)/.test(frame); }; setDebug(debug, dexieStackFrameFilter); function Dexie(dbName, options) { /// Specify only if you wich to control which addons that should run on this instance var deps = Dexie.dependencies; var opts = extend({ // Default Options addons: Dexie.addons, // Pick statically registered addons by default autoOpen: true, // Don't require db.open() explicitely. indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env. IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env. }, options); var addons = opts.addons, autoOpen = opts.autoOpen, indexedDB = opts.indexedDB, IDBKeyRange = opts.IDBKeyRange; var globalSchema = this._dbSchema = {}; var versions = []; var dbStoreNames = []; var allTables = {}; /// var idbdb = null; // Instance of IDBDatabase var dbOpenError = null; var isBeingOpened = false; var openComplete = false; var READONLY = "readonly", READWRITE = "readwrite"; var db = this; var dbReadyResolve, dbReadyPromise = new Promise(function (resolve) { dbReadyResolve = resolve; }), cancelOpen, openCanceller = new Promise(function (_, reject) { cancelOpen = reject; }); var autoSchema = true; var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB), hasGetAll; function init() { // Default subscribers to "versionchange" and "blocked". // Can be overridden by custom handlers. If custom handlers return false, these default // behaviours will be prevented. db.on("versionchange", function (ev) { // Default behavior for versionchange event is to close database connection. // Caller can override this behavior by doing db.on("versionchange", function(){ return false; }); // Let's not block the other window from making it's delete() or open() call. // NOTE! This event is never fired in IE,Edge or Safari. if (ev.newVersion > 0) console.warn('Another connection wants to upgrade database \'' + db.name + '\'. Closing db now to resume the upgrade.');else console.warn('Another connection wants to delete database \'' + db.name + '\'. Closing db now to resume the delete request.'); db.close(); // In many web applications, it would be recommended to force window.reload() // when this event occurs. To do that, subscribe to the versionchange event // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion) // The reason for this is that your current web app obviously has old schema code that needs // to be updated. Another window got a newer version of the app and needs to upgrade DB but // your window is blocking it unless we close it here. }); db.on("blocked", function (ev) { if (!ev.newVersion || ev.newVersion < ev.oldVersion) console.warn('Dexie.delete(\'' + db.name + '\') was blocked');else console.warn('Upgrade \'' + db.name + '\' blocked by other connection holding version ' + ev.oldVersion / 10); }); } // // // // ------------------------- Versioning Framework--------------------------- // // // this.version = function (versionNumber) { /// /// if (idbdb || isBeingOpened) throw new exceptions.Schema("Cannot add version when database is open"); this.verno = Math.max(this.verno, versionNumber); var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; if (versionInstance) return versionInstance; versionInstance = new Version(versionNumber); versions.push(versionInstance); versions.sort(lowerVersionFirst); return versionInstance; }; function Version(versionNumber) { this._cfg = { version: versionNumber, storesSource: null, dbschema: {}, tables: {}, contentUpgrade: null }; this.stores({}); // Derive earlier schemas by default. } extend(Version.prototype, { stores: function (stores) { /// /// Defines the schema for a particular version /// /// /// Example:
/// {users: "id++,first,last,&username,*email",
/// passwords: "id++,&username"}
///
/// Syntax: {Table: "[primaryKey][++],[&][*]index1,[&][*]index2,..."}

/// Special characters:
/// "&" means unique key,
/// "*" means value is multiEntry,
/// "++" means auto-increment and only applicable for primary key
/// this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax. var storesSpec = {}; versions.forEach(function (version) { // 'versions' is always sorted by lowest version first. extend(storesSpec, version._cfg.storesSource); }); var dbschema = this._cfg.dbschema = {}; this._parseStoresSpec(storesSpec, dbschema); // Update the latest schema to this version // Update API globalSchema = db._dbSchema = dbschema; removeTablesApi([allTables, db, Transaction.prototype]); setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema); dbStoreNames = keys(dbschema); return this; }, upgrade: function (upgradeFunction) { /// Function that performs upgrading actions. var self = this; fakeAutoComplete(function () { upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema)); // BUGBUG: No code completion for prev version's tables wont appear. }); this._cfg.contentUpgrade = upgradeFunction; return this; }, _parseStoresSpec: function (stores, outSchema) { keys(stores).forEach(function (tableName) { if (stores[tableName] !== null) { var instanceTemplate = {}; var indexes = parseIndexSyntax(stores[tableName]); var primKey = indexes.shift(); if (primKey.multi) throw new exceptions.Schema("Primary key cannot be multi-valued"); if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath); indexes.forEach(function (idx) { if (idx.auto) throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); if (!idx.keyPath) throw new exceptions.Schema("Index must have a name and cannot be an empty string"); setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return ""; }) : ""); }); outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate); } }); } }); function runUpgraders(oldVersion, idbtrans, reject) { var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema); trans.create(idbtrans); trans._completion.catch(reject); var rejectTransaction = trans._reject.bind(trans); newScope(function () { PSD.trans = trans; if (oldVersion === 0) { // Create tables: keys(globalSchema).forEach(function (tableName) { createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); }); Promise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); } else updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction); }); } function updateTablesAndIndexes(oldVersion, trans, idbtrans) { // Upgrade version to version, step-by-step from oldest to newest version. // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version) var queue = []; var oldVersionStruct = versions.filter(function (version) { return version._cfg.version === oldVersion; })[0]; if (!oldVersionStruct) throw new exceptions.Upgrade("Dexie specification of currently installed DB version is missing"); globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema; var anyContentUpgraderHasRun = false; var versToRun = versions.filter(function (v) { return v._cfg.version > oldVersion; }); versToRun.forEach(function (version) { /// queue.push(function () { var oldSchema = globalSchema; var newSchema = version._cfg.dbschema; adjustToExistingIndexNames(oldSchema, idbtrans); adjustToExistingIndexNames(newSchema, idbtrans); globalSchema = db._dbSchema = newSchema; var diff = getSchemaDiff(oldSchema, newSchema); // Add tables diff.add.forEach(function (tuple) { createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes); }); // Change tables diff.change.forEach(function (change) { if (change.recreate) { throw new exceptions.Upgrade("Not yet support for changing primary key"); } else { var store = idbtrans.objectStore(change.name); // Add indexes change.add.forEach(function (idx) { addIndex(store, idx); }); // Update indexes change.change.forEach(function (idx) { store.deleteIndex(idx.name); addIndex(store, idx); }); // Delete indexes change.del.forEach(function (idxName) { store.deleteIndex(idxName); }); } }); if (version._cfg.contentUpgrade) { anyContentUpgraderHasRun = true; return Promise.follow(function () { version._cfg.contentUpgrade(trans); }); } }); queue.push(function (idbtrans) { if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of. var newSchema = version._cfg.dbschema; // Delete old tables deleteRemovedTables(newSchema, idbtrans); } }); }); // Now, create a queue execution engine function runQueue() { return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : Promise.resolve(); } return runQueue().then(function () { createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version) }); } function getSchemaDiff(oldSchema, newSchema) { var diff = { del: [], // Array of table names add: [], // Array of [tableName, newDefinition] change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs} }; for (var table in oldSchema) { if (!newSchema[table]) diff.del.push(table); } for (table in newSchema) { var oldDef = oldSchema[table], newDef = newSchema[table]; if (!oldDef) { diff.add.push([table, newDef]); } else { var change = { name: table, def: newDef, recreate: false, del: [], add: [], change: [] }; if (oldDef.primKey.src !== newDef.primKey.src) { // Primary key has changed. Remove and re-add table. change.recreate = true; diff.change.push(change); } else { // Same primary key. Just find out what differs: var oldIndexes = oldDef.idxByName; var newIndexes = newDef.idxByName; for (var idxName in oldIndexes) { if (!newIndexes[idxName]) change.del.push(idxName); } for (idxName in newIndexes) { var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; if (!oldIdx) change.add.push(newIdx);else if (oldIdx.src !== newIdx.src) change.change.push(newIdx); } if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { diff.change.push(change); } } } } return diff; } function createTable(idbtrans, tableName, primKey, indexes) { /// var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); indexes.forEach(function (idx) { addIndex(store, idx); }); return store; } function createMissingTables(newSchema, idbtrans) { keys(newSchema).forEach(function (tableName) { if (!idbtrans.db.objectStoreNames.contains(tableName)) { createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); } }); } function deleteRemovedTables(newSchema, idbtrans) { for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) { var storeName = idbtrans.db.objectStoreNames[i]; if (newSchema[storeName] == null) { idbtrans.db.deleteObjectStore(storeName); } } } function addIndex(store, idx) { store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); } function dbUncaught(err) { return db.on.error.fire(err); } // // // Dexie Protected API // // this._allTables = allTables; this._tableFactory = function createTable(mode, tableSchema) { /// if (mode === READONLY) return new Table(tableSchema.name, tableSchema, Collection);else return new WriteableTable(tableSchema.name, tableSchema); }; this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new Transaction(mode, storeNames, dbschema, parentTransaction); }; /* Generate a temporary transaction when db operations are done outside a transactino scope. */ function tempTransaction(mode, storeNames, fn) { // Last argument is "writeLocked". But this doesnt apply to oneshot direct db operations, so we ignore it. if (!openComplete && !PSD.letThrough) { if (!isBeingOpened) { if (!autoOpen) return rejection(new exceptions.DatabaseClosed(), dbUncaught); db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. } return dbReadyPromise.then(function () { return tempTransaction(mode, storeNames, fn); }); } else { var trans = db._createTransaction(mode, storeNames, globalSchema); return trans._promise(mode, function (resolve, reject) { newScope(function () { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise. PSD.trans = trans; fn(resolve, reject, trans); }); }).then(function (result) { // Instead of resolving value directly, wait with resolving it until transaction has completed. // Otherwise the data would not be in the DB if requesting it in the then() operation. // Specifically, to ensure that the following expression will work: // // db.friends.put({name: "Arne"}).then(function () { // db.friends.where("name").equals("Arne").count(function(count) { // assert (count === 1); // }); // }); // return trans._completion.then(function () { return result; }); }); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major. trans._reject(err); return rejection(err); });*/ } } this._whenReady = function (fn) { return new Promise(fake || openComplete || PSD.letThrough ? fn : function (resolve, reject) { if (!isBeingOpened) { if (!autoOpen) { reject(new exceptions.DatabaseClosed()); return; } db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. } dbReadyPromise.then(function () { fn(resolve, reject); }); }).uncaught(dbUncaught); }; // // // // // Dexie API // // // this.verno = 0; this.open = function () { if (isBeingOpened || idbdb) return dbReadyPromise.then(function () { return dbOpenError ? rejection(dbOpenError, dbUncaught) : db; }); debug && (openCanceller._stackHolder = getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called. isBeingOpened = true; dbOpenError = null; openComplete = false; // Function pointers to call when the core opening process completes. var resolveDbReady = dbReadyResolve, // upgradeTransaction to abort on failure. upgradeTransaction = null; return Promise.race([openCanceller, new Promise(function (resolve, reject) { doFakeAutoComplete(function () { return resolve(); }); // Make sure caller has specified at least one version if (versions.length > 0) autoSchema = false; // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE: // IE fails when deleting objectStore after reading from it. // A future version of Dexie.js will stopover an intermediate version to workaround this. // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number. // If no API, throw! if (!indexedDB) throw new exceptions.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL " + "(not locally). If using old Safari versions, make sure to include indexedDB polyfill."); var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10)); if (!req) throw new exceptions.MissingAPI("IndexedDB API not available"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134 req.onerror = wrap(eventRejectHandler(reject)); req.onblocked = wrap(fireOnBlocked); req.onupgradeneeded = wrap(function (e) { upgradeTransaction = req.transaction; if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail. // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases. // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we // do not create a new database by accident here. req.onerror = preventDefault; // Prohibit onabort error from firing before we're done! upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.) // Close database and delete it. req.result.close(); var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here! delreq.onsuccess = delreq.onerror = wrap(function () { reject(new exceptions.NoSuchDatabase('Database ' + dbName + ' doesnt exist')); }); } else { upgradeTransaction.onerror = wrap(eventRejectHandler(reject)); var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix. runUpgraders(oldVer / 10, upgradeTransaction, reject, req); } }, reject); req.onsuccess = wrap(function () { // Core opening procedure complete. Now let's just record some stuff. upgradeTransaction = null; idbdb = req.result; connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari. if (autoSchema) readGlobalSchema();else if (idbdb.objectStoreNames.length > 0) { try { adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY)); } catch (e) { // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120. } } idbdb.onversionchange = wrap(function (ev) { db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari) db.on("versionchange").fire(ev); }); if (!hasNativeGetDatabaseNames) { // Update localStorage with list of database names globalDatabaseList(function (databaseNames) { if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName); }); } resolve(); }, reject); })]).then(function () { // Before finally resolving the dbReadyPromise and this promise, // call and await all on('ready') subscribers: // Dexie.vip() makes subscribers able to use the database while being opened. // This is a must since these subscribers take part of the opening procedure. return Dexie.vip(db.on.ready.fire); }).then(function () { // Resolve the db.open() with the db instance. isBeingOpened = false; return db; }).catch(function (err) { try { // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit. upgradeTransaction && upgradeTransaction.abort(); } catch (e) {} isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event). db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh. // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that. dbOpenError = err; // Record the error. It will be used to reject further promises of db operations. return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught(). }).finally(function () { openComplete = true; resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters. }); }; this.close = function () { var idx = connections.indexOf(db); if (idx >= 0) connections.splice(idx, 1); if (idbdb) { try { idbdb.close(); } catch (e) {} idbdb = null; } autoOpen = false; dbOpenError = new exceptions.DatabaseClosed(); if (isBeingOpened) cancelOpen(dbOpenError); // Reset dbReadyPromise promise: dbReadyPromise = new Promise(function (resolve) { dbReadyResolve = resolve; }); openCanceller = new Promise(function (_, reject) { cancelOpen = reject; }); }; this.delete = function () { var hasArguments = arguments.length > 0; return new Promise(function (resolve, reject) { if (hasArguments) throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); if (isBeingOpened) { dbReadyPromise.then(doDelete); } else { doDelete(); } function doDelete() { db.close(); var req = indexedDB.deleteDatabase(dbName); req.onsuccess = wrap(function () { if (!hasNativeGetDatabaseNames) { globalDatabaseList(function (databaseNames) { var pos = databaseNames.indexOf(dbName); if (pos >= 0) return databaseNames.splice(pos, 1); }); } resolve(); }); req.onerror = wrap(eventRejectHandler(reject)); req.onblocked = fireOnBlocked; } }).uncaught(dbUncaught); }; this.backendDB = function () { return idbdb; }; this.isOpen = function () { return idbdb !== null; }; this.hasFailed = function () { return dbOpenError !== null; }; this.dynamicallyOpened = function () { return autoSchema; }; // // Properties // this.name = dbName; // db.tables - an array of all Table instances. setProp(this, "tables", { get: function () { /// return keys(allTables).map(function (name) { return allTables[name]; }); } }); // // Events // this.on = Events(this, "error", "populate", "blocked", "versionchange", { ready: [promisableChain, nop] }); this.on.error.subscribe = deprecated("Dexie.on.error", this.on.error.subscribe); this.on.error.unsubscribe = deprecated("Dexie.on.error.unsubscribe", this.on.error.unsubscribe); this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { return function (subscriber, bSticky) { Dexie.vip(function () { if (openComplete) { // Database already open. Call subscriber asap. if (!dbOpenError) Promise.resolve().then(subscriber); // bSticky: Also subscribe to future open sucesses (after close / reopen) if (bSticky) subscribe(subscriber); } else { // Database not yet open. Subscribe to it. subscribe(subscriber); // If bSticky is falsy, make sure to unsubscribe subscriber when fired once. if (!bSticky) subscribe(function unsubscribe() { db.on.ready.unsubscribe(subscriber); db.on.ready.unsubscribe(unsubscribe); }); } }); }; }); fakeAutoComplete(function () { db.on("populate").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema)); db.on("error").fire(new Error()); }); this.transaction = function (mode, tableInstances, scopeFunc) { /// /// /// /// "r" for readonly, or "rw" for readwrite /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction /// Function to execute with transaction // Let table arguments be all arguments between mode and last argument. var i = arguments.length; if (i < 2) throw new exceptions.InvalidArgument("Too few arguments"); // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments) // and clone arguments except the first one into local var 'args'. var args = new Array(i - 1); while (--i) { args[i - 1] = arguments[i]; } // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments. scopeFunc = args.pop(); var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays. var parentTransaction = PSD.trans; // Check if parent transactions is bound to this db instance, and if caller wants to reuse it if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null; var onlyIfCompatible = mode.indexOf('?') !== -1; mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth. try { // // Get storeNames from arguments. Either through given table instances, or through given table names. // var storeNames = tables.map(function (table) { var storeName = table instanceof Table ? table.name : table; if (typeof storeName !== 'string') throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); return storeName; }); // // Resolve mode. Allow shortcuts "r" and "rw". // if (mode == "r" || mode == READONLY) mode = READONLY;else if (mode == "rw" || mode == READWRITE) mode = READWRITE;else throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); if (parentTransaction) { // Basic checks if (parentTransaction.mode === READONLY && mode === READWRITE) { if (onlyIfCompatible) { // Spawn new transaction instead. parentTransaction = null; } else throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); } if (parentTransaction) { storeNames.forEach(function (storeName) { if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { if (onlyIfCompatible) { // Spawn new transaction instead. parentTransaction = null; } else throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction."); } }); } } } catch (e) { return parentTransaction ? parentTransaction._promise(null, function (_, reject) { reject(e); }) : rejection(e, dbUncaught); } // If this is a sub-transaction, lock the parent and then launch the sub-transaction. return parentTransaction ? parentTransaction._promise(mode, enterTransactionScope, "lock") : db._whenReady(enterTransactionScope); function enterTransactionScope(resolve) { var parentPSD = PSD; resolve(Promise.resolve().then(function () { return newScope(function () { // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction(). PSD.transless = PSD.transless || parentPSD; // Our transaction. //return new Promise((resolve, reject) => { var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction); // Let the transaction instance be part of a Promise-specific data (PSD) value. PSD.trans = trans; if (parentTransaction) { // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing) trans.idbtrans = parentTransaction.idbtrans; } else { trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it. } // Provide arguments to the scope function (for backward compatibility) var tableArgs = storeNames.map(function (name) { return allTables[name]; }); tableArgs.push(trans); var returnValue; return Promise.follow(function () { // Finally, call the scope function with our table and transaction arguments. returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func. if (returnValue) { if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { // scopeFunc returned an iterator with throw-support. Handle yield as await. returnValue = awaitIterator(returnValue); } else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) { throw new exceptions.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: " + scopeFunc.toString()); } } }).uncaught(dbUncaught).then(function () { if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion. return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well. }).then(function () { return returnValue; }).catch(function (e) { //reject(e); trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc! return rejection(e); }); //}); }); })); } }; this.table = function (tableName) { /// if (fake && autoSchema) return new WriteableTable(tableName); if (!hasOwn(allTables, tableName)) { throw new exceptions.InvalidTable('Table ' + tableName + ' does not exist'); } return allTables[tableName]; }; // // // // Table Class // // // function Table(name, tableSchema, collClass) { /// this.name = name; this.schema = tableSchema; this.hook = allTables[name] ? allTables[name].hook : Events(null, { "creating": [hookCreatingChain, nop], "reading": [pureFunctionChain, mirror], "updating": [hookUpdatingChain, nop], "deleting": [hookDeletingChain, nop] }); this._collClass = collClass || Collection; } props(Table.prototype, { // // Table Protected Methods // _trans: function getTransaction(mode, fn, writeLocked) { var trans = PSD.trans; return trans && trans.db === db ? trans._promise(mode, fn, writeLocked) : tempTransaction(mode, [this.name], fn); }, _idbstore: function getIDBObjectStore(mode, fn, writeLocked) { if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion. var trans = PSD.trans, tableName = this.name; function supplyIdbStore(resolve, reject, trans) { fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans); } return trans && trans.db === db ? trans._promise(mode, supplyIdbStore, writeLocked) : tempTransaction(mode, [this.name], supplyIdbStore); }, // // Table Public Methods // get: function (key, cb) { var self = this; return this._idbstore(READONLY, function (resolve, reject, idbstore) { fake && resolve(self.schema.instanceTemplate); var req = idbstore.get(key); req.onerror = eventRejectHandler(reject); req.onsuccess = wrap(function () { resolve(self.hook.reading.fire(req.result)); }, reject); }).then(cb); }, where: function (indexName) { return new WhereClause(this, indexName); }, count: function (cb) { return this.toCollection().count(cb); }, offset: function (offset) { return this.toCollection().offset(offset); }, limit: function (numRows) { return this.toCollection().limit(numRows); }, reverse: function () { return this.toCollection().reverse(); }, filter: function (filterFunction) { return this.toCollection().and(filterFunction); }, each: function (fn) { return this.toCollection().each(fn); }, toArray: function (cb) { return this.toCollection().toArray(cb); }, orderBy: function (index) { return new this._collClass(new WhereClause(this, index)); }, toCollection: function () { return new this._collClass(new WhereClause(this)); }, mapToClass: function (constructor, structure) { /// /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}. /// /// Constructor function representing the class. /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also /// know what type each member has. Example: {name: String, emailAddresses: [String], password} this.schema.mappedClass = constructor; var instanceTemplate = Object.create(constructor.prototype); if (structure) { // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance. applyStructure(instanceTemplate, structure); } this.schema.instanceTemplate = instanceTemplate; // Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class // no matter which method to use for reading (Table.get() or Table.where(...)... ) var readHook = function (obj) { if (!obj) return obj; // No valid object. (Value is null). Return as is. // Create a new object that derives from constructor: var res = Object.create(constructor.prototype); // Clone members: for (var m in obj) { if (hasOwn(obj, m)) try { res[m] = obj[m]; } catch (_) {} }return res; }; if (this.schema.readHook) { this.hook.reading.unsubscribe(this.schema.readHook); } this.schema.readHook = readHook; this.hook("reading", readHook); return constructor; }, defineClass: function (structure) { /// /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database /// as well as making it possible to extend the prototype of the returned constructor function. /// /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} return this.mapToClass(Dexie.defineClass(structure), structure); } }); // // // // WriteableTable Class (extends Table) // // // function WriteableTable(name, tableSchema, collClass) { Table.call(this, name, tableSchema, collClass || WriteableCollection); } function BulkErrorHandlerCatchAll(errorList, done, supportHooks) { return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(function (e) { errorList.push(e); done && done(); }); } function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) { // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...], // else keysOrTuples must be just an array of keys: [key1, key2, ...]. return new Promise(function (resolve, reject) { var len = keysOrTuples.length, lastItem = len - 1; if (len === 0) return resolve(); if (!hasDeleteHook) { for (var i = 0; i < len; ++i) { var req = idbstore.delete(keysOrTuples[i]); req.onerror = wrap(eventRejectHandler(reject)); if (i === lastItem) req.onsuccess = wrap(function () { return resolve(); }); } } else { var hookCtx, errorHandler = hookedEventRejectHandler(reject), successHandler = hookedEventSuccessHandler(null); tryCatch(function () { for (var i = 0; i < len; ++i) { hookCtx = { onsuccess: null, onerror: null }; var tuple = keysOrTuples[i]; deletingHook.call(hookCtx, tuple[0], tuple[1], trans); var req = idbstore.delete(tuple[0]); req._hookCtx = hookCtx; req.onerror = errorHandler; if (i === lastItem) req.onsuccess = hookedEventSuccessHandler(resolve);else req.onsuccess = successHandler; } }, function (err) { hookCtx.onerror && hookCtx.onerror(err); throw err; }); } }).uncaught(dbUncaught); } derive(WriteableTable).from(Table).extend({ bulkDelete: function (keys$$1) { if (this.hook.deleting.fire === nop) { return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { resolve(bulkDelete(idbstore, trans, keys$$1, false, nop)); }); } else { return this.where(':id').anyOf(keys$$1).delete().then(function () {}); // Resolve with undefined. } }, bulkPut: function (objects, keys$$1) { var _this = this; return this._idbstore(READWRITE, function (resolve, reject, idbstore) { if (!idbstore.keyPath && !_this.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument"); if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); if (objects.length === 0) return resolve(); // Caller provided empty list. var done = function (result) { if (errorList.length === 0) resolve(result);else reject(new BulkError(_this.name + '.bulkPut(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList)); }; var req, errorList = [], errorHandler, numObjs = objects.length, table = _this; if (_this.hook.creating.fire === nop && _this.hook.updating.fire === nop) { // // Standard Bulk (no 'creating' or 'updating' hooks to care about) // errorHandler = BulkErrorHandlerCatchAll(errorList); for (var i = 0, l = objects.length; i < l; ++i) { req = keys$$1 ? idbstore.put(objects[i], keys$$1[i]) : idbstore.put(objects[i]); req.onerror = errorHandler; } // Only need to catch success or error on the last operation // according to the IDB spec. req.onerror = BulkErrorHandlerCatchAll(errorList, done); req.onsuccess = eventSuccessHandler(done); } else { var effectiveKeys = keys$$1 || idbstore.keyPath && objects.map(function (o) { return getByKeyPath(o, idbstore.keyPath); }); // Generate map of {[key]: object} var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, function (key, i) { return key != null && [key, objects[i]]; }); var promise = !effectiveKeys ? // Auto-incremented key-less objects only without any keys argument. table.bulkAdd(objects) : // Keys provided. Either as inbound in provided objects, or as a keys argument. // Begin with updating those that exists in DB: table.where(':id').anyOf(effectiveKeys.filter(function (key) { return key != null; })).modify(function () { this.value = objectLookup[this.primKey]; objectLookup[this.primKey] = null; // Mark as "don't add this" }).catch(ModifyError, function (e) { errorList = e.failures; // No need to concat here. These are the first errors added. }).then(function () { // Now, let's examine which items didnt exist so we can add them: var objsToAdd = [], keysToAdd = keys$$1 && []; // Iterate backwards. Why? Because if same key was used twice, just add the last one. for (var i = effectiveKeys.length - 1; i >= 0; --i) { var key = effectiveKeys[i]; if (key == null || objectLookup[key]) { objsToAdd.push(objects[i]); keys$$1 && keysToAdd.push(key); if (key != null) objectLookup[key] = null; // Mark as "dont add again" } } // The items are in reverse order so reverse them before adding. // Could be important in order to get auto-incremented keys the way the caller // would expect. Could have used unshift instead of push()/reverse(), // but: http://jsperf.com/unshift-vs-reverse objsToAdd.reverse(); keys$$1 && keysToAdd.reverse(); return table.bulkAdd(objsToAdd, keysToAdd); }).then(function (lastAddedKey) { // Resolve with key of the last object in given arguments to bulkPut(): var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided. return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey; }); promise.then(done).catch(BulkError, function (e) { // Concat failure from ModifyError and reject using our 'done' method. errorList = errorList.concat(e.failures); done(); }).catch(reject); } }, "locked"); // If called from transaction scope, lock transaction til all steps are done. }, bulkAdd: function (objects, keys$$1) { var self = this, creatingHook = this.hook.creating.fire; return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { if (!idbstore.keyPath && !self.schema.primKey.auto && !keys$$1) throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument"); if (idbstore.keyPath && keys$$1) throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); if (keys$$1 && keys$$1.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); if (objects.length === 0) return resolve(); // Caller provided empty list. function done(result) { if (errorList.length === 0) resolve(result);else reject(new BulkError(self.name + '.bulkAdd(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList)); } var req, errorList = [], errorHandler, successHandler, numObjs = objects.length; if (creatingHook !== nop) { // // There are subscribers to hook('creating') // Must behave as documented. // var keyPath = idbstore.keyPath, hookCtx; errorHandler = BulkErrorHandlerCatchAll(errorList, null, true); successHandler = hookedEventSuccessHandler(null); tryCatch(function () { for (var i = 0, l = objects.length; i < l; ++i) { hookCtx = { onerror: null, onsuccess: null }; var key = keys$$1 && keys$$1[i]; var obj = objects[i], effectiveKey = keys$$1 ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined, keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); if (effectiveKey == null && keyToUse != null) { if (keyPath) { obj = deepClone(obj); setByKeyPath(obj, keyPath, keyToUse); } else { key = keyToUse; } } req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); req._hookCtx = hookCtx; if (i < l - 1) { req.onerror = errorHandler; if (hookCtx.onsuccess) req.onsuccess = successHandler; } } }, function (err) { hookCtx.onerror && hookCtx.onerror(err); throw err; }); req.onerror = BulkErrorHandlerCatchAll(errorList, done, true); req.onsuccess = hookedEventSuccessHandler(done); } else { // // Standard Bulk (no 'creating' hook to care about) // errorHandler = BulkErrorHandlerCatchAll(errorList); for (var i = 0, l = objects.length; i < l; ++i) { req = keys$$1 ? idbstore.add(objects[i], keys$$1[i]) : idbstore.add(objects[i]); req.onerror = errorHandler; } // Only need to catch success or error on the last operation // according to the IDB spec. req.onerror = BulkErrorHandlerCatchAll(errorList, done); req.onsuccess = eventSuccessHandler(done); } }); }, add: function (obj, key) { /// /// Add an object to the database. In case an object with same primary key already exists, the object will not be added. /// /// A javascript object to insert /// Primary key var creatingHook = this.hook.creating.fire; return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { var hookCtx = { onsuccess: null, onerror: null }; if (creatingHook !== nop) { var effectiveKey = key != null ? key : idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined; var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key. if (effectiveKey == null && keyToUse != null) { // Using "==" and "!=" to check for either null or undefined! if (idbstore.keyPath) setByKeyPath(obj, idbstore.keyPath, keyToUse);else key = keyToUse; } } try { var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); req._hookCtx = hookCtx; req.onerror = hookedEventRejectHandler(reject); req.onsuccess = hookedEventSuccessHandler(function (result) { // TODO: Remove these two lines in next major release (2.0?) // It's no good practice to have side effects on provided parameters var keyPath = idbstore.keyPath; if (keyPath) setByKeyPath(obj, keyPath, result); resolve(result); }); } catch (e) { if (hookCtx.onerror) hookCtx.onerror(e); throw e; } }); }, put: function (obj, key) { /// /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated. /// /// A javascript object to insert or update /// Primary key var self = this, creatingHook = this.hook.creating.fire, updatingHook = this.hook.updating.fire; if (creatingHook !== nop || updatingHook !== nop) { // // People listens to when("creating") or when("updating") events! // We must know whether the put operation results in an CREATE or UPDATE. // return this._trans(READWRITE, function (resolve, reject, trans) { // Since key is optional, make sure we get it from obj if not provided var effectiveKey = key !== undefined ? key : self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath); if (effectiveKey == null) { // "== null" means checking for either null or undefined. // No primary key. Must use add(). self.add(obj).then(resolve, reject); } else { // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add(). trans._lock(); // Needed because operation is splitted into modify() and add(). // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation. obj = deepClone(obj); self.where(":id").equals(effectiveKey).modify(function () { // Replace extisting value with our object // CRUD event firing handled in WriteableCollection.modify() this.value = obj; }).then(function (count) { if (count === 0) { // Object's key was not found. Add the object instead. // CRUD event firing will be done in add() return self.add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key. } else { return effectiveKey; // Resolve with the provided key. } }).finally(function () { trans._unlock(); }).then(resolve, reject); } }); } else { // Use the standard IDB put() method. return this._idbstore(READWRITE, function (resolve, reject, idbstore) { var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj); req.onerror = eventRejectHandler(reject); req.onsuccess = function (ev) { var keyPath = idbstore.keyPath; if (keyPath) setByKeyPath(obj, keyPath, ev.target.result); resolve(req.result); }; }); } }, 'delete': function (key) { /// Primary key of the object to delete if (this.hook.deleting.subscribers.length) { // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will // call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted. return this.where(":id").equals(key).delete(); } else { // No one listens. Use standard IDB delete() method. return this._idbstore(READWRITE, function (resolve, reject, idbstore) { var req = idbstore.delete(key); req.onerror = eventRejectHandler(reject); req.onsuccess = function () { resolve(req.result); }; }); } }, clear: function () { if (this.hook.deleting.subscribers.length) { // People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will // call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted. return this.toCollection().delete(); } else { return this._idbstore(READWRITE, function (resolve, reject, idbstore) { var req = idbstore.clear(); req.onerror = eventRejectHandler(reject); req.onsuccess = function () { resolve(req.result); }; }); } }, update: function (keyOrObject, modifications) { if (typeof modifications !== 'object' || isArray(modifications)) throw new exceptions.InvalidArgument("Modifications must be an object."); if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { // object to modify. Also modify given object with the modifications: keys(modifications).forEach(function (keyPath) { setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); }); var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); if (key === undefined) return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key"), dbUncaught); return this.where(":id").equals(key).modify(modifications); } else { // key to modify return this.where(":id").equals(keyOrObject).modify(modifications); } } }); // // // // Transaction Class // // // function Transaction(mode, storeNames, dbschema, parent) { var _this2 = this; /// /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction. /// /// Any of "readwrite" or "readonly" /// Array of table names to operate on this.db = db; this.mode = mode; this.storeNames = storeNames; this.idbtrans = null; this.on = Events(this, "complete", "error", "abort"); this.parent = parent || null; this.active = true; this._tables = null; this._reculock = 0; this._blockedFuncs = []; this._psd = null; this._dbschema = dbschema; this._resolve = null; this._reject = null; this._completion = new Promise(function (resolve, reject) { _this2._resolve = resolve; _this2._reject = reject; }).uncaught(dbUncaught); this._completion.then(function () { _this2.on.complete.fire(); }, function (e) { _this2.on.error.fire(e); _this2.parent ? _this2.parent._reject(e) : _this2.active && _this2.idbtrans && _this2.idbtrans.abort(); _this2.active = false; return rejection(e); // Indicate we actually DO NOT catch this error. }); } props(Transaction.prototype, { // // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions) // _lock: function () { assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. // Temporary set all requests into a pending queue if they are called before database is ready. ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage) if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this; return this; }, _unlock: function () { assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. if (--this._reculock === 0) { if (!PSD.global) PSD.lockOwnerFor = null; while (this._blockedFuncs.length > 0 && !this._locked()) { var fnAndPSD = this._blockedFuncs.shift(); try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) {} } } return this; }, _locked: function () { // Checks if any write-lock is applied on this transaction. // To simplify the Dexie API for extension implementations, we support recursive locks. // This is accomplished by using "Promise Specific Data" (PSD). // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ). // PSD is local to code executing on top of the call stacks of any of any code executed by Promise(): // * callback given to the Promise() constructor (function (resolve, reject){...}) // * callbacks given to then()/catch()/finally() methods (function (value){...}) // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise. // Derivation is done so that the inner PSD __proto__ points to the outer PSD. // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock. return this._reculock && PSD.lockOwnerFor !== this; }, create: function (idbtrans) { var _this3 = this; assert(!this.idbtrans); if (!idbtrans && !idbdb) { switch (dbOpenError && dbOpenError.name) { case "DatabaseClosedError": // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() throw new exceptions.DatabaseClosed(dbOpenError); case "MissingAPIError": // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); default: // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()! throw new exceptions.OpenFailed(dbOpenError); } } if (!this.active) throw new exceptions.TransactionInactive(); assert(this._completion._state === null); idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode); idbtrans.onerror = wrap(function (ev) { preventDefault(ev); // Prohibit default bubbling to window.error _this3._reject(idbtrans.error); }); idbtrans.onabort = wrap(function (ev) { preventDefault(ev); _this3.active && _this3._reject(new exceptions.Abort()); _this3.active = false; _this3.on("abort").fire(ev); }); idbtrans.oncomplete = wrap(function () { _this3.active = false; _this3._resolve(); }); return this; }, _promise: function (mode, fn, bWriteLock) { var self = this; var p = self._locked() ? // Read lock always. Transaction is write-locked. Wait for mutex. new Promise(function (resolve, reject) { self._blockedFuncs.push([function () { self._promise(mode, fn, bWriteLock).then(resolve, reject); }, PSD]); }) : newScope(function () { var p_ = self.active ? new Promise(function (resolve, reject) { if (mode === READWRITE && self.mode !== READWRITE) throw new exceptions.ReadOnly("Transaction is readonly"); if (!self.idbtrans && mode) self.create(); if (bWriteLock) self._lock(); // Write lock if write operation is requested fn(resolve, reject, self); }) : rejection(new exceptions.TransactionInactive()); if (self.active && bWriteLock) p_.finally(function () { self._unlock(); }); return p_; }); p._lib = true; return p.uncaught(dbUncaught); }, // // Transaction Public Properties and Methods // abort: function () { this.active && this._reject(new exceptions.Abort()); this.active = false; }, tables: { get: deprecated("Transaction.tables", function () { return arrayToObject(this.storeNames, function (name) { return [name, allTables[name]]; }); }, "Use db.tables()") }, complete: deprecated("Transaction.complete()", function (cb) { return this.on("complete", cb); }), error: deprecated("Transaction.error()", function (cb) { return this.on("error", cb); }), table: deprecated("Transaction.table()", function (name) { if (this.storeNames.indexOf(name) === -1) throw new exceptions.InvalidTable("Table " + name + " not in transaction"); return allTables[name]; }) }); // // // // WhereClause // // // function WhereClause(table, index, orCollection) { /// /// /// this._ctx = { table: table, index: index === ":id" ? null : index, collClass: table._collClass, or: orCollection }; } props(WhereClause.prototype, function () { // WhereClause private methods function fail(collectionOrWhereClause, err, T) { var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) : collectionOrWhereClause; collection._ctx.error = T ? new T(err) : new TypeError(err); return collection; } function emptyCollection(whereClause) { return new whereClause._ctx.collClass(whereClause, function () { return IDBKeyRange.only(""); }).limit(0); } function upperFactory(dir) { return dir === "next" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); }; } function lowerFactory(dir) { return dir === "next" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); }; } function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { var length = Math.min(key.length, lowerNeedle.length); var llp = -1; for (var i = 0; i < length; ++i) { var lwrKeyChar = lowerKey[i]; if (lwrKeyChar !== lowerNeedle[i]) { if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); return null; } if (cmp(key[i], lwrKeyChar) < 0) llp = i; } if (length < lowerNeedle.length && dir === "next") return key + upperNeedle.substr(key.length); if (length < key.length && dir === "prev") return key.substr(0, upperNeedle.length); return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1); } function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { /// var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; if (!needles.every(function (s) { return typeof s === 'string'; })) { return fail(whereClause, STRING_EXPECTED); } function initDirection(dir) { upper = upperFactory(dir); lower = lowerFactory(dir); compare = dir === "next" ? simpleCompare : simpleCompareReverse; var needleBounds = needles.map(function (needle) { return { lower: lower(needle), upper: upper(needle) }; }).sort(function (a, b) { return compare(a.lower, b.lower); }); upperNeedles = needleBounds.map(function (nb) { return nb.upper; }); lowerNeedles = needleBounds.map(function (nb) { return nb.lower; }); direction = dir; nextKeySuffix = dir === "next" ? "" : suffix; } initDirection("next"); var c = new whereClause._ctx.collClass(whereClause, function () { return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); }); c._ondirectionchange = function (direction) { // This event onlys occur before filter is called the first time. initDirection(direction); }; var firstPossibleNeedle = 0; c._addAlgorithm(function (cursor, advance, resolve) { /// /// /// var key = cursor.key; if (typeof key !== 'string') return false; var lowerKey = lower(key); if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { return true; } else { var lowestPossibleCasing = null; for (var i = firstPossibleNeedle; i < needlesLen; ++i) { var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); if (casing === null && lowestPossibleCasing === null) firstPossibleNeedle = i + 1;else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { lowestPossibleCasing = casing; } } if (lowestPossibleCasing !== null) { advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); }); } else { advance(resolve); } return false; } }); return c; } // // WhereClause public methods // return { between: function (lower, upper, includeLower, includeUpper) { /// /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates. /// /// /// /// Whether items that equals lower should be included. Default true. /// Whether items that equals upper should be included. Default false. /// includeLower = includeLower !== false; // Default to true includeUpper = includeUpper === true; // Default to false try { if (cmp(lower, upper) > 0 || cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection. return new this._ctx.collClass(this, function () { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); }); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); } }, equals: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.only(value); }); }, above: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.lowerBound(value, true); }); }, aboveOrEqual: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.lowerBound(value); }); }, below: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.upperBound(value, true); }); }, belowOrEqual: function (value) { return new this._ctx.collClass(this, function () { return IDBKeyRange.upperBound(value); }); }, startsWith: function (str) { /// if (typeof str !== 'string') return fail(this, STRING_EXPECTED); return this.between(str, str + maxString, true, true); }, startsWithIgnoreCase: function (str) { /// if (str === "") return this.startsWith(str); return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); }, equalsIgnoreCase: function (str) { /// return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); }, anyOfIgnoreCase: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (set.length === 0) return emptyCollection(this); return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, ""); }, startsWithAnyOfIgnoreCase: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (set.length === 0) return emptyCollection(this); return addIgnoreCaseAlgorithm(this, function (x, a) { return a.some(function (n) { return x.indexOf(n) === 0; }); }, set, maxString); }, anyOf: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); var compare = ascending; try { set.sort(compare); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); } if (set.length === 0) return emptyCollection(this); var c = new this._ctx.collClass(this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); }); c._ondirectionchange = function (direction) { compare = direction === "next" ? ascending : descending; set.sort(compare); }; var i = 0; c._addAlgorithm(function (cursor, advance, resolve) { var key = cursor.key; while (compare(key, set[i]) > 0) { // The cursor has passed beyond this key. Check next. ++i; if (i === set.length) { // There is no next. Stop searching. advance(resolve); return false; } } if (compare(key, set[i]) === 0) { // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. return true; } else { // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. advance(function () { cursor.continue(set[i]); }); return false; } }); return c; }, notEqual: function (value) { return this.inAnyRange([[-Infinity, value], [value, maxKey]], { includeLowers: false, includeUppers: false }); }, noneOf: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection. try { set.sort(ascending); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); } // Transform ["a","b","c"] to a set of ranges for between/above/below: [[-Infinity,"a"], ["a","b"], ["b","c"], ["c",maxKey]] var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]]; }, null); ranges.push([set[set.length - 1], maxKey]); return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); }, /** Filter out values withing given set of ranges. * Example, give children and elders a rebate of 50%: * * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2}); * * @param {(string|number|Date|Array)[][]} ranges * @param {{includeLowers: boolean, includeUppers: boolean}} options */ inAnyRange: function (ranges, options) { var ctx = this._ctx; if (ranges.length === 0) return emptyCollection(this); if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0; })) { return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); } var includeLowers = !options || options.includeLowers !== false; // Default to true var includeUppers = options && options.includeUppers === true; // Default to false function addRange(ranges, newRange) { for (var i = 0, l = ranges.length; i < l; ++i) { var range = ranges[i]; if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) { range[0] = min(range[0], newRange[0]); range[1] = max(range[1], newRange[1]); break; } } if (i === l) ranges.push(newRange); return ranges; } var sortDirection = ascending; function rangeSorter(a, b) { return sortDirection(a[0], b[0]); } // Join overlapping ranges var set; try { set = ranges.reduce(addRange, []); set.sort(rangeSorter); } catch (ex) { return fail(this, INVALID_KEY_ARGUMENT); } var i = 0; var keyIsBeyondCurrentEntry = includeUppers ? function (key) { return ascending(key, set[i][1]) > 0; } : function (key) { return ascending(key, set[i][1]) >= 0; }; var keyIsBeforeCurrentEntry = includeLowers ? function (key) { return descending(key, set[i][0]) > 0; } : function (key) { return descending(key, set[i][0]) >= 0; }; function keyWithinCurrentRange(key) { return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); } var checkKey = keyIsBeyondCurrentEntry; var c = new ctx.collClass(this, function () { return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); }); c._ondirectionchange = function (direction) { if (direction === "next") { checkKey = keyIsBeyondCurrentEntry; sortDirection = ascending; } else { checkKey = keyIsBeforeCurrentEntry; sortDirection = descending; } set.sort(rangeSorter); }; c._addAlgorithm(function (cursor, advance, resolve) { var key = cursor.key; while (checkKey(key)) { // The cursor has passed beyond this key. Check next. ++i; if (i === set.length) { // There is no next. Stop searching. advance(resolve); return false; } } if (keyWithinCurrentRange(key)) { // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. return true; } else if (cmp(key, set[i][1]) === 0 || cmp(key, set[i][0]) === 0) { // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border. // Continue to next key but don't include this one. return false; } else { // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. advance(function () { if (sortDirection === ascending) cursor.continue(set[i][0]);else cursor.continue(set[i][1]); }); return false; } }); return c; }, startsWithAnyOf: function () { var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); if (!set.every(function (s) { return typeof s === 'string'; })) { return fail(this, "startsWithAnyOf() only works with strings"); } if (set.length === 0) return emptyCollection(this); return this.inAnyRange(set.map(function (str) { return [str, str + maxString]; })); } }; }); // // // // Collection Class // // // function Collection(whereClause, keyRangeGenerator) { /// /// /// /// Where clause instance /// var keyRange = null, error = null; if (keyRangeGenerator) try { keyRange = keyRangeGenerator(); } catch (ex) { error = ex; } var whereCtx = whereClause._ctx, table = whereCtx.table; this._ctx = { table: table, index: whereCtx.index, isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name, range: keyRange, keysOnly: false, dir: "next", unique: "", algorithm: null, filter: null, replayFilter: null, justLimit: true, // True if a replayFilter is just a filter that performs a "limit" operation (or none at all) isMatch: null, offset: 0, limit: Infinity, error: error, // If set, any promise must be rejected with this error or: whereCtx.or, valueMapper: table.hook.reading.fire }; } function isPlainKeyRange(ctx, ignoreLimitFilter) { return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); } props(Collection.prototype, function () { // // Collection Private Functions // function addFilter(ctx, fn) { ctx.filter = combine(ctx.filter, fn); } function addReplayFilter(ctx, factory, isLimitFilter) { var curr = ctx.replayFilter; ctx.replayFilter = curr ? function () { return combine(curr(), factory()); } : factory; ctx.justLimit = isLimitFilter && !curr; } function addMatchFilter(ctx, fn) { ctx.isMatch = combine(ctx.isMatch, fn); } /** @param ctx { * isPrimKey: boolean, * table: Table, * index: string * } * @param store IDBObjectStore **/ function getIndexOrStore(ctx, store) { if (ctx.isPrimKey) return store; var indexSpec = ctx.table.schema.idxByName[ctx.index]; if (!indexSpec) throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed"); return store.index(indexSpec.name); } /** @param ctx { * isPrimKey: boolean, * table: Table, * index: string, * keysOnly: boolean, * range?: IDBKeyRange, * dir: "next" | "prev" * } */ function openCursor(ctx, store) { var idxOrStore = getIndexOrStore(ctx, store); return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique); } function iter(ctx, fn, resolve, reject, idbstore) { var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; if (!ctx.or) { iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper); } else (function () { var set = {}; var resolved = 0; function resolveboth() { if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion. } function union(item, cursor, advance) { if (!filter || filter(cursor, advance, resolveboth, reject)) { var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string if (!hasOwn(set, key)) { set[key] = true; fn(item, cursor, advance); } } } ctx.or._iterate(union, resolveboth, reject, idbstore); iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper); })(); } function getInstanceTemplate(ctx) { return ctx.table.schema.instanceTemplate; } return { // // Collection Protected Functions // _read: function (fn, cb) { var ctx = this._ctx; if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); });else return ctx.table._idbstore(READONLY, fn).then(cb); }, _write: function (fn) { var ctx = this._ctx; if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) { reject(ctx.error); });else return ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued. }, _addAlgorithm: function (fn) { var ctx = this._ctx; ctx.algorithm = combine(ctx.algorithm, fn); }, _iterate: function (fn, resolve, reject, idbstore) { return iter(this._ctx, fn, resolve, reject, idbstore); }, clone: function (props$$1) { var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); if (props$$1) extend(ctx, props$$1); rv._ctx = ctx; return rv; }, raw: function () { this._ctx.valueMapper = null; return this; }, // // Collection Public methods // each: function (fn) { var ctx = this._ctx; if (fake) { var item = getInstanceTemplate(ctx), primKeyPath = ctx.table.schema.primKey.keyPath, key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath), primaryKey = getByKeyPath(item, primKeyPath); fn(item, { key: key, primaryKey: primaryKey }); } return this._read(function (resolve, reject, idbstore) { iter(ctx, fn, resolve, reject, idbstore); }); }, count: function (cb) { if (fake) return Promise.resolve(0).then(cb); var ctx = this._ctx; if (isPlainKeyRange(ctx, true)) { // This is a plain key range. We can use the count() method if the index. return this._read(function (resolve, reject, idbstore) { var idx = getIndexOrStore(ctx, idbstore); var req = ctx.range ? idx.count(ctx.range) : idx.count(); req.onerror = eventRejectHandler(reject); req.onsuccess = function (e) { resolve(Math.min(e.target.result, ctx.limit)); }; }, cb); } else { // Algorithms, filters or expressions are applied. Need to count manually. var count = 0; return this._read(function (resolve, reject, idbstore) { iter(ctx, function () { ++count;return false; }, function () { resolve(count); }, reject, idbstore); }, cb); } }, sortBy: function (keyPath, cb) { /// var parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1; function getval(obj, i) { if (i) return getval(obj[parts[i]], i - 1); return obj[lastPart]; } var order = this._ctx.dir === "next" ? 1 : -1; function sorter(a, b) { var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); return aVal < bVal ? -order : aVal > bVal ? order : 0; } return this.toArray(function (a) { return a.sort(sorter); }).then(cb); }, toArray: function (cb) { var ctx = this._ctx; return this._read(function (resolve, reject, idbstore) { fake && resolve([getInstanceTemplate(ctx)]); if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { // Special optimation if we could use IDBObjectStore.getAll() or // IDBKeyRange.getAll(): var readingHook = ctx.table.hook.reading.fire; var idxOrStore = getIndexOrStore(ctx, idbstore); var req = ctx.limit < Infinity ? idxOrStore.getAll(ctx.range, ctx.limit) : idxOrStore.getAll(ctx.range); req.onerror = eventRejectHandler(reject); req.onsuccess = readingHook === mirror ? eventSuccessHandler(resolve) : wrap(eventSuccessHandler(function (res) { try { resolve(res.map(readingHook)); } catch (e) { reject(e); } })); } else { // Getting array through a cursor. var a = []; iter(ctx, function (item) { a.push(item); }, function arrayComplete() { resolve(a); }, reject, idbstore); } }, cb); }, offset: function (offset) { var ctx = this._ctx; if (offset <= 0) return this; ctx.offset += offset; // For count() if (isPlainKeyRange(ctx)) { addReplayFilter(ctx, function () { var offsetLeft = offset; return function (cursor, advance) { if (offsetLeft === 0) return true; if (offsetLeft === 1) { --offsetLeft;return false; } advance(function () { cursor.advance(offsetLeft); offsetLeft = 0; }); return false; }; }); } else { addReplayFilter(ctx, function () { var offsetLeft = offset; return function () { return --offsetLeft < 0; }; }); } return this; }, limit: function (numRows) { this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count() addReplayFilter(this._ctx, function () { var rowsLeft = numRows; return function (cursor, advance, resolve) { if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here. }; }, true); return this; }, until: function (filterFunction, bIncludeStopEntry) { var ctx = this._ctx; fake && filterFunction(getInstanceTemplate(ctx)); addFilter(this._ctx, function (cursor, advance, resolve) { if (filterFunction(cursor.value)) { advance(resolve); return bIncludeStopEntry; } else { return true; } }); return this; }, first: function (cb) { return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); }, last: function (cb) { return this.reverse().first(cb); }, filter: function (filterFunction) { /// function(val){return true/false} fake && filterFunction(getInstanceTemplate(this._ctx)); addFilter(this._ctx, function (cursor) { return filterFunction(cursor.value); }); // match filters not used in Dexie.js but can be used by 3rd part libraries to test a // collection for a match without querying DB. Used by Dexie.Observable. addMatchFilter(this._ctx, filterFunction); return this; }, and: function (filterFunction) { return this.filter(filterFunction); }, or: function (indexName) { return new WhereClause(this._ctx.table, indexName, this); }, reverse: function () { this._ctx.dir = this._ctx.dir === "prev" ? "next" : "prev"; if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir); return this; }, desc: function () { return this.reverse(); }, eachKey: function (cb) { var ctx = this._ctx; ctx.keysOnly = !ctx.isMatch; return this.each(function (val, cursor) { cb(cursor.key, cursor); }); }, eachUniqueKey: function (cb) { this._ctx.unique = "unique"; return this.eachKey(cb); }, eachPrimaryKey: function (cb) { var ctx = this._ctx; ctx.keysOnly = !ctx.isMatch; return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); }, keys: function (cb) { var ctx = this._ctx; ctx.keysOnly = !ctx.isMatch; var a = []; return this.each(function (item, cursor) { a.push(cursor.key); }).then(function () { return a; }).then(cb); }, primaryKeys: function (cb) { var ctx = this._ctx; if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { // Special optimation if we could use IDBObjectStore.getAllKeys() or // IDBKeyRange.getAllKeys(): return this._read(function (resolve, reject, idbstore) { var idxOrStore = getIndexOrStore(ctx, idbstore); var req = ctx.limit < Infinity ? idxOrStore.getAllKeys(ctx.range, ctx.limit) : idxOrStore.getAllKeys(ctx.range); req.onerror = eventRejectHandler(reject); req.onsuccess = eventSuccessHandler(resolve); }).then(cb); } ctx.keysOnly = !ctx.isMatch; var a = []; return this.each(function (item, cursor) { a.push(cursor.primaryKey); }).then(function () { return a; }).then(cb); }, uniqueKeys: function (cb) { this._ctx.unique = "unique"; return this.keys(cb); }, firstKey: function (cb) { return this.limit(1).keys(function (a) { return a[0]; }).then(cb); }, lastKey: function (cb) { return this.reverse().firstKey(cb); }, distinct: function () { var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes. var set = {}; addFilter(this._ctx, function (cursor) { var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string var found = hasOwn(set, strKey); set[strKey] = true; return !found; }); return this; } }; }); // // // WriteableCollection Class // // function WriteableCollection() { Collection.apply(this, arguments); } derive(WriteableCollection).from(Collection).extend({ // // WriteableCollection Public Methods // modify: function (changes) { var self = this, ctx = this._ctx, hook = ctx.table.hook, updatingHook = hook.updating.fire, deletingHook = hook.deleting.fire; fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate); return this._write(function (resolve, reject, idbstore, trans) { var modifyer; if (typeof changes === 'function') { // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item) if (updatingHook === nop && deletingHook === nop) { // Noone cares about what is being changed. Just let the modifier function be the given argument as is. modifyer = changes; } else { // People want to know exactly what is being modified or deleted. // Let modifyer be a proxy function that finds out what changes the caller is actually doing // and call the hooks accordingly! modifyer = function (item) { var origItem = deepClone(item); // Clone the item first so we can compare laters. if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object) if (!hasOwn(this, "value")) { // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place. deletingHook.call(this, this.primKey, item, trans); } else { // No deletion. Check what was changed var objectDiff = getObjectDiff(origItem, this.value); var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans); if (additionalChanges) { // Hook want to apply additional modifications. Make sure to fullfill the will of the hook. item = this.value; keys(additionalChanges).forEach(function (keyPath) { setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath }); } } }; } } else if (updatingHook === nop) { // changes is a set of {keyPath: value} and no one is listening to the updating hook. var keyPaths = keys(changes); var numKeys = keyPaths.length; modifyer = function (item) { var anythingModified = false; for (var i = 0; i < numKeys; ++i) { var keyPath = keyPaths[i], val = changes[keyPath]; if (getByKeyPath(item, keyPath) !== val) { setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath anythingModified = true; } } return anythingModified; }; } else { // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and // allow it to add additional modifications to make. var origChanges = changes; changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it. modifyer = function (item) { var anythingModified = false; var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans); if (additionalChanges) extend(changes, additionalChanges); keys(changes).forEach(function (keyPath) { var val = changes[keyPath]; if (getByKeyPath(item, keyPath) !== val) { setByKeyPath(item, keyPath, val); anythingModified = true; } }); if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration return anythingModified; }; } var count = 0; var successCount = 0; var iterationComplete = false; var failures = []; var failKeys = []; var currentKey = null; function modifyItem(item, cursor) { currentKey = cursor.primaryKey; var thisContext = { primKey: cursor.primaryKey, value: item, onsuccess: null, onerror: null }; function onerror(e) { failures.push(e); failKeys.push(thisContext.primKey); checkFinished(); return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction } if (modifyer.call(thisContext, item, thisContext) !== false) { // If a callback explicitely returns false, do not perform the update! var bDelete = !hasOwn(thisContext, "value"); ++count; tryCatch(function () { var req = bDelete ? cursor.delete() : cursor.update(thisContext.value); req._hookCtx = thisContext; req.onerror = hookedEventRejectHandler(onerror); req.onsuccess = hookedEventSuccessHandler(function () { ++successCount; checkFinished(); }); }, onerror); } else if (thisContext.onsuccess) { // Hook will expect either onerror or onsuccess to always be called! thisContext.onsuccess(thisContext.value); } } function doReject(e) { if (e) { failures.push(e); failKeys.push(currentKey); } return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys)); } function checkFinished() { if (iterationComplete && successCount + failures.length === count) { if (failures.length > 0) doReject();else resolve(successCount); } } self.clone().raw()._iterate(modifyItem, function () { iterationComplete = true; checkFinished(); }, doReject, idbstore); }); }, 'delete': function () { var _this4 = this; var ctx = this._ctx, range = ctx.range, deletingHook = ctx.table.hook.deleting.fire, hasDeleteHook = deletingHook !== nop; if (!hasDeleteHook && isPlainKeyRange(ctx) && (ctx.isPrimKey && !hangsOnDeleteLargeKeyRange || !range)) // if no range, we'll use clear(). { // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208) // For chromium, this is the way most optimized version. // For IE/Edge, this could hang the indexedDB engine and make operating system instable // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7) return this._write(function (resolve, reject, idbstore) { // Our API contract is to return a count of deleted items, so we have to count() before delete(). var onerror = eventRejectHandler(reject), countReq = range ? idbstore.count(range) : idbstore.count(); countReq.onerror = onerror; countReq.onsuccess = function () { var count = countReq.result; tryCatch(function () { var delReq = range ? idbstore.delete(range) : idbstore.clear(); delReq.onerror = onerror; delReq.onsuccess = function () { return resolve(count); }; }, function (err) { return reject(err); }); }; }); } // Default version to use when collection is not a vanilla IDBKeyRange on the primary key. // Divide into chunks to not starve RAM. // If has delete hook, we will have to collect not just keys but also objects, so it will use // more memory and need lower chunk size. var CHUNKSIZE = hasDeleteHook ? 2000 : 10000; return this._write(function (resolve, reject, idbstore, trans) { var totalCount = 0; // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance. var collection = _this4.clone({ keysOnly: !ctx.isMatch && !hasDeleteHook }) // load just keys (unless filter() or and() or deleteHook has subscribers) .distinct() // In case multiEntry is used, never delete same key twice because resulting count // would become larger than actual delete count. .limit(CHUNKSIZE).raw(); // Don't filter through reading-hooks (like mapped classes etc) var keysOrTuples = []; // We're gonna do things on as many chunks that are needed. // Use recursion of nextChunk function: var nextChunk = function () { return collection.each(hasDeleteHook ? function (val, cursor) { // Somebody subscribes to hook('deleting'). Collect all primary keys and their values, // so that the hook can be called with its values in bulkDelete(). keysOrTuples.push([cursor.primaryKey, cursor.value]); } : function (val, cursor) { // No one subscribes to hook('deleting'). Collect only primary keys: keysOrTuples.push(cursor.primaryKey); }).then(function () { // Chromium deletes faster when doing it in sort order. hasDeleteHook ? keysOrTuples.sort(function (a, b) { return ascending(a[0], b[0]); }) : keysOrTuples.sort(ascending); return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook); }).then(function () { var count = keysOrTuples.length; totalCount += count; keysOrTuples = []; return count < CHUNKSIZE ? totalCount : nextChunk(); }); }; resolve(nextChunk()); }); } }); // // // // ------------------------- Help functions --------------------------- // // // function lowerVersionFirst(a, b) { return a._cfg.version - b._cfg.version; } function setApiOnPlace(objs, tableNames, mode, dbschema) { tableNames.forEach(function (tableName) { var tableInstance = db._tableFactory(mode, dbschema[tableName]); objs.forEach(function (obj) { tableName in obj || (obj[tableName] = tableInstance); }); }); } function removeTablesApi(objs) { objs.forEach(function (obj) { for (var key in obj) { if (obj[key] instanceof Table) delete obj[key]; } }); } function iterate(req, filter, fn, resolve, reject, valueMapper) { // Apply valueMapper (hook('reading') or mappped class) var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; // Wrap fn with PSD and microtick stuff from Promise. var wrappedFn = wrap(mappedFn, reject); if (!req.onerror) req.onerror = eventRejectHandler(reject); if (filter) { req.onsuccess = trycatcher(function filter_record() { var cursor = req.result; if (cursor) { var c = function () { cursor.continue(); }; if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject)) wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); c(); } else { resolve(); } }, reject); } else { req.onsuccess = trycatcher(function filter_record() { var cursor = req.result; if (cursor) { var c = function () { cursor.continue(); }; wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); c(); } else { resolve(); } }, reject); } } function parseIndexSyntax(indexes) { /// /// var rv = []; indexes.split(',').forEach(function (index) { index = index.trim(); var name = index.replace(/([&*]|\+\+)/g, ""); // Remove "&", "++" and "*" // Let keyPath of "[a+b]" be ["a","b"]: var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; rv.push(new IndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), /\./.test(index))); }); return rv; } function cmp(key1, key2) { return indexedDB.cmp(key1, key2); } function min(a, b) { return cmp(a, b) < 0 ? a : b; } function max(a, b) { return cmp(a, b) > 0 ? a : b; } function ascending(a, b) { return indexedDB.cmp(a, b); } function descending(a, b) { return indexedDB.cmp(b, a); } function simpleCompare(a, b) { return a < b ? -1 : a === b ? 0 : 1; } function simpleCompareReverse(a, b) { return a > b ? -1 : a === b ? 0 : 1; } function combine(filter1, filter2) { return filter1 ? filter2 ? function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : filter1 : filter2; } function readGlobalSchema() { db.verno = idbdb.version / 10; db._dbSchema = globalSchema = {}; dbStoreNames = slice(idbdb.objectStoreNames, 0); if (dbStoreNames.length === 0) return; // Database contains no stores. var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly'); dbStoreNames.forEach(function (storeName) { var store = trans.objectStore(storeName), keyPath = store.keyPath, dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted); var indexes = []; for (var j = 0; j < store.indexNames.length; ++j) { var idbindex = store.index(store.indexNames[j]); keyPath = idbindex.keyPath; dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted); indexes.push(index); } globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {}); }); setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema); } function adjustToExistingIndexNames(schema, idbtrans) { /// /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db /// /// Map between name and TableSchema /// var storeNames = idbtrans.db.objectStoreNames; for (var i = 0; i < storeNames.length; ++i) { var storeName = storeNames[i]; var store = idbtrans.objectStore(storeName); hasGetAll = 'getAll' in store; for (var j = 0; j < store.indexNames.length; ++j) { var indexName = store.indexNames[j]; var keyPath = store.index(indexName).keyPath; var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; if (schema[storeName]) { var indexSpec = schema[storeName].idxByName[dexieName]; if (indexSpec) indexSpec.name = indexName; } } } } function fireOnBlocked(ev) { db.on("blocked").fire(ev); // Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari: connections.filter(function (c) { return c.name === db.name && c !== db && !c._vcFired; }).map(function (c) { return c.on("versionchange").fire(ev); }); } extend(this, { Collection: Collection, Table: Table, Transaction: Transaction, Version: Version, WhereClause: WhereClause, WriteableCollection: WriteableCollection, WriteableTable: WriteableTable }); init(); addons.forEach(function (fn) { fn(db); }); } var fakeAutoComplete = function () {}; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) var fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) function parseType(type) { if (typeof type === 'function') { return new type(); } else if (isArray(type)) { return [parseType(type[0])]; } else if (type && typeof type === 'object') { var rv = {}; applyStructure(rv, type); return rv; } else { return type; } } function applyStructure(obj, structure) { keys(structure).forEach(function (member) { var value = parseType(structure[member]); obj[member] = value; }); return obj; } function eventSuccessHandler(done) { return function (ev) { done(ev.target.result); }; } function hookedEventSuccessHandler(resolve) { // wrap() is needed when calling hooks because the rare scenario of: // * hook does a db operation that fails immediately (IDB throws exception) // For calling db operations on correct transaction, wrap makes sure to set PSD correctly. // wrap() will also execute in a virtual tick. // * If not wrapped in a virtual tick, direct exception will launch a new physical tick. // * If this was the last event in the bulk, the promise will resolve after a physical tick // and the transaction will have committed already. // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise, // because it is always marked with _lib = true when created using Transaction._promise(). return wrap(function (event) { var req = event.target, result = req.result, ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance. hookSuccessHandler = ctx && ctx.onsuccess; hookSuccessHandler && hookSuccessHandler(result); resolve && resolve(result); }, resolve); } function eventRejectHandler(reject) { return function (event) { preventDefault(event); reject(event.target.error); return false; }; } function hookedEventRejectHandler(reject) { return wrap(function (event) { // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks. var req = event.target, err = req.error, ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance. hookErrorHandler = ctx && ctx.onerror; hookErrorHandler && hookErrorHandler(err); preventDefault(event); reject(err); return false; }); } function preventDefault(event) { if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below. event.stopPropagation(); if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below. event.preventDefault(); } function globalDatabaseList(cb) { var val, localStorage = Dexie.dependencies.localStorage; if (!localStorage) return cb([]); // Envs without localStorage support try { val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || "[]"); } catch (e) { val = []; } if (cb(val)) { localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val)); } } function awaitIterator(iterator) { var callNext = function (result) { return iterator.next(result); }, doThrow = function (error) { return iterator.throw(error); }, onSuccess = step(callNext), onError = step(doThrow); function step(getNext) { return function (val) { var next = getNext(val), value = next.value; return next.done ? value : !value || typeof value.then !== 'function' ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError); }; } return step(callNext)(); } // // IndexSpec struct // function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) { /// /// /// /// /// /// /// this.name = name; this.keyPath = keyPath; this.unique = unique; this.multi = multi; this.auto = auto; this.compound = compound; this.dotted = dotted; var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && '[' + [].join.call(keyPath, '+') + ']'; this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc; } // // TableSchema struct // function TableSchema(name, primKey, indexes, instanceTemplate) { /// /// /// /// this.name = name; this.primKey = primKey || new IndexSpec(); this.indexes = indexes || [new IndexSpec()]; this.instanceTemplate = instanceTemplate; this.mappedClass = null; this.idxByName = arrayToObject(indexes, function (index) { return [index.name, index]; }); } // Used in when defining dependencies later... // (If IndexedDBShim is loaded, prefer it before standard indexedDB) var idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {}; function safariMultiStoreFix(storeNames) { return storeNames.length === 1 ? storeNames[0] : storeNames; } function getNativeGetDatabaseNamesFn(indexedDB) { var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames); return fn && fn.bind(indexedDB); } // Export Error classes props(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...}; // // Static methods and properties // props(Dexie, { // // Static delete() method. // delete: function (databaseName) { var db = new Dexie(databaseName), promise = db.delete(); promise.onblocked = function (fn) { db.on("blocked", fn); return this; }; return promise; }, // // Static exists() method. // exists: function (name) { return new Dexie(name).open().then(function (db) { db.close(); return true; }).catch(Dexie.NoSuchDatabaseError, function () { return false; }); }, // // Static method for retrieving a list of all existing databases at current host. // getDatabaseNames: function (cb) { return new Promise(function (resolve, reject) { var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB); if (getDatabaseNames) { // In case getDatabaseNames() becomes standard, let's prepare to support it: var req = getDatabaseNames(); req.onsuccess = function (event) { resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array }; req.onerror = eventRejectHandler(reject); } else { globalDatabaseList(function (val) { resolve(val); return false; }); } }).then(cb); }, defineClass: function (structure) { /// /// Create a javascript constructor based on given template for which properties to expect in the class. /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}. /// /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} // Default constructor able to copy given properties into this object. function Class(properties) { /// Properties to initialize object with. /// properties ? extend(this, properties) : fake && applyStructure(this, structure); } return Class; }, applyStructure: applyStructure, ignoreTransaction: function (scopeFunc) { // In case caller is within a transaction but needs to create a separate transaction. // Example of usage: // // Let's say we have a logger function in our app. Other application-logic should be unaware of the // logger function and not need to include the 'logentries' table in all transaction it performs. // The logging should always be done in a separate transaction and not be dependant on the current // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction. // // Dexie.ignoreTransaction(function() { // db.logentries.add(newLogEntry); // }); // // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction // in current Promise-scope. // // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an // API for this because // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout(). // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate(). // 3) setImmediate() is not supported in the ES standard. // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough. return PSD.trans ? usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional. scopeFunc(); // No need to change scope because there is no ongoing transaction. }, vip: function (fn) { // To be used by subscribers to the on('ready') event. // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing. // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that. // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip() // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by // the caller will not resolve until database is opened. return newScope(function () { PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing. return fn(); }); }, async: function (generatorFn) { return function () { try { var rv = awaitIterator(generatorFn.apply(this, arguments)); if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv); return rv; } catch (e) { return rejection(e); } }; }, spawn: function (generatorFn, args, thiz) { try { var rv = awaitIterator(generatorFn.apply(thiz, args || [])); if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv); return rv; } catch (e) { return rejection(e); } }, // Dexie.currentTransaction property currentTransaction: { get: function () { return PSD.trans || null; } }, // Export our Promise implementation since it can be handy as a standalone Promise implementation Promise: Promise, // Dexie.debug proptery: // Dexie.debug = false // Dexie.debug = true // Dexie.debug = "dexie" - don't hide dexie's stack frames. debug: { get: function () { return debug; }, set: function (value) { setDebug(value, value === 'dexie' ? function () { return true; } : dexieStackFrameFilter); } }, // Export our derive/extend/override methodology derive: derive, extend: extend, props: props, override: override, // Export our Events() function - can be handy as a toolkit Events: Events, events: { get: deprecated(function () { return Events; }) }, // Backward compatible lowercase version. // Utilities getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, asap: asap, maxKey: maxKey, // Addon registry addons: [], // Global DB connection list connections: connections, MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate. errnames: errnames, // Export other static classes IndexSpec: IndexSpec, TableSchema: TableSchema, // // Dependencies // // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included. // // In node.js, however, these properties must be set "manually" before instansiating a new Dexie(). // For node.js, you need to require indexeddb-js or similar and then set these deps. // dependencies: { // Required: indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange }, // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc. semVer: DEXIE_VERSION, version: DEXIE_VERSION.split('.').map(function (n) { return parseInt(n); }).reduce(function (p, c, i) { return p + c / Math.pow(10, i * 2); }), fakeAutoComplete: fakeAutoComplete, // https://github.com/dfahlander/Dexie.js/issues/186 // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return // x.default. Workaround: Set Dexie.default = Dexie. default: Dexie }); tryCatch(function () { // Optional dependencies // localStorage Dexie.dependencies.localStorage = (typeof chrome !== "undefined" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage; }); // Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0. Promise.rejectionMapper = mapError; // Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015. doFakeAutoComplete(function () { Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete; Dexie.fake = fake = true; }); return Dexie; }))); //# sourceMappingURL=dexie.js.map /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5), __webpack_require__(53).setImmediate)) /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; 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; }; }(); 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; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Dexie = __webpack_require__(153); var _write = __webpack_require__(191); var pushable = __webpack_require__(168); var toBuffer = __webpack_require__(193); var defer = __webpack_require__(167); var toWindow = __webpack_require__(190).recent; var pull = __webpack_require__(77); module.exports = function () { function IdbBlobStore(dbname) { _classCallCheck(this, IdbBlobStore); this.path = dbname || 'pull-blob-store-' + Math.random().toString().slice(2, 10); this.db = new Dexie(this.path); // Setup database this.db.version(1).stores(_defineProperty({}, this.path, '++,key,blob')); } _createClass(IdbBlobStore, [{ key: 'write', value: function write(key, cb) { var _this = this; cb = cb || function () {}; var d = defer(); if (!key) { cb(new Error('Missing key')); return d; } this.remove(key, function (err) { if (err) { return cb(err); } var table = _this.table; d.resolve(pull(toWindow(100, 10), _write(writer, reduce, 100, cb))); function writer(data, cb) { var blobs = data.map(function (blob) { return { key: key, blob: blob }; }); table.bulkPut(blobs).then(function () { return cb(); }).catch(cb); } function reduce(queue, data) { queue = queue || []; if (!Array.isArray(data)) { data = [data]; } data = data.map(ensureBuffer); if (!queue.length || last(queue).length > 99) { queue.push(Buffer.concat(data)); } else { queue[lastIndex(queue)] = Buffer.concat(last(queue).concat(data)); } return queue; } }); return d; } }, { key: 'read', value: function read(key) { var _this2 = this; var p = pushable(); if (!key) { p.end(new Error('Missing key')); return p; } this.exists(key, function (err, exists) { if (err) { return p.end(err); } if (!exists) { return p.end(new Error('Not found')); } _this2.table.where('key').equals(key).each(function (val) { return p.push(toBuffer(val.blob)); }).catch(function (err) { return p.end(err); }).then(function () { return p.end(); }); }); return p; } }, { key: 'exists', value: function exists(key, cb) { cb = cb || function () {}; if (!key) { return cb(new Error('Missing key')); } this.table.where('key').equals(key).count().then(function (val) { return cb(null, Boolean(val)); }).catch(cb); } }, { key: 'remove', value: function remove(key, cb) { cb = cb || function () {}; if (!key) { return cb(new Error('Missing key')); } var coll = this.table.where('key').equals(key); coll.count(function (count) { return count > 0 ? coll.delete() : null; }).then(function () { return cb(); }).catch(cb); } }, { key: 'table', get: function get() { return this.db[this.path]; } }]); return IdbBlobStore; }(); function lastIndex(arr) { return arr.length - 1; } function last(arr) { return arr[lastIndex(arr)]; } function ensureBuffer(data) { return Buffer.isBuffer(data) ? data : Buffer.from(data); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21).Buffer)) /***/ }, /* 155 */ /***/ function(module, exports) { exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } /***/ }, /* 156 */ /***/ 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 } } /***/ }, /* 157 */ /***/ function(module, exports) { module.exports = isTypedArray isTypedArray.strict = isStrictTypedArray isTypedArray.loose = isLooseTypedArray var toString = Object.prototype.toString var names = { '[object Int8Array]': true , '[object Int16Array]': true , '[object Int32Array]': true , '[object Uint8Array]': true , '[object Uint8ClampedArray]': true , '[object Uint16Array]': true , '[object Uint32Array]': true , '[object Float32Array]': true , '[object Float64Array]': true } function isTypedArray(arr) { return ( isStrictTypedArray(arr) || isLooseTypedArray(arr) ) } function isStrictTypedArray(arr) { return ( arr instanceof Int8Array || arr instanceof Int16Array || arr instanceof Int32Array || arr instanceof Uint8Array || arr instanceof Uint8ClampedArray || arr instanceof Uint16Array || arr instanceof Uint32Array || arr instanceof Float32Array || arr instanceof Float64Array ) } function isLooseTypedArray(arr) { return names[toString.call(arr)] } /***/ }, /* 158 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(setImmediate) { module.exports = function () { var next = typeof setImmediate === 'undefined' ? setTimeout : setImmediate var locked = {} function _releaser (key, exec) { return function (done) { return function () { _release(key, exec) if (done) done.apply(null, arguments) } } } function _release (key, exec) { var i = locked[key].indexOf(exec) //should usually be 0 if(!~i) return locked[key].splice(i, 1) //note, that the next locker isn't triggered until next tick, //so it's always after the released callback if(isLocked(key)) next(function () { locked[key][0](_releaser(key, locked[key][0])) }) else delete locked[key] } function _lock(key, exec) { if(isLocked(key)) return locked[key].push(exec), false return locked[key] = [exec], true } function lock(key, exec) { if(Array.isArray(key)) { var keys = key.length, locks = [] var l = {} function releaser (done) { return function () { var args = [].slice.call(arguments) for(var key in l) _release(key, l[key]) done.apply(this, args) } } key.forEach(function (key) { var n = 0 function ready () { if(n++) return if(!--keys) //all the keys are ready! exec(releaser) } l[key] = ready if(_lock(key, ready)) ready() }) return } if(_lock(key, exec)) exec(_releaser(key, exec)) } function isLocked (key) { return Array.isArray(locked[key]) ? !! locked[key].length : false } lock.isLocked = isLocked return lock } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(53).setImmediate)) /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** 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')(); /** * 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 `_.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 ? array.length : 0; 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 ? array.length : 0; 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 ? array.length : 0, 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; } /** * 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) { if (value !== value) { return baseFindIndex(array, baseIsNaN, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (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 `_.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); }; } /** * 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); } /** * 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 `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** 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 = root['__core-js_shared__']; /** 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 decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** 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 Symbol = root.Symbol, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'), nativeCreate = getNative(Object, 'create'); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; 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) : {}; } /** * 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) { return this.has(key) && delete this.__data__[key]; } /** * 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__; 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 ? entries.length : 0; 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__ = []; } /** * 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); } 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) { 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 ? entries.length : 0; 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.__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) { return getMapData(this, key)['delete'](key); } /** * 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) { getMapData(this, key).set(key, value); 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 ? values.length : 0; 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; /** * 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; } /** * 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 ? iteratee(value) : 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 `_.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 `_.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) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * 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) { 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] = array; return apply(func, this, otherArgs); }; } /** * 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 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; } /** * 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 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 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); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @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 ''; } /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. Result values * are chosen from 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) : []; }); /** * 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 ? array.length : 0; return length ? array[length - 1] : undefined; } /** * 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 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 */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * 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 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 `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) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * 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 && (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 && typeof value == 'object'; } module.exports = differenceWith; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, module) {/** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', promiseTag = '[object Promise]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; 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 property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, 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; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** 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 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; /** Built-in method references without a dependency on `root`. */ var 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 { return freeProcess && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * 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 ? array.length : 0; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * 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 `_.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 `_.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 `_.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); }; } /** * 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 `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } 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)); }; } /** * 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; } /** 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 = root['__core-js_shared__']; /** 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 decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** 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 Symbol = root.Symbol, Uint8Array = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max; /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** 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 hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; 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) : {}; } /** * 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) { return this.has(key) && delete this.__data__[key]; } /** * 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__; 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 ? entries.length : 0; 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__ = []; } /** * 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); } 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) { 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 ? entries.length : 0; 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.__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) { return getMapData(this, key)['delete'](key); } /** * 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) { getMapData(this, key).set(key, value); 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 ? values.length : 0; 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) { this.__data__ = new ListCache(entries); } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; } /** * 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) { return this.__data__['delete'](key); } /** * 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 cache = this.__data__; if (cache instanceof ListCache) { var pairs = cache.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); return this; } cache = this.__data__ = new MapCache(pairs); } cache.set(key, value); 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) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. // Safari 9 makes `arguments.length` enumerable in strict mode. var result = (isArray(value) || isArguments(value)) ? baseTimes(value.length, String) : []; var length = result.length, skipIndexes = !!length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) { result.push(key); } } return result; } /** * 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; } /** * 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 = isKey(path, object) ? [path] : castPath(path); 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 `getTag`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { return objectToString.call(value); } /** * 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 `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @param {boolean} [bitmask] The bitmask of comparison flags. * The bitmask may be composed of the following flags: * 1 - Unordered comparison * 2 - Partial comparison * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, bitmask, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, 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 {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparisons. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = getTag(object); objTag = objTag == argsTag ? objectTag : objTag; } if (!othIsArr) { othTag = getTag(other); othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag; if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); } if (!(bitmask & PARTIAL_COMPARE_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, customizer, bitmask, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, equalFunc, customizer, bitmask, stack); } /** * 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, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, 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) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * 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[objectToString.call(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 `_.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, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); }; } /** * 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 `_.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 (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the cast property path array. */ function castPath(value) { return isArray(value) ? value : stringToPath(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 {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_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 & UNORDERED_COMPARE_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 (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { return seen.add(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, 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 {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @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, equalFunc, customizer, bitmask, 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 & PARTIAL_COMPARE_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 |= UNORDERED_COMPARE_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, 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 {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(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, customizer, bitmask, 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; } /** * 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; } /** * 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, // for data views in Edge < 14, and promises in Node.js. 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 = objectToString.call(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : undefined; 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; }; } /** * 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 = isKey(path, object) ? [path] : castPath(path); var result, index = -1, length = path.length; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result) { return result; } var length = object ? object.length : 0; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * 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) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * 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 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 `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))); }; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoize(function(string) { string = toString(string); var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.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 process. * @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 ''; } /** * 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 ? array.length : 0; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, baseIteratee(predicate, 3), index); } /** * 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 `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 && 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); return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Assign cache to `_.memoize`. memoize.Cache = MapCache; /** * 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 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 */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * 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 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 `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) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * 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 && (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 && typeof value == 'object'; } /** * 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) && objectToString.call(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; /** * 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 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 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 process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /** * 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 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 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); } /** * 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; } /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = findIndex; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5), __webpack_require__(196)(module))) /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** 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')(); /** * 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; } /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var Symbol = root.Symbol, propertyIsEnumerable = objectProto.propertyIsEnumerable, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** * 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; } /** * 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]); } /** * 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 ? array.length : 0; return length ? baseFlatten(array, 1) : []; } /** * 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 */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * 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 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 `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) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * 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 && (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 && typeof value == 'object'; } module.exports = flatten; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }, /* 163 */ /***/ function(module, exports) { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]', symbolTag = '[object Symbol]'; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** 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 octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * 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; } /** * 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) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || 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; } /** * 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 ? array.length : 0; 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); } /** * 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 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); } /** * 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) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * 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 && (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 && typeof value == 'object'; } /** * 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) && objectToString.call(value) == symbolTag); } /** * 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 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); } module.exports = slice; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** 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')(); /** * 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 `_.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 ? array.length : 0; 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 ? array.length : 0; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * 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; } /** * 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) { if (value !== value) { return baseFindIndex(array, baseIsNaN, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (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; } /** * 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); } /** * 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 `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } 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; } /** 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 = root['__core-js_shared__']; /** 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 decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** 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 Symbol = root.Symbol, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'), Set = getNative(root, 'Set'), nativeCreate = getNative(Object, 'create'); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; 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) : {}; } /** * 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) { return this.has(key) && delete this.__data__[key]; } /** * 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__; 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 ? entries.length : 0; 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__ = []; } /** * 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); } 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) { 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 ? entries.length : 0; 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.__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) { return getMapData(this, key)['delete'](key); } /** * 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) { getMapData(this, key).set(key, value); 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 ? values.length : 0; 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; /** * 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; } /** * 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 `_.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) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * 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) { 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] = array; return apply(func, this, otherArgs); }; } /** * 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; } /** * 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); }; /** * 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 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; } /** * 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 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 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); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @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 ''; } /** * 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 ? array.length : 0; return length ? array[length - 1] : undefined; } /** * 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); if (isArrayLikeObject(comparator)) { comparator = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * 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 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 */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * 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 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 `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) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * 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 && (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 && typeof value == 'object'; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } module.exports = unionWith; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }, /* 165 */ /***/ function(module, exports) { var looper = module.exports = function (fun) { return function next (a, b, c) { var loop = true, returned = false, sync = false do { sync = true; loop = false fun.call(function (x, y, z) { if(sync) { a = x; b = y; c = z loop = true } else next(x, y, z) }, a, b, c) sync = false } while(loop) } } /***/ }, /* 166 */ /***/ 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__(25))) /***/ }, /* 167 */ /***/ function(module, exports) { module.exports = function (stream) { var read, started = false, id = Math.random() function consume (_read) { if(!_read) throw new Error('must be passed a readable') read = _read if(started) stream(read) } consume.resolve = consume.ready = consume.start = function (_stream) { started = true; stream = _stream || stream if(read) stream(read) return consume } return consume } /***/ }, /* 168 */ /***/ function(module, exports) { module.exports = pullPushable function pullPushable (onClose) { // create a buffer for data // that have been pushed // but not yet pulled. var buffer = [] // a pushable is a source stream // (abort, cb) => cb(end, data) // // when pushable is pulled, // keep references to abort and cb // so we can call back after // .end(end) or .push(data) var abort, cb function read (_abort, _cb) { if (_abort) { abort = _abort // if there is already a cb waiting, abort it. if (cb) callback(abort) } cb = _cb drain() } var ended read.end = function (end) { ended = ended || end || true // attempt to drain drain() } read.push = function (data) { if (ended) return // if sink already waiting, // we can call back directly. if (cb) { callback(abort, data) return } // otherwise push data and // attempt to drain buffer.push(data) drain() } return read // `drain` calls back to (if any) waiting // sink with abort, end, or next data. function drain () { if (!cb) return if (abort) callback(abort) else if (!buffer.length && ended) callback(ended) else if (buffer.length) callback(null, buffer.shift()) } // `callback` calls back to waiting sink, // and removes references to sink cb. function callback (err, val) { var _cb = cb // if error and pushable passed onClose, call it // the first time this stream ends or errors. if (err && onClose) { var c = onClose onClose = null c(err === true ? null : err) } cb = null _cb(err, val) } } /***/ }, /* 169 */ /***/ function(module, exports) { "use strict"; 'use strict' module.exports = function pull (a) { var length = arguments.length if (typeof a === 'function' && a.length === 1) { var args = new Array(length) for(var i = 0; i < length; i++) args[i] = arguments[i] return function (read) { if (args == null) { throw new TypeError("partial sink should only be called once!") } // Grab the reference after the check, because it's always an array now // (engines like that kind of consistency). var ref = args args = null // Prioritize common case of small number of pulls. switch (length) { case 1: return pull(read, ref[0]) case 2: return pull(read, ref[0], ref[1]) case 3: return pull(read, ref[0], ref[1], ref[2]) case 4: return pull(read, ref[0], ref[1], ref[2], ref[3]) default: ref.unshift(read) return pull.apply(null, ref) } } } var read = a if (read && typeof read.source === 'function') { read = read.source } for (var i = 1; i < length; i++) { var s = arguments[i] if (typeof s === 'function') { read = s(read) } else if (s && typeof s === 'object') { s.sink(read) read = s.source } } return read } /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var reduce = __webpack_require__(50) module.exports = function collect (cb) { return reduce(function (arr, item) { arr.push(item) return arr }, [], cb) } /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var reduce = __webpack_require__(50) module.exports = function concat (cb) { return reduce(function (a, b) { return a + b }, '', cb) } /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' function id (e) { return e } var prop = __webpack_require__(27) var drain = __webpack_require__(26) module.exports = function find (test, cb) { var ended = false if(!cb) cb = test, test = id else test = prop(test) || id return drain(function (data) { if(test(data)) { ended = true cb(null, data) return false } }, function (err) { if(ended) return //already called back cb(err === true ? null : err, null) }) } /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' module.exports = { drain: __webpack_require__(26), onEnd: __webpack_require__(175), log: __webpack_require__(174), find: __webpack_require__(172), reduce: __webpack_require__(50), collect: __webpack_require__(170), concat: __webpack_require__(171) } /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var drain = __webpack_require__(26) module.exports = function log (done) { return drain(function (data) { console.log(data) }, done) } /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var drain = __webpack_require__(26) module.exports = function onEnd (done) { return drain(null, done) } /***/ }, /* 176 */ /***/ function(module, exports) { "use strict"; 'use strict' module.exports = function count (max) { var i = 0; max = max || Infinity return function (end, cb) { if(end) return cb && cb(end) if(i > max) return cb(true) cb(null, i++) } } /***/ }, /* 177 */ /***/ function(module, exports) { "use strict"; 'use strict' //a stream that ends immediately. module.exports = function empty () { return function (abort, cb) { cb(true) } } /***/ }, /* 178 */ /***/ function(module, exports) { "use strict"; 'use strict' //a stream that errors immediately. module.exports = function error (err) { return function (abort, cb) { cb(err) } } /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' module.exports = { keys: __webpack_require__(181), once: __webpack_require__(78), values: __webpack_require__(51), count: __webpack_require__(176), infinite: __webpack_require__(180), empty: __webpack_require__(177), error: __webpack_require__(178) } /***/ }, /* 180 */ /***/ function(module, exports) { "use strict"; 'use strict' module.exports = function infinite (generate) { generate = generate || Math.random return function (end, cb) { if(end) return cb && cb(end) return cb(null, generate()) } } /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var values = __webpack_require__(51) module.exports = function (object) { return values(Object.keys(object)) } /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' function id (e) { return e } var prop = __webpack_require__(27) module.exports = function asyncMap (map) { if(!map) return id map = prop(map) var busy = false, abortCb, aborted return function (read) { return function next (abort, cb) { if(aborted) return cb(aborted) if(abort) { aborted = abort if(!busy) read(abort, cb) else read(abort, function () { //if we are still busy, wait for the mapper to complete. if(busy) abortCb = cb else cb(abort) }) } else read(null, function (end, data) { if(end) cb(end) else if(aborted) cb(aborted) else { busy = true map(data, function (err, data) { busy = false if(aborted) { cb(aborted) abortCb(aborted) } else if(err) next (err, cb) else cb(null, data) }) } }) } } } /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var tester = __webpack_require__(81) var filter = __webpack_require__(52) module.exports = function filterNot (test) { test = tester(test) return filter(function (data) { return !test(data) }) } /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var values = __webpack_require__(51) var once = __webpack_require__(78) //convert a stream of arrays or streams into just a stream. module.exports = function flatten () { return function (read) { var _read return function (abort, cb) { if (abort) { //abort the current stream, and then stream of streams. _read ? _read(abort, function(err) { read(err || abort, cb) }) : read(abort, cb) } else if(_read) nextChunk() else nextStream() function nextChunk () { _read(null, function (err, data) { if (err === true) nextStream() else if (err) { read(true, function(abortErr) { // TODO: what do we do with the abortErr? cb(err) }) } else cb(null, data) }) } function nextStream () { _read = null read(null, function (end, stream) { if(end) return cb(end) if(Array.isArray(stream) || stream && 'object' === typeof stream) stream = values(stream) else if('function' != typeof stream) stream = once(stream) _read = stream nextChunk() }) } } } } /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' module.exports = { map: __webpack_require__(186), asyncMap: __webpack_require__(182), filter: __webpack_require__(52), filterNot: __webpack_require__(183), through: __webpack_require__(189), take: __webpack_require__(188), unique: __webpack_require__(79), nonUnique: __webpack_require__(187), flatten: __webpack_require__(184) } /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' function id (e) { return e } var prop = __webpack_require__(27) module.exports = function map (mapper) { if(!mapper) return id mapper = prop(mapper) return function (read) { return function (abort, cb) { read(abort, function (end, data) { try { data = !end ? mapper(data) : null } catch (err) { return read(err, function () { return cb(err) }) } cb(end, data) }) } } } /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 'use strict' var unique = __webpack_require__(79) //passes an item through when you see it for the second time. module.exports = function nonUnique (field) { return unique(field, true) } /***/ }, /* 188 */ /***/ function(module, exports) { "use strict"; 'use strict' //read a number of items and then stop. module.exports = function take (test, opts) { opts = opts || {} var last = opts.last || false // whether the first item for which !test(item) should still pass var ended = false if('number' === typeof test) { last = true var n = test; test = function () { return --n } } return function (read) { function terminate (cb) { read(true, function (err) { last = false; cb(err || true) }) } return function (end, cb) { if(ended) last ? terminate(cb) : cb(ended) else if(ended = end) read(ended, cb) else read(null, function (end, data) { if(ended = ended || end) { //last ? terminate(cb) : cb(ended) } else if(!test(data)) { ended = true last ? cb(null, data) : terminate(cb) } else cb(null, data) }) } } } /***/ }, /* 189 */ /***/ function(module, exports) { "use strict"; 'use strict' //a pass through stream that doesn't change the value. module.exports = function through (op, onEnd) { var a = false function once (abort) { if(a || !onEnd) return a = true onEnd(abort === true ? null : abort) } return function (read) { return function (end, cb) { if(end) once(end) return read(end, function (end, data) { if(!end) op && op(data) else once(end) cb(end, data) }) } } } /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { var looper = __webpack_require__(165) var window = module.exports = function (init, start) { return function (read) { start = start || function (start, data) { return {start: start, data: data} } var windows = [], output = [], ended = null var data, end var j = 0 return function (abort, cb) { if(output.length) return cb(null, output.shift()) if(ended) return cb(ended) var i = 0 var k = j ++ read(abort, looper(function (end, data) { var next = this var reduce, update, once = false if(end) ended = end function _update (end, _data) { if(once) return once = true delete windows[windows.indexOf(update)] output.push(start(data, _data)) } if(!ended) update = init(data, _update) if(update) windows.push(update) else //don't allow data unless a window started here! once = true windows.forEach(function (update, i) { update(end, data) }) if(output.length) return cb(null, output.shift()) else if(ended) return cb(ended) else read(null, next) })) } }} window.recent = function (size, time) { var current = null return window(function (data, cb) { if(current) return current = [] var timer function done () { var _current = current current = null clearTimeout(timer) cb(null, _current) } if(time) timer = setTimeout(done, time) return function (end, data) { if(end) return done() current.push(data) if(size != null && current.length >= size) done() } }, function (_, data) { return data }) } window.sliding = function (reduce, width) { width = width || 10 var k = 0 return window(function (data, cb) { var acc var i = 0 var l = k++ return function (end, data) { if(end) return acc = reduce(acc, data) if(width <= ++ i) cb(null, acc) } }) } /***/ }, /* 191 */ /***/ function(module, exports) { //another idea: buffer 2* the max, but only call write with half of that, //this could manage cases where the read ahead is latent. Hmm, we probably //shouldn't guess at that here, just handle write latency. //how would we measure this anyway? function append (array, item) { (array = array || []).push(item) return array } module.exports = function (write, reduce, max, cb) { reduce = reduce || append var ended, _cb, _read function reader (read) { var queue = null, writing = false, length = 0 _read = read if(ended) return read(ended, function (err) { cb(err) _cb && _cb() }) var reading = false function more () { if(reading || ended) return reading = true read(null, function (err, data) { reading = false next(err, data) }) } function flush () { if(writing) return var _queue = queue queue = null; writing = true; length = 0 write(_queue, function (err) { writing = false if(ended === true && !length) cb(err) else if(ended && ended !== true) { cb(ended) _cb && _cb() } else if(err) read(ended = err, cb) //abort upstream. else if(length) flush() else more() }) } function next (end, data) { if(ended) return ended = end if(!ended) { queue = reduce(queue, data) length = (queue && queue.length) || 0 if(queue != null) flush() if(length < max) more() } else if(!writing) cb(ended === true ? null : ended) } reader.abort = function (__cb) { _cb = function (end) { __cb && __cb() } read(ended = new Error('aborted'), function (end) { end = end === true ? null : end if(!writing) { cb && cb(end) _cb && _cb(end) } }) } more() } reader.abort = function (cb) { ended = new Error('aborted before connecting') _cb = function (err) { cb && cb() } } return reader } /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a