From 8f990e0cccb995800e4b7c759b59e2726b02355f Mon Sep 17 00:00:00 2001 From: haad Date: Mon, 30 Jan 2017 11:10:24 +0200 Subject: [PATCH] Immutable ipfs-log Use immutable ipfs-log. Simplify internals. Remove obsolete dependencies. Update dependencies. Use @dignifiedquire's mapSeries for Promises. Split tests to individual stores. Improve tests. Fix build process. Build size down to 121kb. Fix benchmarks and examples. Move Cache to Stores (and to its own module). --- .gitignore | 1 + Makefile | 3 + conf/webpack.config.js | 67 +- conf/webpack.config.minified.js | 68 - conf/webpack.example.config.js | 2 +- dist/orbitdb.js | 14388 ++++-------------------------- dist/orbitdb.min.js | 29 +- examples/benchmark.js | 4 +- examples/browser/browser.html | 132 +- examples/browser/index.html | 5 +- examples/browser/index.js | 171 +- package.json | 47 +- src/Cache.js | 85 - src/OrbitDB.js | 76 +- test/client.test.js | 657 -- test/counterdb.test.js | 40 +- test/docstore.test.js | 191 + test/eventlog.test.js | 387 + test/feed.test.js | 428 + test/ipfs-daemons.conf.js | 14 +- test/kvstore.test.js | 163 + test/persistency.js | 96 + test/promise-map-series.js | 16 + test/replicate.test.js | 126 +- test/test-config.js | 18 + test/test-daemons.js | 9 + test/test-utils.js | 18 + 27 files changed, 3260 insertions(+), 13981 deletions(-) delete mode 100644 conf/webpack.config.minified.js delete mode 100644 src/Cache.js delete mode 100644 test/client.test.js create mode 100644 test/docstore.test.js create mode 100644 test/eventlog.test.js create mode 100644 test/feed.test.js create mode 100644 test/kvstore.test.js create mode 100644 test/persistency.js create mode 100644 test/promise-map-series.js create mode 100644 test/test-config.js create mode 100644 test/test-daemons.js create mode 100644 test/test-utils.js diff --git a/.gitignore b/.gitignore index 1eaf68e..90e9793 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ dump.rdb Vagrantfile examples/browser/bundle.js examples/browser/*.map +examples/browser/lib dist/*.map orbit-db/ ipfs/ diff --git a/Makefile b/Makefile index 1652ba6..8cad818 100644 --- a/Makefile +++ b/Makefile @@ -8,6 +8,9 @@ test: deps build: test npm run build + mkdir -p examples/browser/lib/ + cp dist/orbitdb.min.js examples/browser/lib/orbitdb.min.js + cp node_modules/ipfs-daemon/dist/ipfs-browser-daemon.min.js examples/browser/lib/ipfs-browser-daemon.min.js @echo "Build success!" @echo "Output: 'dist/', 'examples/browser/'" diff --git a/conf/webpack.config.js b/conf/webpack.config.js index 01ea6b9..e7d0c0c 100644 --- a/conf/webpack.config.js +++ b/conf/webpack.config.js @@ -1,3 +1,5 @@ +'use strict' + const webpack = require('webpack') const path = require('path') @@ -6,59 +8,26 @@ module.exports = { output: { libraryTarget: 'var', library: 'OrbitDB', - filename: './dist/orbitdb.js' + filename: './dist/orbitdb.min.js' }, - devtool: 'sourcemap', - stats: { - colors: true, - cached: false + devtool: 'source-map', + resolve: { + modules: [ + 'node_modules', + path.resolve(__dirname, '../node_modules') + ] + }, + resolveLoader: { + modules: [ + 'node_modules', + path.resolve(__dirname, '../node_modules') + ], + moduleExtensions: ['-loader'] }, node: { console: false, - process: 'mock', Buffer: true }, - plugins: [ - ], - resolve: { - modules: [ - path.join(__dirname, '../node_modules') - ], - alias: { - http: 'stream-http', - https: 'https-browserify', - Buffer: 'buffer' - } - }, - module: { - loaders: [ - { - test: /\.js$/, - exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: require.resolve('babel-preset-es2015'), - plugins: require.resolve('babel-plugin-transform-runtime') - } - }, - { - test: /\.js$/, - include: /node_modules\/(hoek|qs|wreck|boom|ipfs-.+|orbit-db.+|logplease|crdts|promisify-es6)/, - loader: 'babel-loader', - query: { - presets: require.resolve('babel-preset-es2015'), - plugins: require.resolve('babel-plugin-transform-runtime') - } - }, - { - test: /\.json$/, - loader: 'json-loader' - } - ] - }, - externals: { - net: '{}', - tls: '{}', - 'require-dir': '{}' - } + plugins: [], + target: 'web' } diff --git a/conf/webpack.config.minified.js b/conf/webpack.config.minified.js deleted file mode 100644 index efdbfd3..0000000 --- a/conf/webpack.config.minified.js +++ /dev/null @@ -1,68 +0,0 @@ -const webpack = require('webpack') -const path = require('path') - -module.exports = { - entry: './src/OrbitDB.js', - output: { - libraryTarget: 'var', - library: 'OrbitDB', - filename: './dist/orbitdb.min.js' - }, - devtool: 'sourcemap', - stats: { - colors: true, - cached: false - }, - node: { - console: false, - process: 'mock', - Buffer: true - }, - plugins: [ - new webpack.optimize.UglifyJsPlugin({ - mangle: false, - compress: { warnings: false } - }) - ], - resolve: { - modules: [ - path.join(__dirname, '../node_modules') - ], - alias: { - http: 'stream-http', - https: 'https-browserify', - Buffer: 'buffer' - } - }, - module: { - loaders: [ - { - test: /\.js$/, - exclude: /node_modules/, - loader: 'babel-loader', - query: { - presets: require.resolve('babel-preset-es2015'), - plugins: require.resolve('babel-plugin-transform-runtime') - } - }, - { - test: /\.js$/, - include: /node_modules\/(hoek|qs|wreck|boom|ipfs-.+|orbit-db.+|logplease|crdts|promisify-es6)/, - loader: 'babel-loader', - query: { - presets: require.resolve('babel-preset-es2015'), - plugins: require.resolve('babel-plugin-transform-runtime') - } - }, - { - test: /\.json$/, - loader: 'json-loader' - } - ] - }, - externals: { - net: '{}', - tls: '{}', - 'require-dir': '{}' - } -} diff --git a/conf/webpack.example.config.js b/conf/webpack.example.config.js index 876125e..cf3150a 100644 --- a/conf/webpack.example.config.js +++ b/conf/webpack.example.config.js @@ -33,7 +33,7 @@ module.exports = { // // Can be dropped once https://github.com/devongovett/browserify-zlib/pull/18 // is shipped - zlib: 'browserify-zlib', + zlib: 'browserify-zlib-next', // Can be dropped once https://github.com/webpack/node-libs-browser/pull/41 // is shipped http: 'stream-http' diff --git a/dist/orbitdb.js b/dist/orbitdb.js index 2551f6e..a7aaccd 100644 --- a/dist/orbitdb.js +++ b/dist/orbitdb.js @@ -64,7 +64,7 @@ var OrbitDB = /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 198); +/******/ return __webpack_require__(__webpack_require__.s = 191); /******/ }) /************************************************************************/ /******/ ([ @@ -126,8 +126,8 @@ 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) +var store = __webpack_require__(46)('wks') + , uid = __webpack_require__(33) , Symbol = __webpack_require__(4).Symbol , USE_SYMBOL = typeof Symbol == 'function'; @@ -149,64 +149,31 @@ 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__(20); +var isObject = __webpack_require__(18); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }), -/* 8 */ +/* 6 */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty -module.exports = !__webpack_require__(19)(function(){ +module.exports = !__webpack_require__(17)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }), -/* 9 */ +/* 7 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , core = __webpack_require__(2) - , ctx = __webpack_require__(23) - , hide = __webpack_require__(12) + , ctx = __webpack_require__(22) + , hide = __webpack_require__(11) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ @@ -266,15 +233,15 @@ $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), -/* 10 */ +/* 8 */ /***/ (function(module, exports, __webpack_require__) { -var anObject = __webpack_require__(7) - , IE8_DOM_DEFINE = __webpack_require__(62) - , toPrimitive = __webpack_require__(47) +var anObject = __webpack_require__(5) + , IE8_DOM_DEFINE = __webpack_require__(61) + , toPrimitive = __webpack_require__(48) , dP = Object.defineProperty; -exports.f = __webpack_require__(8) ? Object.defineProperty : function defineProperty(O, P, Attributes){ +exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); @@ -287,7 +254,13 @@ exports.f = __webpack_require__(8) ? Object.defineProperty : function defineProp }; /***/ }), -/* 11 */ +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = { "default": __webpack_require__(106), __esModule: true }; + +/***/ }), +/* 10 */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; @@ -296,12 +269,12 @@ module.exports = function(it, key){ }; /***/ }), -/* 12 */ +/* 11 */ /***/ (function(module, exports, __webpack_require__) { -var dP = __webpack_require__(10) - , createDesc = __webpack_require__(32); -module.exports = __webpack_require__(8) ? function(object, key, value){ +var dP = __webpack_require__(8) + , createDesc = __webpack_require__(30); +module.exports = __webpack_require__(6) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; @@ -309,30 +282,30 @@ module.exports = __webpack_require__(8) ? function(object, key, value){ }; /***/ }), -/* 13 */ +/* 12 */ /***/ (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); +var IObject = __webpack_require__(62) + , defined = __webpack_require__(39); module.exports = function(it){ return IObject(defined(it)); }; /***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = { "default": __webpack_require__(112), __esModule: true }; - -/***/ }), -/* 15 */ +/* 13 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(111), __esModule: true }; /***/ }), -/* 16 */ +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = { "default": __webpack_require__(110), __esModule: true }; + +/***/ }), +/* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -348,7 +321,7 @@ var _create = __webpack_require__(99); var _create2 = _interopRequireDefault(_create); -var _typeof2 = __webpack_require__(59); +var _typeof2 = __webpack_require__(58); var _typeof3 = _interopRequireDefault(_typeof2); @@ -371,7 +344,7 @@ exports.default = function (subClass, superClass) { }; /***/ }), -/* 17 */ +/* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -379,7 +352,7 @@ exports.default = function (subClass, superClass) { exports.__esModule = true; -var _typeof2 = __webpack_require__(59); +var _typeof2 = __webpack_require__(58); var _typeof3 = _interopRequireDefault(_typeof2); @@ -393,8 +366,40 @@ exports.default = function (self, call) { return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; }; +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + +module.exports = function(exec){ + try { + return !!exec(); + } catch(e){ + return true; + } +}; + /***/ }), /* 18 */ +/***/ (function(module, exports) { + +module.exports = function(it){ + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +// 19.1.2.14 / 15.2.3.14 Object.keys(O) +var $keys = __webpack_require__(68) + , enumBugKeys = __webpack_require__(41); + +module.exports = Object.keys || function keys(O){ + return $keys(O, enumBugKeys); +}; + +/***/ }), +/* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -409,8 +414,8 @@ exports.default = function (self, call) { var base64 = __webpack_require__(104) -var ieee754 = __webpack_require__(155) -var isArray = __webpack_require__(158) +var ieee754 = __webpack_require__(154) +var isArray = __webpack_require__(157) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer @@ -2188,42 +2193,10 @@ function isnan (val) { return val !== val // eslint-disable-line no-self-compare } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) - -/***/ }), -/* 19 */ -/***/ (function(module, exports) { - -module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; - } -}; - -/***/ }), -/* 20 */ -/***/ (function(module, exports) { - -module.exports = function(it){ - return typeof it === 'object' ? it !== null : typeof it === 'function'; -}; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(35))) /***/ }), /* 21 */ -/***/ (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); -}; - -/***/ }), -/* 22 */ /***/ (function(module, exports) { var toString = {}.toString; @@ -2233,11 +2206,11 @@ module.exports = function(it){ }; /***/ }), -/* 23 */ +/* 22 */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding -var aFunction = __webpack_require__(37); +var aFunction = __webpack_require__(38); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; @@ -2258,49 +2231,13 @@ module.exports = function(fn, that, length){ }; /***/ }), -/* 24 */ +/* 23 */ /***/ (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 */ +/* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -2355,7 +2292,7 @@ module.exports = function drain (op, done) { /***/ }), -/* 27 */ +/* 25 */ /***/ (function(module, exports) { module.exports = function prop (key) { @@ -2369,10 +2306,271 @@ module.exports = function prop (key) { } +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _promise = __webpack_require__(27); + +var _promise2 = _interopRequireDefault(_promise); + +var _assign = __webpack_require__(9); + +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__(36).EventEmitter; +var Log = __webpack_require__(90); +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 = Log.create(this._ipfs); + this._lastWrite = []; + } + + (0, _createClass3.default)(Store, [{ + 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.fromMultihash(this._ipfs, hash, this.options.maxHistory, this._onLoadProgress.bind(this)).then(function (log) { + return Log.join(_this._ipfs, _this._oplog, log); + }).then(function (merged) { + _this._index.updateIndex(_this._oplog); + _this.events.emit('load.end', _this.dbname); + _this.events.emit('ready', _this.dbname); + 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(hash); + + var newItems = []; + if (hash) this._lastWrite.push(hash); + this.events.emit('sync', this.dbname); + var startTime = new Date().getTime(); + return Log.fromMultihash(this._ipfs, hash, this.options.maxHistory, this._onLoadProgress.bind(this)).then(function (log) { + _this2._oplog = Log.join(_this2._ipfs, _this2._oplog, log); + _this2._index.updateIndex(_this2._oplog); + _this2.events.emit('load.end', _this2.dbname); + _this2.events.emit('synced', _this2.dbname); + }).then(function () { + return Log.toMultihash(_this2._ipfs, _this2._oplog); + }); + } + }, { + key: '_addOperation', + value: function _addOperation(data) { + var _this3 = this; + + var result = void 0, + logHash = void 0; + if (this._oplog) { + return Log.append(this._ipfs, this._oplog, data).then(function (res) { + return _this3._oplog = res; + }).then(function () { + return Log.toMultihash(_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, _this3._oplog.items[_this3._oplog.items.length - 1].hash); + }).then(function () { + return _this3._oplog.items[_this3._oplog.items.length - 1].hash; + }); + } + } + }, { + key: '_onLoadProgress', + value: function _onLoadProgress(hash, entry, parent, depth) { + this.events.emit('load.progress', this.dbname, depth); + } + }]); + return Store; +}(); + +module.exports = Store; + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = { "default": __webpack_require__(113), __esModule: true }; + /***/ }), /* 28 */ /***/ (function(module, exports) { +module.exports = true; + +/***/ }), +/* 29 */ +/***/ (function(module, exports) { + +exports.f = {}.propertyIsEnumerable; + +/***/ }), +/* 30 */ +/***/ (function(module, exports) { + +module.exports = function(bitmap, value){ + return { + enumerable : !(bitmap & 1), + configurable: !(bitmap & 2), + writable : !(bitmap & 4), + value : value + }; +}; + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +var def = __webpack_require__(8).f + , has = __webpack_require__(10) + , 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}); +}; + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +// 7.1.13 ToObject(argument) +var defined = __webpack_require__(39); +module.exports = function(it){ + return Object(defined(it)); +}; + +/***/ }), +/* 33 */ +/***/ (function(module, exports) { + +var id = 0 + , px = Math.random(); +module.exports = function(key){ + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); +}; + +/***/ }), +/* 34 */ +/***/ (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__(160); + cwd = path.resolve(dir, cwd); + }; +})(); + +exports.exit = exports.kill = +exports.umask = exports.dlopen = +exports.uptime = exports.memoryUsage = +exports.uvCounters = function() {}; +exports.features = {}; + + +/***/ }), +/* 35 */ +/***/ (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; + + +/***/ }), +/* 36 */ +/***/ (function(module, exports) { + // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -2677,251 +2875,14 @@ function isUndefined(arg) { } -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - -"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(hash); - - 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.slice().reverse().forEach(function (e) { - return _this2.events.emit('data', _this2.dbname, e); - }); - }).then(function () { - return Log.getIpfsHash(_this2._ipfs, _this2._oplog); - }); - } - }, { - 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, __webpack_require__) { + +module.exports = { "default": __webpack_require__(105), __esModule: true }; + +/***/ }), +/* 38 */ /***/ (function(module, exports) { module.exports = function(it){ @@ -2930,7 +2891,7 @@ module.exports = function(it){ }; /***/ }), -/* 38 */ +/* 39 */ /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) @@ -2940,10 +2901,10 @@ module.exports = function(it){ }; /***/ }), -/* 39 */ +/* 40 */ /***/ (function(module, exports, __webpack_require__) { -var isObject = __webpack_require__(20) +var isObject = __webpack_require__(18) , document = __webpack_require__(4).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); @@ -2952,7 +2913,7 @@ module.exports = function(it){ }; /***/ }), -/* 40 */ +/* 41 */ /***/ (function(module, exports) { // IE 8- don't enum bug keys @@ -2961,27 +2922,27 @@ module.exports = ( ).split(','); /***/ }), -/* 41 */ +/* 42 */ /***/ (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') +var anObject = __webpack_require__(5) + , dPs = __webpack_require__(132) + , enumBugKeys = __webpack_require__(41) + , IE_PROTO = __webpack_require__(45)('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') + var iframe = __webpack_require__(40)('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; - __webpack_require__(61).appendChild(iframe); + __webpack_require__(60).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); @@ -3008,19 +2969,19 @@ module.exports = Object.create || function create(O, Properties){ /***/ }), -/* 42 */ +/* 43 */ /***/ (function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }), -/* 43 */ +/* 44 */ /***/ (function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives -var $export = __webpack_require__(9) +var $export = __webpack_require__(7) , core = __webpack_require__(2) - , fails = __webpack_require__(19); + , fails = __webpack_require__(17); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; @@ -3029,17 +2990,17 @@ module.exports = function(KEY, exec){ }; /***/ }), -/* 44 */ +/* 45 */ /***/ (function(module, exports, __webpack_require__) { -var shared = __webpack_require__(45)('keys') - , uid = __webpack_require__(35); +var shared = __webpack_require__(46)('keys') + , uid = __webpack_require__(33); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; /***/ }), -/* 45 */ +/* 46 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(4) @@ -3050,7 +3011,7 @@ module.exports = function(key){ }; /***/ }), -/* 46 */ +/* 47 */ /***/ (function(module, exports) { // 7.1.4 ToInteger @@ -3061,11 +3022,11 @@ module.exports = function(it){ }; /***/ }), -/* 47 */ +/* 48 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) -var isObject = __webpack_require__(20); +var isObject = __webpack_require__(18); // 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){ @@ -3078,33 +3039,33 @@ module.exports = function(it, S){ }; /***/ }), -/* 48 */ +/* 49 */ /***/ (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; + , LIBRARY = __webpack_require__(28) + , wksExt = __webpack_require__(50) + , defineProperty = __webpack_require__(8).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 */ +/* 50 */ /***/ (function(module, exports, __webpack_require__) { exports.f = __webpack_require__(3); /***/ }), -/* 50 */ +/* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var drain = __webpack_require__(26) +var drain = __webpack_require__(24) module.exports = function reduce (reducer, acc, cb ) { if(!cb) cb = acc, acc = null @@ -3127,12 +3088,12 @@ module.exports = function reduce (reducer, acc, cb ) { /***/ }), -/* 51 */ +/* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var abortCb = __webpack_require__(80) +var abortCb = __webpack_require__(78) module.exports = function values (array, onAbort) { if(!array) @@ -3157,13 +3118,13 @@ module.exports = function values (array, onAbort) { /***/ }), -/* 52 */ +/* 53 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var tester = __webpack_require__(81) +var tester = __webpack_require__(79) module.exports = function filter (test) { //regexp @@ -3187,65 +3148,6 @@ module.exports = function filter (test) { -/***/ }), -/* 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__) { @@ -3257,15 +3159,15 @@ var _defineProperty2 = __webpack_require__(103); var _defineProperty3 = _interopRequireDefault(_defineProperty2); -var _iterator2 = __webpack_require__(58); +var _iterator2 = __webpack_require__(57); var _iterator3 = _interopRequireDefault(_iterator2); -var _getPrototypeOf = __webpack_require__(15); +var _getPrototypeOf = __webpack_require__(14); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); -var _assign = __webpack_require__(6); +var _assign = __webpack_require__(9); var _assign2 = _interopRequireDefault(_assign); @@ -3277,20 +3179,17 @@ var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); -var _possibleConstructorReturn2 = __webpack_require__(17); +var _possibleConstructorReturn2 = __webpack_require__(16); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); -var _inherits2 = __webpack_require__(16); +var _inherits2 = __webpack_require__(15); 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 Store = __webpack_require__(26); var EventIndex = __webpack_require__(55); var EventStore = function (_Store) { @@ -3349,7 +3248,7 @@ var EventStore = function (_Store) { 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 events = this._index.get().slice(); var result = []; if (opts.gt || opts.gte) { @@ -3366,13 +3265,15 @@ var EventStore = function (_Store) { 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); + var index = ops.map(function (e) { + return e.hash; + }).indexOf(hash); + var startIndex = Math.max(index, 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); + var res = ops.slice(startIndex).slice(0, amount); + return res; } }]); return EventStore; @@ -3387,7 +3288,7 @@ module.exports = EventStore; "use strict"; -var _keys = __webpack_require__(14); +var _keys = __webpack_require__(13); var _keys2 = _interopRequireDefault(_keys); @@ -3419,11 +3320,11 @@ var EventIndex = function () { } }, { key: 'updateIndex', - value: function updateIndex(oplog, added) { + value: function updateIndex(oplog) { var _this2 = this; - added.reduce(function (handled, item) { - if (!handled.includes(item.hash)) { + oplog.items.reduce(function (handled, item) { + if (!handled.includes(item.hash) && !_this2._index[item.hash]) { handled.push(item.hash); if (item.payload.op === 'ADD') _this2._index[item.hash] = item; } @@ -3440,30 +3341,24 @@ module.exports = EventIndex; /* 56 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(109), __esModule: true }; +module.exports = { "default": __webpack_require__(108), __esModule: true }; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(114), __esModule: true }; +module.exports = { "default": __webpack_require__(115), __esModule: true }; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(116), __esModule: true }; - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - "use strict"; exports.__esModule = true; -var _iterator = __webpack_require__(58); +var _iterator = __webpack_require__(57); var _iterator2 = _interopRequireDefault(_iterator); @@ -3482,11 +3377,11 @@ exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.d }; /***/ }), -/* 60 */ +/* 59 */ /***/ (function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() -var cof = __webpack_require__(22) +var cof = __webpack_require__(21) , TAG = __webpack_require__(3)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; @@ -3510,44 +3405,44 @@ module.exports = function(it){ }; /***/ }), -/* 61 */ +/* 60 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(4).document && document.documentElement; /***/ }), -/* 62 */ +/* 61 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = !__webpack_require__(8) && !__webpack_require__(19)(function(){ - return Object.defineProperty(__webpack_require__(39)('div'), 'a', {get: function(){ return 7; }}).a != 7; +module.exports = !__webpack_require__(6) && !__webpack_require__(17)(function(){ + return Object.defineProperty(__webpack_require__(40)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }), -/* 63 */ +/* 62 */ /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings -var cof = __webpack_require__(22); +var cof = __webpack_require__(21); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), -/* 64 */ +/* 63 */ /***/ (function(module, exports, __webpack_require__) { "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) +var LIBRARY = __webpack_require__(28) + , $export = __webpack_require__(7) + , redefine = __webpack_require__(69) + , hide = __webpack_require__(11) + , has = __webpack_require__(10) + , Iterators = __webpack_require__(23) + , $iterCreate = __webpack_require__(125) + , setToStringTag = __webpack_require__(31) + , getPrototypeOf = __webpack_require__(67) , ITERATOR = __webpack_require__(3)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' @@ -3610,18 +3505,18 @@ module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED }; /***/ }), -/* 65 */ +/* 64 */ /***/ (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) +var pIE = __webpack_require__(29) + , createDesc = __webpack_require__(30) + , toIObject = __webpack_require__(12) + , toPrimitive = __webpack_require__(48) + , has = __webpack_require__(10) + , IE8_DOM_DEFINE = __webpack_require__(61) , gOPD = Object.getOwnPropertyDescriptor; -exports.f = __webpack_require__(8) ? gOPD : function getOwnPropertyDescriptor(O, P){ +exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { @@ -3631,12 +3526,12 @@ exports.f = __webpack_require__(8) ? gOPD : function getOwnPropertyDescriptor(O, }; /***/ }), -/* 66 */ +/* 65 */ /***/ (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 +var toIObject = __webpack_require__(12) + , gOPN = __webpack_require__(66).f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames @@ -3656,25 +3551,25 @@ module.exports.f = function getOwnPropertyNames(it){ /***/ }), -/* 67 */ +/* 66 */ /***/ (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'); +var $keys = __webpack_require__(68) + , hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; /***/ }), -/* 68 */ +/* 67 */ /***/ (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') +var has = __webpack_require__(10) + , toObject = __webpack_require__(32) + , IE_PROTO = __webpack_require__(45)('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ @@ -3686,13 +3581,13 @@ module.exports = Object.getPrototypeOf || function(O){ }; /***/ }), -/* 69 */ +/* 68 */ /***/ (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'); +var has = __webpack_require__(10) + , toIObject = __webpack_require__(12) + , arrayIndexOf = __webpack_require__(118)(false) + , IE_PROTO = __webpack_require__(45)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) @@ -3707,20 +3602,20 @@ module.exports = function(object, names){ return result; }; +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = __webpack_require__(11); + /***/ }), /* 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) +var ctx = __webpack_require__(22) + , invoke = __webpack_require__(121) + , html = __webpack_require__(60) + , cel = __webpack_require__(40) , global = __webpack_require__(4) , process = global.process , setTask = global.setImmediate @@ -3756,7 +3651,7 @@ if(!setTask || !clearTask){ delete queue[id]; }; // Node.js 0.8- - if(__webpack_require__(22)(process) == 'process'){ + if(__webpack_require__(21)(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; @@ -3794,32 +3689,32 @@ module.exports = { }; /***/ }), -/* 72 */ +/* 71 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength -var toInteger = __webpack_require__(46) +var toInteger = __webpack_require__(47) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), -/* 73 */ +/* 72 */ /***/ (function(module, exports) { /***/ }), -/* 74 */ +/* 73 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var $at = __webpack_require__(138)(true); +var $at = __webpack_require__(137)(true); // 21.1.3.27 String.prototype[@@iterator]() -__webpack_require__(64)(String, 'String', function(iterated){ +__webpack_require__(63)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() @@ -3834,13 +3729,13 @@ __webpack_require__(64)(String, 'String', function(iterated){ }); /***/ }), -/* 75 */ +/* 74 */ /***/ (function(module, exports, __webpack_require__) { -__webpack_require__(141); +__webpack_require__(140); var global = __webpack_require__(4) - , hide = __webpack_require__(12) - , Iterators = __webpack_require__(24) + , hide = __webpack_require__(11) + , Iterators = __webpack_require__(23) , TO_STRING_TAG = __webpack_require__(3)('toStringTag'); for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ @@ -3852,321 +3747,17 @@ for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList' } /***/ }), -/* 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 */ +/* 75 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var sources = __webpack_require__(179) -var sinks = __webpack_require__(173) -var throughs = __webpack_require__(185) +var sources = __webpack_require__(173) +var sinks = __webpack_require__(167) +var throughs = __webpack_require__(179) -exports = module.exports = __webpack_require__(169) +exports = module.exports = __webpack_require__(163) for(var k in sources) exports[k] = sources[k] @@ -4180,12 +3771,12 @@ for(var k in sinks) /***/ }), -/* 78 */ +/* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var abortCb = __webpack_require__(80) +var abortCb = __webpack_require__(78) module.exports = function once (value, onAbort) { return function (abort, cb) { @@ -4203,15 +3794,15 @@ module.exports = function once (value, onAbort) { /***/ }), -/* 79 */ +/* 77 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function id (e) { return e } -var prop = __webpack_require__(27) -var filter = __webpack_require__(52) +var prop = __webpack_require__(25) +var filter = __webpack_require__(53) //drop items you have already seen. module.exports = function unique (field, invert) { @@ -4228,7 +3819,7 @@ module.exports = function unique (field, invert) { /***/ }), -/* 80 */ +/* 78 */ /***/ (function(module, exports) { module.exports = function abortCb(cb, abort, onAbort) { @@ -4240,10 +3831,10 @@ module.exports = function abortCb(cb, abort, onAbort) { /***/ }), -/* 81 */ +/* 79 */ /***/ (function(module, exports, __webpack_require__) { -var prop = __webpack_require__(27) +var prop = __webpack_require__(25) function id (e) { return e } @@ -4257,17 +3848,76 @@ module.exports = function tester (test) { /***/ }), -/* 82 */ +/* 80 */ +/***/ (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__(186); +exports.setImmediate = setImmediate; +exports.clearImmediate = clearImmediate; + + +/***/ }), +/* 81 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) { -var _stringify = __webpack_require__(36); +var _stringify = __webpack_require__(37); var _stringify2 = _interopRequireDefault(_stringify); -var _promise = __webpack_require__(57); +var _promise = __webpack_require__(27); var _promise2 = _interopRequireDefault(_promise); @@ -4281,9 +3931,9 @@ 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 pull = __webpack_require__(75); +var BlobStore = __webpack_require__(153); +var Lock = __webpack_require__(158); var filePath = void 0; var store = void 0; @@ -4370,20 +4020,20 @@ var Cache = function () { }(); module.exports = Cache; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18).Buffer)) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer)) /***/ }), -/* 83 */ +/* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _getPrototypeOf = __webpack_require__(15); +var _getPrototypeOf = __webpack_require__(14); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); -var _assign = __webpack_require__(6); +var _assign = __webpack_require__(9); var _assign2 = _interopRequireDefault(_assign); @@ -4395,17 +4045,17 @@ var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); -var _possibleConstructorReturn2 = __webpack_require__(17); +var _possibleConstructorReturn2 = __webpack_require__(16); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); -var _inherits2 = __webpack_require__(16); +var _inherits2 = __webpack_require__(15); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var Store = __webpack_require__(29); +var Store = __webpack_require__(26); var CounterIndex = __webpack_require__(93); var CounterStore = function (_Store) { @@ -4447,21 +4097,21 @@ var CounterStore = function (_Store) { module.exports = CounterStore; /***/ }), -/* 84 */ +/* 83 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _keys = __webpack_require__(14); +var _keys = __webpack_require__(13); var _keys2 = _interopRequireDefault(_keys); -var _getPrototypeOf = __webpack_require__(15); +var _getPrototypeOf = __webpack_require__(14); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); -var _assign = __webpack_require__(6); +var _assign = __webpack_require__(9); var _assign2 = _interopRequireDefault(_assign); @@ -4473,17 +4123,17 @@ var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); -var _possibleConstructorReturn2 = __webpack_require__(17); +var _possibleConstructorReturn2 = __webpack_require__(16); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); -var _inherits2 = __webpack_require__(16); +var _inherits2 = __webpack_require__(15); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var Store = __webpack_require__(29); +var Store = __webpack_require__(26); var DocumentIndex = __webpack_require__(94); var DocumentStore = function (_Store) { @@ -4551,17 +4201,17 @@ var DocumentStore = function (_Store) { module.exports = DocumentStore; /***/ }), -/* 85 */ +/* 84 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _getPrototypeOf = __webpack_require__(15); +var _getPrototypeOf = __webpack_require__(14); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); -var _assign = __webpack_require__(6); +var _assign = __webpack_require__(9); var _assign2 = _interopRequireDefault(_assign); @@ -4573,11 +4223,11 @@ var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); -var _possibleConstructorReturn2 = __webpack_require__(17); +var _possibleConstructorReturn2 = __webpack_require__(16); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); -var _inherits2 = __webpack_require__(16); +var _inherits2 = __webpack_require__(15); var _inherits3 = _interopRequireDefault(_inherits2); @@ -4617,17 +4267,17 @@ var FeedStore = function (_EventStore) { module.exports = FeedStore; /***/ }), -/* 86 */ +/* 85 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _getPrototypeOf = __webpack_require__(15); +var _getPrototypeOf = __webpack_require__(14); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); -var _assign = __webpack_require__(6); +var _assign = __webpack_require__(9); var _assign2 = _interopRequireDefault(_assign); @@ -4639,17 +4289,17 @@ var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); -var _possibleConstructorReturn2 = __webpack_require__(17); +var _possibleConstructorReturn2 = __webpack_require__(16); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); -var _inherits2 = __webpack_require__(16); +var _inherits2 = __webpack_require__(15); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var Store = __webpack_require__(29); +var Store = __webpack_require__(26); var KeyValueIndex = __webpack_require__(96); var KeyValueStore = function (_Store) { @@ -4671,7 +4321,7 @@ var KeyValueStore = function (_Store) { }, { key: 'set', value: function set(key, data) { - this.put(key, data); + return this.put(key, data); } }, { key: 'put', @@ -4704,7 +4354,7 @@ var KeyValueStore = function (_Store) { module.exports = KeyValueStore; /***/ }), -/* 87 */ +/* 86 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -4713,13 +4363,13 @@ module.exports = KeyValueStore; module.exports = __webpack_require__(97); /***/ }), -/* 88 */ +/* 87 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _keys = __webpack_require__(14); +var _keys = __webpack_require__(13); var _keys2 = _interopRequireDefault(_keys); @@ -4733,7 +4383,7 @@ var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var isEqual = __webpack_require__(89).isEqual; +var isEqual = __webpack_require__(88).isEqual; var GCounter = function () { function GCounter(id, payload) { @@ -4794,7 +4444,7 @@ var GCounter = function () { module.exports = GCounter; /***/ }), -/* 89 */ +/* 88 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -4821,13 +4471,13 @@ exports.isEqual = function (a, b) { }; /***/ }), -/* 90 */ +/* 89 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) { -var _stringify = __webpack_require__(36); +var _stringify = __webpack_require__(37); var _stringify2 = _interopRequireDefault(_stringify); @@ -4841,7 +4491,7 @@ var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = function () { +var Entry = function () { function Entry() { (0, _classCallCheck3.default)(this, Entry); } @@ -4849,17 +4499,27 @@ module.exports = function () { (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) { + /** + * Create an Entry + * @param {IPFS} ipfs - An IPFS instance + * @param {string|Buffer|Object|Array} data - Data of the entry to be added + * @param {Array} [next=[]] Parents of the entry + * @example + * const entry = await Entry.create(ipfs, 'hello') + * console.log(entry) + * // { hash: "Qm...Foo", payload: "hello", next: [] } + * @returns {Promise} + */ + value: function create(ipfs) { + var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; 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) { + var nexts = next !== null && Array.isArray(next) ? next.filter(function (e) { + return e !== undefined; + }).map(function (e) { return e.hash ? e.hash : e; }) : [next !== null && next.hash ? next.hash : next]; @@ -4869,20 +4529,27 @@ module.exports = function () { next: nexts // Array of IPFS hashes }; - return Entry.toIpfsHash(ipfs, entry).then(function (hash) { + return Entry.toMultihash(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" + /** + * Get the multihash of an Entry + * @param {IPFS} [ipfs] An IPFS instance + * @param {string|Buffer|Object|Array} [data] Data of the entry to be added + * @param {Array} [next=[]] Parents of the entry + * @example + * const hash = await Entry.toMultihash(ipfs, entry) + * console.log(hash) + * // "Qm...Foo" + * @returns {Promise} + */ }, { - key: "toIpfsHash", - value: function toIpfsHash(ipfs, entry) { + key: "toMultihash", + value: function toMultihash(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) { @@ -4890,18 +4557,25 @@ module.exports = function () { }); } - // Returns a Promise - // Example: - // Entry.fromIpfsHash(ipfs, "Qm...Foo") - // .then((entry) => console.log(entry)) // { hash: "Qm...Foo", payload: "hello", next: null } + /** + * Create an Entry from a multihash + * @param {IPFS} [ipfs] An IPFS instance + * @param {string} [hash] Multihash to create an Entry from + * @example + * const hash = await Entry.fromMultihash(ipfs, "Qm...Foo") + * console.log(hash) + * // { hash: "Qm...Foo", payload: "hello", next: [] } + * @returns {Promise} + */ }, { - key: "fromIpfsHash", - value: function fromIpfsHash(ipfs, hash) { + key: "fromMultihash", + value: function fromMultihash(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); + return JSON.parse(obj.toJSON().data); + }).then(function (data) { var entry = { hash: hash, payload: data.payload, @@ -4911,10 +4585,12 @@ module.exports = function () { }); } - // Returns a boolean - // Example: - // const hasChild = Entry.hasChild(entry1, entry2) - // true|false + /** + * Check if an entry has another entry as its child + * @param {Entry} [entry1] Entry to check from + * @param {Entry} [entry2] Child + * @returns {boolean} + */ }, { key: "hasChild", @@ -4922,36 +4598,50 @@ module.exports = function () { return entry1.next.includes(entry2.hash); } - // Returns a boolean - // Example: - // const equal = Entry.compare(entry1, entry2) - // true|false + /** + * Check if an entry equals another entry + * @param {Entry} a + * @param {Entry} b + * @returns {boolean} + */ }, { key: "compare", value: function compare(a, b) { return a.hash === b.hash; } + + /** + * @alias compare + */ + + }, { + key: "isEqual", + value: function isEqual(a, b) { + return a.hash === b.hash; + } }]); return Entry; }(); -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18).Buffer)) + +module.exports = Entry; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer)) /***/ }), -/* 91 */ +/* 90 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) { -var _stringify = __webpack_require__(36); +var _promise = __webpack_require__(27); + +var _promise2 = _interopRequireDefault(_promise); + +var _stringify = __webpack_require__(37); var _stringify2 = _interopRequireDefault(_stringify); -var _assign = __webpack_require__(6); - -var _assign2 = _interopRequireDefault(_assign); - var _classCallCheck2 = __webpack_require__(0); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); @@ -4962,202 +4652,536 @@ 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 Entry = __webpack_require__(89); +var mapSeries = __webpack_require__(91); -var MaxBatchSize = 10; // How many items to keep per local batch -var MaxHistory = 256; // How many items to fetch on join +/** + * ipfs-log + * + * @example + * // https://github.com/haadcode/ipfs-log/blob/master/examples/log.js + * const IPFS = require('ipfs-daemon') + * const Log = require('ipfs-log') + * const ipfs = new IPFS() + * + * ipfs.on('ready', () => { + * const log1 = Log.create(ipfs, ['one']) + * const log2 = Log.create(ipfs, [{ two: 'hello' }, { ok: true }]) + * const out = Log.join(ipfs, log2, log2) + * .collect() + * .map((e) => e.payload) + * .join('\n') + * console.log(out) + * // ['one', '{ two: 'hello' }', '{ ok: true }'] + * }) + */ var Log = function () { - function Log(ipfs, id, opts) { + function Log(ipfs, entries, heads) { (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(); + this._entries = entries || []; + this._heads = heads || LogUtils._findHeads(this) || []; } + /** + * Returns the items in the log + * @returns {Array} + */ + + (0, _createClass3.default)(Log, [{ - key: 'add', - value: function add(data) { + key: 'get', + + + /** + * Find a log entry + * @param {string} [hash] [The multihash of the entry] + * @returns {Entry|undefined} + */ + value: function get(hash) { + return this.items.find(function (e) { + return e.hash === hash; + }); + } + + /** + * Returns the log entries as a formatted string + * @example + * two + * └─one + * └─three + * @param {boolean} [withHash=false] - If set to 'true', the hash of the entry is included + * @returns {string} + */ + + }, { + key: 'toString', + value: function toString(withHash) { 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; - }); + return this.items.slice().reverse().map(function (e, idx) { + var parents = LogUtils._findParents(_this, e); + var len = parents.length; + var padding = new Array(Math.max(len - 1, 0)); + padding = len > 1 ? padding.fill(' ') : padding; + padding = len > 0 ? padding.concat(['└─']) : padding; + return padding.join('') + (withHash ? e.hash + ' ' : '') + e.payload; + }).join('\n'); } + + /** + * Get the log in JSON format + * @returns {Object<{heads}>} + */ + }, { - 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: 'toJSON', + value: function toJSON() { + return { heads: this.heads }; } + + /** + * Get the log as a Buffer + * @returns {Buffer} + */ + }, { - 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: 'toBuffer', + value: function toBuffer() { + return new Buffer((0, _stringify2.default)(this.toJSON())); } }, { key: 'items', get: function get() { - return this._items.concat(this._currentBatch); + return this._entries; } + + /** + * Returns a list of heads as multihashes + * @returns {Array} + */ + }, { - key: 'snapshot', + key: 'heads', get: function get() { - return { - id: this.id, - items: this._heads - }; - } - }], [{ - 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 this._heads; } }]); return Log; }(); -module.exports = Log; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18).Buffer)) +var LogUtils = function () { + function LogUtils() { + (0, _classCallCheck3.default)(this, LogUtils); + } + + (0, _createClass3.default)(LogUtils, null, [{ + key: 'create', + + /** + * Create a new log + * @param {IPFS} ipfs An IPFS instance + * @param {string} id - ID for the log + * @param {Array} [entries] - Entries for this log + * @param {Array} [heads] - Heads for this log + * @returns {Log} + */ + value: function create(ipfs, entries, heads) { + if (!ipfs) throw new Error('Ipfs instance not defined'); + // TODO: if (Array.isArray(entries)) + // TODO: entries.map((e) => Entry.isEntry(e) ? e : await Entry.create(ipfs, e)) + return new Log(ipfs, entries, heads); + } + + /** + * Create a new log starting from an entry + * @param {IPFS} [ipfs] An IPFS instance + * @param {string} id + * @param {string} [hash] [Multihash of the entry to start from] + * @param {Number} length + * @param {function(hash, entry, parent, depth)} onProgressCallback + * @returns {Promise} + */ + + }, { + key: 'fromEntry', + value: function fromEntry(ipfs, hash) { + var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1; + var onProgressCallback = arguments[3]; + + return LogUtils._fetchRecursive(ipfs, hash, {}, length, 0, null, onProgressCallback).then(function (items) { + var log = LogUtils.create(ipfs); + items.reverse().forEach(function (e) { + return LogUtils._insert(ipfs, log, e); + }); + log._heads = LogUtils._findHeads(log); + return log; + }); + } + + /** + * Create a log from multihash + * @param {IPFS} [ipfs] An IPFS instance + * @param {string} [hash] Multihash to create the log from + * @param {Number} [length=-1] How many items to include in the log + * @returns {Promise} + */ + + }, { + key: 'fromMultihash', + value: function fromMultihash(ipfs, hash) { + var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1; + var onProgressCallback = arguments[3]; + + if (!ipfs) throw new Error('Ipfs instance not defined'); + if (!hash) throw new Error('Invalid hash: ' + hash); + 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.heads) throw new Error('Not a Log instance'); + // Fetch logs starting from each head entry + var allLogs = logData.heads.sort(LogUtils._compare).map(function (f) { + return LogUtils.fromEntry(ipfs, f, length, onProgressCallback); + }); + // Join all logs together to one log + var joinAll = function joinAll(logs) { + return LogUtils.joinAll(ipfs, logs); + }; + return _promise2.default.all(allLogs).then(joinAll); + }); + } + + /** + * Get the log's multihash + * @param {IPFS} [ipfs] An IPFS instance + * @param {Log} log + * @returns {Promise} + */ + + }, { + key: 'toMultihash', + value: function toMultihash(ipfs, log) { + if (!ipfs) throw new Error('Ipfs instance not defined'); + if (!log) throw new Error('Log instance not defined'); + if (log.items.length < 1) throw new Error('Can\'t serialize an empty log'); + return ipfs.object.put(log.toBuffer()).then(function (res) { + return res.toJSON().multihash; + }); + } + + /** + * Add an entry to a log + * @description Adds an entry to the Log and returns a new Log. Doesn't modify the original Log. + * @memberof Log + * @static + * @param {IPFS} ipfs An IPFS instance + * @param {Log} log - The Log to add the entry to + * @param {string|Buffer|Object|Array} data - Data of the entry to be added + * @returns {Log} + */ + + }, { + key: 'append', + value: function append(ipfs, log, data) { + if (!ipfs) throw new Error('Ipfs instance not defined'); + if (!log) throw new Error('Log instance not defined'); + // Create the entry + return Entry.create(ipfs, data, log.heads).then(function (entry) { + // Add the entry to the previous log entries + var items = log.items.slice().concat([entry]); + // Set the heads of this log to the latest entry + var heads = [entry.hash]; + // Create a new log instance + return new Log(ipfs, items, heads); + }); + } + + /** + * Join two logs + * + * @description Joins two logs returning a new log. Doesn't mutate the original logs. + * + * @param {IPFS} [ipfs] An IPFS instance + * @param {Log} a + * @param {Log} b + * + * @example + * const log = Log.join(ipfs, log1, log2) + * + * @returns {Log} + */ + + }, { + key: 'join', + value: function join(ipfs, a, b, size) { + if (!ipfs) throw new Error('Ipfs instance not defined'); + if (!a || !b) throw new Error('Log instance not defined'); + if (!a.items || !b.items) throw new Error('Log to join must be an instance of Log'); + + // If size is not specified, join all entries by default + size = size ? size : a.items.length + b.items.length; + + // Get the heads from both logs and sort them by their IDs + var getHeadEntries = function getHeadEntries(log) { + return log.heads.map(function (e) { + return log.get(e); + }).filter(function (e) { + return e !== undefined; + }).slice(); + }; + + var headsA = getHeadEntries(a); + var headsB = getHeadEntries(b); + var heads = headsA.concat(headsB).map(function (e) { + return e.hash; + }).sort(); + + // Sort which log should come first based on heads' IDs + var aa = headsA[0] ? headsA[0].hash : null; + var bb = headsB[0] ? headsB[0].hash : null; + var isFirst = aa < bb; + var log1 = isFirst ? a : b; + var log2 = isFirst ? b : a; + + // Cap the size of the entries + var newEntries = log2.items.slice(0, size); + var oldEntries = log1.items.slice(0, size); + + // Create a new log instance + var result = LogUtils.create(ipfs, oldEntries, heads); + + // Insert each entry to the log + newEntries.forEach(function (e) { + return LogUtils._insert(ipfs, result, e); + }); + + return result; + } + + /** + * Join multiple logs + * @param {IPFS} [ipfs] An IPFS instance + * @param {Array} logs + * @returns {Log} + */ + + }, { + key: 'joinAll', + value: function joinAll(ipfs, logs) { + return logs.reduce(function (log, val, i) { + if (!log) return val; + return LogUtils.join(ipfs, log, val); + }, null); + } + + /** + * Expand the size of the log + * @param {IPFS} [ipfs] An IPFS instance + * @param {Log} log + * @param {Number} length + * @param {function(hash, entry, parent, depth)} onProgressCallback + * @returns {Promise} + */ + + }, { + key: 'expand', + value: function expand(ipfs, log) { + var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1; + var onProgressCallback = arguments[3]; + + // TODO: Find tails (entries that point to an entry that is not in the log) + var tails = log.items.slice()[0].next.sort(LogUtils._compare); + // Fetch a log starting from each tail entry + var getLog = tails.map(function (f) { + return LogUtils.fromEntry(ipfs, f, length, onProgressCallback); + }); + // Join all logs together to one log + var joinAll = function joinAll(logs) { + return LogUtils.joinAll(ipfs, logs.concat([log])); + }; + // Create all logs and join them + return _promise2.default.all(getLog).then(joinAll); + } + + /** + * Insert an entry to the log + * @private + * @param {Entry} entry Entry to be inserted + * @returns {Entry} + */ + + }, { + key: '_insert', + value: function _insert(ipfs, log, entry) { + var hashes = log.items.map(function (f) { + return f.hash; + }); + // If entry is already in the log, don't insert + if (hashes.includes(entry.hash)) return entry; + // Find the item's parents' indices + var indices = entry.next.map(function (next) { + return hashes.indexOf(next); + }); + // Find the largest index (latest parent) + var index = indices.length > 0 ? Math.max(Math.max.apply(null, indices) + 1, 0) : 0; + // Insert + log.items.splice(index, 0, entry); + return entry; + } + + /** + * Fetch log entries recursively + * @private + * @param {IPFS} [ipfs] An IPFS instance + * @param {string} [hash] Multihash of the entry to fetch + * @param {string} [parent] Parent of the node to be fetched + * @param {Object} [all] Entries to skip + * @param {Number} [amount=-1] How many entries to fetch. + * @param {Number} [depth=0] Current depth of the recursion + * @param {function(hash, entry, parent, depth)} onProgressCallback + * @returns {Promise>} + */ + + }, { + key: '_fetchRecursive', + value: function _fetchRecursive(ipfs, hash) { + var all = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var amount = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : -1; + var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var parent = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + var onProgressCallback = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : function () {}; + + // If the given hash is already fetched + // or if we're at maximum depth, return + if (all[hash] || depth >= amount && amount > 0) { + return _promise2.default.resolve([]); + } + // Create the entry and add it to the result + return Entry.fromMultihash(ipfs, hash).then(function (entry) { + all[hash] = entry; + onProgressCallback(hash, entry, parent, depth); + var fetch = function fetch(hash) { + return LogUtils._fetchRecursive(ipfs, hash, all, amount, depth + 1, entry, onProgressCallback); + }; + return mapSeries(entry.next, fetch, { concurrency: 1 }).then(function (res) { + return res.concat([entry]); + }).then(function (res) { + return res.reduce(function (a, b) { + return a.concat(b); + }, []); + }); // flatten the array + }); + } + + /** + * Find heads of a log + * @private + * @param {Log} log + * @returns {Array} + */ + + }, { + key: '_findHeads', + value: function _findHeads(log) { + return log.items.slice().reverse().filter(function (f) { + return !LogUtils._isReferencedInChain(log, f); + }).map(function (f) { + return f.hash; + }).sort(LogUtils._compare); + } + + /** + * Check if an entry is referenced by another entry in the log + * @private + * @param {log} [log] Log to search an entry from + * @param {Entry} [entry] Entry to search for + * @returns {boolean} + */ + + }, { + key: '_isReferencedInChain', + value: function _isReferencedInChain(log, entry) { + return log.items.slice().reverse().find(function (e) { + return Entry.hasChild(e, entry); + }) !== undefined; + } + + /** + * Find entry's parents + * @private + * @description Returns entry's parents as an Array up to the root entry + * @param {Log} [log] Log to search parents from + * @param {Entry} [entry] Entry for which to find the parents + * @returns {Array} + */ + + }, { + key: '_findParents', + value: function _findParents(log, entry) { + var stack = []; + var parent = log.items.find(function (e) { + return Entry.hasChild(e, entry); + }); + var prev = entry; + while (parent) { + stack.push(parent); + prev = parent; + parent = log.items.find(function (e) { + return Entry.hasChild(e, prev); + }); + } + return stack; + } + + /** + * Internal compare function + * @private + * @returns {boolean} + */ + + }, { + key: '_compare', + value: function _compare(a, b) { + return a < b; + } + }]); + return LogUtils; +}(); + +module.exports = LogUtils; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer)) + +/***/ }), +/* 91 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// https://gist.github.com/dignifiedquire/dd08d2f3806a7b87f45b00c41fe109b7 + +var _promise = __webpack_require__(27); + +var _promise2 = _interopRequireDefault(_promise); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = function mapSeries(list, func) { + var res = []; + + return list.reduce(function (acc, next) { + return acc.then(function (val) { + res.push(val); + + return func(next); + }); + }, _promise2.default.resolve(null)).then(function (val) { + res.push(val); + return res.slice(1); + }); +}; /***/ }), /* 92 */ @@ -5166,11 +5190,11 @@ module.exports = Log; "use strict"; /* WEBPACK VAR INJECTION */(function(process) { -var _keys = __webpack_require__(14); +var _keys = __webpack_require__(13); var _keys2 = _interopRequireDefault(_keys); -var _assign = __webpack_require__(6); +var _assign = __webpack_require__(9); var _assign2 = _interopRequireDefault(_assign); @@ -5184,9 +5208,9 @@ 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 fs = __webpack_require__(190); +var format = __webpack_require__(189).format; +var EventEmitter = __webpack_require__(36).EventEmitter; var isNodejs = process.version ? true : false; @@ -5261,31 +5285,33 @@ var Logger = function () { (0, _createClass3.default)(Logger, [{ key: 'debug', value: function debug() { - if (this._shouldLog(LogLevels.DEBUG)) this._write(LogLevels.DEBUG, format.apply(null, arguments)); + this._write(LogLevels.DEBUG, format.apply(null, arguments)); } }, { key: 'log', value: function log() { - if (this._shouldLog(LogLevels.DEBUG)) this.debug.apply(this, arguments); + this.debug.apply(this, arguments); } }, { key: 'info', value: function info() { - if (this._shouldLog(LogLevels.INFO)) this._write(LogLevels.INFO, format.apply(null, arguments)); + this._write(LogLevels.INFO, format.apply(null, arguments)); } }, { key: 'warn', value: function warn() { - if (this._shouldLog(LogLevels.WARN)) this._write(LogLevels.WARN, format.apply(null, arguments)); + this._write(LogLevels.WARN, format.apply(null, arguments)); } }, { key: 'error', value: function error() { - if (this._shouldLog(LogLevels.ERROR)) this._write(LogLevels.ERROR, format.apply(null, arguments)); + 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); @@ -5427,7 +5453,7 @@ module.exports = { }, // for testing, events: GlobalEvents }; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(34))) /***/ }), /* 93 */ @@ -5446,7 +5472,7 @@ var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var Counter = __webpack_require__(88); +var Counter = __webpack_require__(87); var CounterIndex = function () { function CounterIndex(id) { @@ -5462,11 +5488,12 @@ var CounterIndex = function () { } }, { key: 'updateIndex', - value: function updateIndex(oplog, added) { + value: function updateIndex(oplog) { var _this = this; + console.log(oplog.items); if (this._counter) { - added.filter(function (f) { + oplog.items.filter(function (f) { return f && f.payload.op === 'COUNTER'; }).map(function (f) { return Counter.from(f.payload.value); @@ -5512,10 +5539,10 @@ var DocumentIndex = function () { } }, { key: 'updateIndex', - value: function updateIndex(oplog, added) { + value: function updateIndex(oplog) { var _this = this; - added.reverse().reduce(function (handled, item) { + oplog.items.slice().reverse().reduce(function (handled, item) { if (handled.indexOf(item.payload.key) === -1) { handled.push(item.payload.key); if (item.payload.op === 'PUT') { @@ -5540,7 +5567,7 @@ module.exports = DocumentIndex; "use strict"; -var _getPrototypeOf = __webpack_require__(15); +var _getPrototypeOf = __webpack_require__(14); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); @@ -5552,11 +5579,11 @@ var _createClass2 = __webpack_require__(1); var _createClass3 = _interopRequireDefault(_createClass2); -var _possibleConstructorReturn2 = __webpack_require__(17); +var _possibleConstructorReturn2 = __webpack_require__(16); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); -var _inherits2 = __webpack_require__(16); +var _inherits2 = __webpack_require__(15); var _inherits3 = _interopRequireDefault(_inherits2); @@ -5574,10 +5601,10 @@ var FeedIndex = function (_EventIndex) { (0, _createClass3.default)(FeedIndex, [{ key: 'updateIndex', - value: function updateIndex(oplog, added) { + value: function updateIndex(oplog) { var _this2 = this; - added.reduce(function (handled, item) { + oplog.items.reduce(function (handled, item) { if (!handled.includes(item.hash)) { handled.push(item.hash); if (item.payload.op === 'ADD') { @@ -5626,10 +5653,10 @@ var KeyValueIndex = function () { } }, { key: 'updateIndex', - value: function updateIndex(oplog, added) { + value: function updateIndex(oplog) { var _this = this; - added.reverse().reduce(function (handled, item) { + oplog.items.slice().reverse().reduce(function (handled, item) { if (!handled.includes(item.payload.key)) { handled.push(item.payload.key); if (item.payload.op === 'PUT') { @@ -5654,7 +5681,7 @@ module.exports = KeyValueIndex; "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) { -var _keys = __webpack_require__(14); +var _keys = __webpack_require__(13); var _keys2 = _interopRequireDefault(_keys); @@ -5728,7 +5755,7 @@ var IPFSPubsub = function () { }(); module.exports = IPFSPubsub; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18).Buffer)) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer)) /***/ }), /* 98 */ @@ -5816,25 +5843,25 @@ module.exports = Index; /* 99 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(108), __esModule: true }; +module.exports = { "default": __webpack_require__(107), __esModule: true }; /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(110), __esModule: true }; +module.exports = { "default": __webpack_require__(109), __esModule: true }; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(113), __esModule: true }; +module.exports = { "default": __webpack_require__(112), __esModule: true }; /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = { "default": __webpack_require__(115), __esModule: true }; +module.exports = { "default": __webpack_require__(114), __esModule: true }; /***/ }), /* 103 */ @@ -5870,5726 +5897,158 @@ exports.default = function (obj, key, value) { /* 104 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +;(function (exports) { + 'use strict'; -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array -var lookup = [] -var revLookup = [] -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) -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} + 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 + } -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } + 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 - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 -} + // 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 -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return b64.length * 3 / 4 - placeHoldersCount(b64) -} + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) -function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length - arr = new Arr(len * 3 / 4 - placeHolders) + var L = 0 - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len + function push (v) { + arr[L++] = v + } - var L = 0 + 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) + } - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = 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) + } - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } + return arr + } - return arr -} + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} + function encode (num) { + return lookup.charAt(num) + } -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 + // 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) + } - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } + // 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 + } - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } + return output + } - parts.push(output) - - return parts.join('') -} + 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); }; +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { + +__webpack_require__(141); +module.exports = __webpack_require__(2).Object.assign; + /***/ }), /* 107 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(142); -module.exports = __webpack_require__(2).Object.assign; +var $Object = __webpack_require__(2).Object; +module.exports = function create(P, D){ + return $Object.create(P, D); +}; /***/ }), /* 108 */ @@ -11597,8 +6056,8 @@ module.exports = __webpack_require__(2).Object.assign; __webpack_require__(143); var $Object = __webpack_require__(2).Object; -module.exports = function create(P, D){ - return $Object.create(P, D); +module.exports = function defineProperty(it, key, desc){ + return $Object.defineProperty(it, key, desc); }; /***/ }), @@ -11607,8 +6066,8 @@ module.exports = function create(P, D){ __webpack_require__(144); var $Object = __webpack_require__(2).Object; -module.exports = function defineProperty(it, key, desc){ - return $Object.defineProperty(it, key, desc); +module.exports = function getOwnPropertyNames(it){ + return $Object.getOwnPropertyNames(it); }; /***/ }), @@ -11616,68 +6075,58 @@ module.exports = function defineProperty(it, key, desc){ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(145); -var $Object = __webpack_require__(2).Object; -module.exports = function getOwnPropertyNames(it){ - return $Object.getOwnPropertyNames(it); -}; +module.exports = __webpack_require__(2).Object.getPrototypeOf; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(146); -module.exports = __webpack_require__(2).Object.getPrototypeOf; +module.exports = __webpack_require__(2).Object.keys; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(147); -module.exports = __webpack_require__(2).Object.keys; +module.exports = __webpack_require__(2).Object.setPrototypeOf; /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { +__webpack_require__(72); +__webpack_require__(73); +__webpack_require__(74); __webpack_require__(148); -module.exports = __webpack_require__(2).Object.setPrototypeOf; +module.exports = __webpack_require__(2).Promise; /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { -__webpack_require__(73); -__webpack_require__(74); -__webpack_require__(75); __webpack_require__(149); -module.exports = __webpack_require__(2).Promise; +__webpack_require__(72); +__webpack_require__(150); +__webpack_require__(151); +module.exports = __webpack_require__(2).Symbol; /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { -__webpack_require__(150); __webpack_require__(73); -__webpack_require__(151); -__webpack_require__(152); -module.exports = __webpack_require__(2).Symbol; +__webpack_require__(74); +module.exports = __webpack_require__(50).f('iterator'); /***/ }), /* 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 */ +/* 117 */ /***/ (function(module, exports) { module.exports = function(it, Constructor, name, forbiddenField){ @@ -11687,14 +6136,14 @@ module.exports = function(it, Constructor, name, forbiddenField){ }; /***/ }), -/* 119 */ +/* 118 */ /***/ (function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes -var toIObject = __webpack_require__(13) - , toLength = __webpack_require__(72) - , toIndex = __webpack_require__(139); +var toIObject = __webpack_require__(12) + , toLength = __webpack_require__(71) + , toIndex = __webpack_require__(138); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) @@ -11713,13 +6162,13 @@ module.exports = function(IS_INCLUDES){ }; /***/ }), -/* 120 */ +/* 119 */ /***/ (function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols -var getKeys = __webpack_require__(21) - , gOPS = __webpack_require__(42) - , pIE = __webpack_require__(31); +var getKeys = __webpack_require__(19) + , gOPS = __webpack_require__(43) + , pIE = __webpack_require__(29); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; @@ -11733,15 +6182,15 @@ module.exports = function(it){ }; /***/ }), -/* 121 */ +/* 120 */ /***/ (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) +var ctx = __webpack_require__(22) + , call = __webpack_require__(124) + , isArrayIter = __webpack_require__(122) + , anObject = __webpack_require__(5) + , toLength = __webpack_require__(71) + , getIterFn = __webpack_require__(139) , BREAK = {} , RETURN = {}; var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ @@ -11763,7 +6212,7 @@ exports.BREAK = BREAK; exports.RETURN = RETURN; /***/ }), -/* 122 */ +/* 121 */ /***/ (function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 @@ -11784,11 +6233,11 @@ module.exports = function(fn, args, that){ }; /***/ }), -/* 123 */ +/* 122 */ /***/ (function(module, exports, __webpack_require__) { // check on default Array iterator -var Iterators = __webpack_require__(24) +var Iterators = __webpack_require__(23) , ITERATOR = __webpack_require__(3)('iterator') , ArrayProto = Array.prototype; @@ -11797,21 +6246,21 @@ module.exports = function(it){ }; /***/ }), -/* 124 */ +/* 123 */ /***/ (function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) -var cof = __webpack_require__(22); +var cof = __webpack_require__(21); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; /***/ }), -/* 125 */ +/* 124 */ /***/ (function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error -var anObject = __webpack_require__(7); +var anObject = __webpack_require__(5); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); @@ -11824,18 +6273,18 @@ module.exports = function(iterator, fn, value, entries){ }; /***/ }), -/* 126 */ +/* 125 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var create = __webpack_require__(41) - , descriptor = __webpack_require__(32) - , setToStringTag = __webpack_require__(33) +var create = __webpack_require__(42) + , descriptor = __webpack_require__(30) + , setToStringTag = __webpack_require__(31) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() -__webpack_require__(12)(IteratorPrototype, __webpack_require__(3)('iterator'), function(){ return this; }); +__webpack_require__(11)(IteratorPrototype, __webpack_require__(3)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); @@ -11843,7 +6292,7 @@ module.exports = function(Constructor, NAME, next){ }; /***/ }), -/* 127 */ +/* 126 */ /***/ (function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(3)('iterator') @@ -11869,7 +6318,7 @@ module.exports = function(exec, skipClosing){ }; /***/ }), -/* 128 */ +/* 127 */ /***/ (function(module, exports) { module.exports = function(done, value){ @@ -11877,11 +6326,11 @@ module.exports = function(done, value){ }; /***/ }), -/* 129 */ +/* 128 */ /***/ (function(module, exports, __webpack_require__) { -var getKeys = __webpack_require__(21) - , toIObject = __webpack_require__(13); +var getKeys = __webpack_require__(19) + , toIObject = __webpack_require__(12); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) @@ -11892,18 +6341,18 @@ module.exports = function(object, el){ }; /***/ }), -/* 130 */ +/* 129 */ /***/ (function(module, exports, __webpack_require__) { -var META = __webpack_require__(35)('meta') - , isObject = __webpack_require__(20) - , has = __webpack_require__(11) - , setDesc = __webpack_require__(10).f +var META = __webpack_require__(33)('meta') + , isObject = __webpack_require__(18) + , has = __webpack_require__(10) + , setDesc = __webpack_require__(8).f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; -var FREEZE = !__webpack_require__(19)(function(){ +var FREEZE = !__webpack_require__(17)(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ @@ -11950,15 +6399,15 @@ var meta = module.exports = { }; /***/ }), -/* 131 */ +/* 130 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(4) - , macrotask = __webpack_require__(71).set + , macrotask = __webpack_require__(70).set , Observer = global.MutationObserver || global.WebKitMutationObserver , process = global.process , Promise = global.Promise - , isNode = __webpack_require__(22)(process) == 'process'; + , isNode = __webpack_require__(21)(process) == 'process'; module.exports = function(){ var head, last, notify; @@ -12023,21 +6472,21 @@ module.exports = function(){ }; /***/ }), -/* 132 */ +/* 131 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 19.1.2.1 Object.assign(target, source, ...) -var getKeys = __webpack_require__(21) - , gOPS = __webpack_require__(42) - , pIE = __webpack_require__(31) - , toObject = __webpack_require__(34) - , IObject = __webpack_require__(63) +var getKeys = __webpack_require__(19) + , gOPS = __webpack_require__(43) + , pIE = __webpack_require__(29) + , toObject = __webpack_require__(32) + , IObject = __webpack_require__(62) , $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) -module.exports = !$assign || __webpack_require__(19)(function(){ +module.exports = !$assign || __webpack_require__(17)(function(){ var A = {} , B = {} , S = Symbol() @@ -12062,14 +6511,14 @@ module.exports = !$assign || __webpack_require__(19)(function(){ } : $assign; /***/ }), -/* 133 */ +/* 132 */ /***/ (function(module, exports, __webpack_require__) { -var dP = __webpack_require__(10) - , anObject = __webpack_require__(7) - , getKeys = __webpack_require__(21); +var dP = __webpack_require__(8) + , anObject = __webpack_require__(5) + , getKeys = __webpack_require__(19); -module.exports = __webpack_require__(8) ? Object.defineProperties : function defineProperties(O, Properties){ +module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length @@ -12080,10 +6529,10 @@ module.exports = __webpack_require__(8) ? Object.defineProperties : function def }; /***/ }), -/* 134 */ +/* 133 */ /***/ (function(module, exports, __webpack_require__) { -var hide = __webpack_require__(12); +var hide = __webpack_require__(11); module.exports = function(target, src, safe){ for(var key in src){ if(safe && target[key])target[key] = src[key]; @@ -12092,13 +6541,13 @@ module.exports = function(target, src, safe){ }; /***/ }), -/* 135 */ +/* 134 */ /***/ (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__(20) - , anObject = __webpack_require__(7); +var isObject = __webpack_require__(18) + , anObject = __webpack_require__(5); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); @@ -12107,7 +6556,7 @@ 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 = __webpack_require__(22)(Function.call, __webpack_require__(64).f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } @@ -12122,15 +6571,15 @@ module.exports = { }; /***/ }), -/* 136 */ +/* 135 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(4) , core = __webpack_require__(2) - , dP = __webpack_require__(10) - , DESCRIPTORS = __webpack_require__(8) + , dP = __webpack_require__(8) + , DESCRIPTORS = __webpack_require__(6) , SPECIES = __webpack_require__(3)('species'); module.exports = function(KEY){ @@ -12142,12 +6591,12 @@ module.exports = function(KEY){ }; /***/ }), -/* 137 */ +/* 136 */ /***/ (function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) -var anObject = __webpack_require__(7) - , aFunction = __webpack_require__(37) +var anObject = __webpack_require__(5) + , aFunction = __webpack_require__(38) , SPECIES = __webpack_require__(3)('species'); module.exports = function(O, D){ var C = anObject(O).constructor, S; @@ -12155,11 +6604,11 @@ module.exports = function(O, D){ }; /***/ }), -/* 138 */ +/* 137 */ /***/ (function(module, exports, __webpack_require__) { -var toInteger = __webpack_require__(46) - , defined = __webpack_require__(38); +var toInteger = __webpack_require__(47) + , defined = __webpack_require__(39); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ @@ -12177,10 +6626,10 @@ module.exports = function(TO_STRING){ }; /***/ }), -/* 139 */ +/* 138 */ /***/ (function(module, exports, __webpack_require__) { -var toInteger = __webpack_require__(46) +var toInteger = __webpack_require__(47) , max = Math.max , min = Math.min; module.exports = function(index, length){ @@ -12189,12 +6638,12 @@ module.exports = function(index, length){ }; /***/ }), -/* 140 */ +/* 139 */ /***/ (function(module, exports, __webpack_require__) { -var classof = __webpack_require__(60) +var classof = __webpack_require__(59) , ITERATOR = __webpack_require__(3)('iterator') - , Iterators = __webpack_require__(24); + , Iterators = __webpack_require__(23); module.exports = __webpack_require__(2).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] @@ -12202,21 +6651,21 @@ module.exports = __webpack_require__(2).getIteratorMethod = function(it){ }; /***/ }), -/* 141 */ +/* 140 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var addToUnscopables = __webpack_require__(117) - , step = __webpack_require__(128) - , Iterators = __webpack_require__(24) - , toIObject = __webpack_require__(13); +var addToUnscopables = __webpack_require__(116) + , step = __webpack_require__(127) + , Iterators = __webpack_require__(23) + , toIObject = __webpack_require__(12); // 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){ +module.exports = __webpack_require__(63)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind @@ -12242,50 +6691,64 @@ addToUnscopables('values'); addToUnscopables('entries'); /***/ }), -/* 142 */ +/* 141 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) -var $export = __webpack_require__(9); +var $export = __webpack_require__(7); -$export($export.S + $export.F, 'Object', {assign: __webpack_require__(132)}); +$export($export.S + $export.F, 'Object', {assign: __webpack_require__(131)}); + +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { + +var $export = __webpack_require__(7) +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +$export($export.S, 'Object', {create: __webpack_require__(42)}); /***/ }), /* 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)}); +var $export = __webpack_require__(7); +// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) +$export($export.S + $export.F * !__webpack_require__(6), 'Object', {defineProperty: __webpack_require__(8).f}); /***/ }), /* 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}); +// 19.1.2.7 Object.getOwnPropertyNames(O) +__webpack_require__(44)('getOwnPropertyNames', function(){ + return __webpack_require__(65).f; +}); /***/ }), /* 145 */ /***/ (function(module, exports, __webpack_require__) { -// 19.1.2.7 Object.getOwnPropertyNames(O) -__webpack_require__(43)('getOwnPropertyNames', function(){ - return __webpack_require__(66).f; +// 19.1.2.9 Object.getPrototypeOf(O) +var toObject = __webpack_require__(32) + , $getPrototypeOf = __webpack_require__(67); + +__webpack_require__(44)('getPrototypeOf', function(){ + return function getPrototypeOf(it){ + return $getPrototypeOf(toObject(it)); + }; }); /***/ }), /* 146 */ /***/ (function(module, exports, __webpack_require__) { -// 19.1.2.9 Object.getPrototypeOf(O) -var toObject = __webpack_require__(34) - , $getPrototypeOf = __webpack_require__(68); +// 19.1.2.14 Object.keys(O) +var toObject = __webpack_require__(32) + , $keys = __webpack_require__(19); -__webpack_require__(43)('getPrototypeOf', function(){ - return function getPrototypeOf(it){ - return $getPrototypeOf(toObject(it)); +__webpack_require__(44)('keys', function(){ + return function keys(it){ + return $keys(toObject(it)); }; }); @@ -12293,42 +6756,28 @@ __webpack_require__(43)('getPrototypeOf', function(){ /* 147 */ /***/ (function(module, exports, __webpack_require__) { -// 19.1.2.14 Object.keys(O) -var toObject = __webpack_require__(34) - , $keys = __webpack_require__(21); - -__webpack_require__(43)('keys', function(){ - return function keys(it){ - return $keys(toObject(it)); - }; -}); +// 19.1.3.19 Object.setPrototypeOf(O, proto) +var $export = __webpack_require__(7); +$export($export.S, 'Object', {setPrototypeOf: __webpack_require__(134).set}); /***/ }), /* 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"; -var LIBRARY = __webpack_require__(30) +var LIBRARY = __webpack_require__(28) , global = __webpack_require__(4) - , ctx = __webpack_require__(23) - , classof = __webpack_require__(60) - , $export = __webpack_require__(9) - , isObject = __webpack_require__(20) - , 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)() + , ctx = __webpack_require__(22) + , classof = __webpack_require__(59) + , $export = __webpack_require__(7) + , isObject = __webpack_require__(18) + , aFunction = __webpack_require__(38) + , anInstance = __webpack_require__(117) + , forOf = __webpack_require__(120) + , speciesConstructor = __webpack_require__(136) + , task = __webpack_require__(70).set + , microtask = __webpack_require__(130)() , PROMISE = 'Promise' , TypeError = global.TypeError , process = global.process @@ -12520,7 +6969,7 @@ if(!USE_NATIVE){ this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; - Internal.prototype = __webpack_require__(134)($Promise.prototype, { + Internal.prototype = __webpack_require__(133)($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); @@ -12546,8 +6995,8 @@ if(!USE_NATIVE){ } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); -__webpack_require__(33)($Promise, PROMISE); -__webpack_require__(136)(PROMISE); +__webpack_require__(31)($Promise, PROMISE); +__webpack_require__(135)(PROMISE); Wrapper = __webpack_require__(2)[PROMISE]; // statics @@ -12571,7 +7020,7 @@ $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { return capability.promise; } }); -$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(127)(function(iter){ +$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(126)(function(iter){ $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) @@ -12617,37 +7066,37 @@ $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(127)(functio }); /***/ }), -/* 150 */ +/* 149 */ /***/ (function(module, exports, __webpack_require__) { "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__(19) - , shared = __webpack_require__(45) - , setToStringTag = __webpack_require__(33) - , uid = __webpack_require__(35) + , has = __webpack_require__(10) + , DESCRIPTORS = __webpack_require__(6) + , $export = __webpack_require__(7) + , redefine = __webpack_require__(69) + , META = __webpack_require__(129).KEY + , $fails = __webpack_require__(17) + , shared = __webpack_require__(46) + , setToStringTag = __webpack_require__(31) + , uid = __webpack_require__(33) , 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__(21) + , wksExt = __webpack_require__(50) + , wksDefine = __webpack_require__(49) + , keyOf = __webpack_require__(128) + , enumKeys = __webpack_require__(119) + , isArray = __webpack_require__(123) + , anObject = __webpack_require__(5) + , toIObject = __webpack_require__(12) + , toPrimitive = __webpack_require__(48) + , createDesc = __webpack_require__(30) + , _create = __webpack_require__(42) + , gOPNExt = __webpack_require__(65) + , $GOPD = __webpack_require__(64) + , $DP = __webpack_require__(8) + , $keys = __webpack_require__(19) , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f @@ -12770,11 +7219,11 @@ if(!USE_NATIVE){ $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; - __webpack_require__(67).f = gOPNExt.f = $getOwnPropertyNames; - __webpack_require__(31).f = $propertyIsEnumerable; - __webpack_require__(42).f = $getOwnPropertySymbols; + __webpack_require__(66).f = gOPNExt.f = $getOwnPropertyNames; + __webpack_require__(29).f = $propertyIsEnumerable; + __webpack_require__(43).f = $getOwnPropertySymbols; - if(DESCRIPTORS && !__webpack_require__(30)){ + if(DESCRIPTORS && !__webpack_require__(28)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } @@ -12849,7 +7298,7 @@ $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) -$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(12)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); +$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(11)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] @@ -12857,22 +7306,22 @@ setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); +/***/ }), +/* 150 */ +/***/ (function(module, exports, __webpack_require__) { + +__webpack_require__(49)('asyncIterator'); + /***/ }), /* 151 */ /***/ (function(module, exports, __webpack_require__) { -__webpack_require__(48)('asyncIterator'); +__webpack_require__(49)('observable'); /***/ }), /* 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) : @@ -17478,10 +11927,10 @@ return Dexie; }))); //# sourceMappingURL=dexie.js.map -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5), __webpack_require__(53).setImmediate)) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(35), __webpack_require__(80).setImmediate)) /***/ }), -/* 154 */ +/* 153 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -17493,13 +11942,13 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope 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); +var Dexie = __webpack_require__(152); +var _write = __webpack_require__(185); +var pushable = __webpack_require__(162); +var toBuffer = __webpack_require__(187); +var defer = __webpack_require__(161); +var toWindow = __webpack_require__(184).recent; +var pull = __webpack_require__(75); module.exports = function () { function IdbBlobStore(dbname) { @@ -17652,10 +12101,10 @@ function last(arr) { function ensureBuffer(data) { return Buffer.isBuffer(data) ? data : Buffer.from(data); } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18).Buffer)) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer)) /***/ }), -/* 155 */ +/* 154 */ /***/ (function(module, exports) { exports.read = function (buffer, offset, isLE, mLen, nBytes) { @@ -17745,7 +12194,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { /***/ }), -/* 156 */ +/* 155 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { @@ -17774,7 +12223,7 @@ if (typeof Object.create === 'function') { /***/ }), -/* 157 */ +/* 156 */ /***/ (function(module, exports) { module.exports = isTypedArray @@ -17821,7 +12270,7 @@ function isLooseTypedArray(arr) { /***/ }), -/* 158 */ +/* 157 */ /***/ (function(module, exports) { var toString = {}.toString; @@ -17832,7 +12281,7 @@ module.exports = Array.isArray || function (arr) { /***/ }), -/* 159 */ +/* 158 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(setImmediate) { @@ -17918,5653 +12367,10 @@ module.exports = function () { return lock } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(53).setImmediate)) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(80).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 */ +/* 159 */ /***/ (function(module, exports) { @@ -23588,7 +12394,7 @@ var looper = module.exports = function (fun) { /***/ }), -/* 166 */ +/* 160 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. @@ -23816,10 +12622,10 @@ var substr = 'ab'.substr(-1) === 'b' } ; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(34))) /***/ }), -/* 167 */ +/* 161 */ /***/ (function(module, exports) { module.exports = function (stream) { @@ -23844,7 +12650,7 @@ module.exports = function (stream) { /***/ }), -/* 168 */ +/* 162 */ /***/ (function(module, exports) { module.exports = pullPushable @@ -23924,7 +12730,7 @@ function pullPushable (onClose) { /***/ }), -/* 169 */ +/* 163 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -23980,13 +12786,13 @@ module.exports = function pull (a) { /***/ }), -/* 170 */ +/* 164 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var reduce = __webpack_require__(50) +var reduce = __webpack_require__(51) module.exports = function collect (cb) { return reduce(function (arr, item) { @@ -23997,13 +12803,13 @@ module.exports = function collect (cb) { /***/ }), -/* 171 */ +/* 165 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var reduce = __webpack_require__(50) +var reduce = __webpack_require__(51) module.exports = function concat (cb) { return reduce(function (a, b) { @@ -24013,15 +12819,15 @@ module.exports = function concat (cb) { /***/ }), -/* 172 */ +/* 166 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function id (e) { return e } -var prop = __webpack_require__(27) -var drain = __webpack_require__(26) +var prop = __webpack_require__(25) +var drain = __webpack_require__(24) module.exports = function find (test, cb) { var ended = false @@ -24048,32 +12854,32 @@ module.exports = function find (test, cb) { /***/ }), -/* 173 */ +/* 167 */ /***/ (function(module, exports, __webpack_require__) { "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) + drain: __webpack_require__(24), + onEnd: __webpack_require__(169), + log: __webpack_require__(168), + find: __webpack_require__(166), + reduce: __webpack_require__(51), + collect: __webpack_require__(164), + concat: __webpack_require__(165) } /***/ }), -/* 174 */ +/* 168 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var drain = __webpack_require__(26) +var drain = __webpack_require__(24) module.exports = function log (done) { return drain(function (data) { @@ -24083,13 +12889,13 @@ module.exports = function log (done) { /***/ }), -/* 175 */ +/* 169 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var drain = __webpack_require__(26) +var drain = __webpack_require__(24) module.exports = function onEnd (done) { return drain(null, done) @@ -24097,7 +12903,7 @@ module.exports = function onEnd (done) { /***/ }), -/* 176 */ +/* 170 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -24117,7 +12923,7 @@ module.exports = function count (max) { /***/ }), -/* 177 */ +/* 171 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -24131,7 +12937,7 @@ module.exports = function empty () { /***/ }), -/* 178 */ +/* 172 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -24146,24 +12952,24 @@ module.exports = function error (err) { /***/ }), -/* 179 */ +/* 173 */ /***/ (function(module, exports, __webpack_require__) { "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) + keys: __webpack_require__(175), + once: __webpack_require__(76), + values: __webpack_require__(52), + count: __webpack_require__(170), + infinite: __webpack_require__(174), + empty: __webpack_require__(171), + error: __webpack_require__(172) } /***/ }), -/* 180 */ +/* 174 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -24180,12 +12986,12 @@ module.exports = function infinite (generate) { /***/ }), -/* 181 */ +/* 175 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var values = __webpack_require__(51) +var values = __webpack_require__(52) module.exports = function (object) { return values(Object.keys(object)) } @@ -24194,14 +13000,14 @@ module.exports = function (object) { /***/ }), -/* 182 */ +/* 176 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function id (e) { return e } -var prop = __webpack_require__(27) +var prop = __webpack_require__(25) module.exports = function asyncMap (map) { if(!map) return id @@ -24244,14 +13050,14 @@ module.exports = function asyncMap (map) { /***/ }), -/* 183 */ +/* 177 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var tester = __webpack_require__(81) -var filter = __webpack_require__(52) +var tester = __webpack_require__(79) +var filter = __webpack_require__(53) module.exports = function filterNot (test) { test = tester(test) @@ -24260,14 +13066,14 @@ module.exports = function filterNot (test) { /***/ }), -/* 184 */ +/* 178 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var values = __webpack_require__(51) -var once = __webpack_require__(78) +var values = __webpack_require__(52) +var once = __webpack_require__(76) //convert a stream of arrays or streams into just a stream. module.exports = function flatten () { @@ -24314,22 +13120,22 @@ module.exports = function flatten () { /***/ }), -/* 185 */ +/* 179 */ /***/ (function(module, exports, __webpack_require__) { "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) + map: __webpack_require__(180), + asyncMap: __webpack_require__(176), + filter: __webpack_require__(53), + filterNot: __webpack_require__(177), + through: __webpack_require__(183), + take: __webpack_require__(182), + unique: __webpack_require__(77), + nonUnique: __webpack_require__(181), + flatten: __webpack_require__(178) } @@ -24337,14 +13143,14 @@ module.exports = { /***/ }), -/* 186 */ +/* 180 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function id (e) { return e } -var prop = __webpack_require__(27) +var prop = __webpack_require__(25) module.exports = function map (mapper) { if(!mapper) return id @@ -24367,13 +13173,13 @@ module.exports = function map (mapper) { /***/ }), -/* 187 */ +/* 181 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var unique = __webpack_require__(79) +var unique = __webpack_require__(77) //passes an item through when you see it for the second time. module.exports = function nonUnique (field) { @@ -24382,7 +13188,7 @@ module.exports = function nonUnique (field) { /***/ }), -/* 188 */ +/* 182 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -24430,7 +13236,7 @@ module.exports = function take (test, opts) { /***/ }), -/* 189 */ +/* 183 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -24460,10 +13266,10 @@ module.exports = function through (op, onEnd) { /***/ }), -/* 190 */ +/* 184 */ /***/ (function(module, exports, __webpack_require__) { -var looper = __webpack_require__(165) +var looper = __webpack_require__(159) var window = module.exports = function (init, start) { return function (read) { @@ -24565,7 +13371,7 @@ window.sliding = function (reduce, width) { /***/ }), -/* 191 */ +/* 185 */ /***/ (function(module, exports) { //another idea: buffer 2* the max, but only call write with half of that, @@ -24665,7 +13471,7 @@ module.exports = function (write, reduce, max, cb) { /***/ }), -/* 192 */ +/* 186 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { @@ -24855,10 +13661,10 @@ module.exports = function (write, reduce, max, cb) { attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self)); -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5), __webpack_require__(25))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(35), __webpack_require__(34))) /***/ }), -/* 193 */ +/* 187 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {/** @@ -24870,7 +13676,7 @@ module.exports = function (write, reduce, max, cb) { * `npm install typedarray-to-buffer` */ -var isTypedArray = __webpack_require__(157).strict +var isTypedArray = __webpack_require__(156).strict module.exports = function typedarrayToBuffer (arr) { if (isTypedArray(arr)) { @@ -24887,10 +13693,10 @@ module.exports = function typedarrayToBuffer (arr) { } } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18).Buffer)) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer)) /***/ }), -/* 194 */ +/* 188 */ /***/ (function(module, exports) { module.exports = function isBuffer(arg) { @@ -24901,7 +13707,7 @@ module.exports = function isBuffer(arg) { } /***/ }), -/* 195 */ +/* 189 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. @@ -25429,7 +14235,7 @@ function isPrimitive(arg) { } exports.isPrimitive = isPrimitive; -exports.isBuffer = __webpack_require__(194); +exports.isBuffer = __webpack_require__(188); function objectToString(o) { return Object.prototype.toString.call(o); @@ -25473,7 +14279,7 @@ exports.log = function() { * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ -exports.inherits = __webpack_require__(156); +exports.inherits = __webpack_require__(155); exports._extend = function(origin, add) { // Don't do anything if add isn't an object @@ -25491,50 +14297,22 @@ function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5), __webpack_require__(25))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(35), __webpack_require__(34))) /***/ }), -/* 196 */ -/***/ (function(module, exports) { - -module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - if(!module.children) module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - get: function() { - return module.l; - } - }); - Object.defineProperty(module, "id", { - enumerable: true, - get: function() { - return module.i; - } - }); - module.webpackPolyfill = 1; - } - return module; -}; - - -/***/ }), -/* 197 */ +/* 190 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), -/* 198 */ +/* 191 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _keys = __webpack_require__(14); +var _keys = __webpack_require__(13); var _keys2 = _interopRequireDefault(_keys); @@ -25548,14 +14326,14 @@ var _createClass3 = _interopRequireDefault(_createClass2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var EventEmitter = __webpack_require__(28).EventEmitter; +var EventEmitter = __webpack_require__(36).EventEmitter; var EventStore = __webpack_require__(54); -var FeedStore = __webpack_require__(85); -var KeyValueStore = __webpack_require__(86); -var CounterStore = __webpack_require__(83); -var DocumentStore = __webpack_require__(84); -var Pubsub = __webpack_require__(87); -var Cache = __webpack_require__(82); +var FeedStore = __webpack_require__(84); +var KeyValueStore = __webpack_require__(85); +var CounterStore = __webpack_require__(82); +var DocumentStore = __webpack_require__(83); +var Pubsub = __webpack_require__(86); +var Cache = __webpack_require__(81); var defaultNetworkName = 'Orbit DEV Network'; diff --git a/dist/orbitdb.min.js b/dist/orbitdb.min.js index 59450aa..d24b910 100644 --- a/dist/orbitdb.min.js +++ b/dist/orbitdb.min.js @@ -1,31 +1,8 @@ -var OrbitDB=function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.i=function(value){return value},__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function(){return module.default}:function(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=198)}([function(module,exports,__webpack_require__){"use strict";exports.__esModule=!0,exports.default=function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.__esModule=!0;var _defineProperty=__webpack_require__(56),_defineProperty2=_interopRequireDefault(_defineProperty);exports.default=function(){function defineProperties(target,props){for(var i=0;i=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)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=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=String(encoding).toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining)):length=remaining;var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128===(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,tempCodePoint>127&&(codePoint=tempCodePoint));break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128===(192&secondByte)&&128===(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint));break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128===(192&secondByte)&&128===(192&thirdByte)&&128===(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,tempCodePoint>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint))}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}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||valuebuf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i>>8*(littleEndian?i:3-i)&255}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){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!==0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>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=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}/*! +var OrbitDB=function(t){function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}var e={};return n.m=t,n.c=e,n.i=function(t){return t},n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},n.p="",n(n.s=82)}([function(t,n,e){"use strict";(function(t){function r(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}function i(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(t,n){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|t}function y(t){return+t!=t&&(t=0),u.alloc(+t)}function g(t,n){if(u.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var e=t.length;if(0===e)return 0;for(var r=!1;;)switch(n){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return H(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return W(t).length;default:if(r)return H(t).length;n=(""+n).toLowerCase(),r=!0}}function m(t,n,e){var r=!1;if((void 0===n||n<0)&&(n=0),n>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if(e>>>=0,n>>>=0,e<=n)return"";for(t||(t="utf8");;)switch(t){case"hex":return B(this,n,e);case"utf8":case"utf-8":return S(this,n,e);case"ascii":return j(this,n,e);case"latin1":case"binary":return R(this,n,e);case"base64":return P(this,n,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,n,e);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}function b(t,n,e){var r=t[n];t[n]=t[e],t[e]=r}function w(t,n,e,r,i){if(0===t.length)return-1;if("string"==typeof e?(r=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=i?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(i)return-1;e=t.length-1}else if(e<0){if(!i)return-1;e=0}if("string"==typeof n&&(n=u.from(n,r)),u.isBuffer(n))return 0===n.length?-1:_(t,n,e,r,i);if("number"==typeof n)return n&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,n,e):Uint8Array.prototype.lastIndexOf.call(t,n,e):_(t,[n],e,r,i);throw new TypeError("val must be string, number or Buffer")}function _(t,n,e,r,i){function o(t,n){return 1===u?t[n]:t.readUInt16BE(n*u)}var u=1,s=t.length,c=n.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(t.length<2||n.length<2)return-1;u=2,s/=2,c/=2,e/=2}var a;if(i){var f=-1;for(a=e;as&&(e=s-c),a=e;a>=0;a--){for(var h=!0,l=0;li&&(r=i):r=i;var o=n.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var u=0;u239?4:o>223?3:o>191?2:1;if(i+s<=e){var c,a,f,h;switch(s){case 1:o<128&&(u=o);break;case 2:c=t[i+1],128==(192&c)&&(h=(31&o)<<6|63&c)>127&&(u=h);break;case 3:c=t[i+1],a=t[i+2],128==(192&c)&&128==(192&a)&&(h=(15&o)<<12|(63&c)<<6|63&a)>2047&&(h<55296||h>57343)&&(u=h);break;case 4:c=t[i+1],a=t[i+2],f=t[i+3],128==(192&c)&&128==(192&a)&&128==(192&f)&&(h=(15&o)<<18|(63&c)<<12|(63&a)<<6|63&f)>65535&&h<1114112&&(u=h)}}null===u?(u=65533,s=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),i+=s}return I(r)}function I(t){var n=t.length;if(n<=tt)return String.fromCharCode.apply(String,t);for(var e="",r=0;rr)&&(e=r);for(var i="",o=n;oe)throw new RangeError("Trying to access beyond buffer length")}function L(t,n,e,r,i,o){if(!u.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(n>i||nt.length)throw new RangeError("Index out of range")}function M(t,n,e,r){n<0&&(n=65535+n+1);for(var i=0,o=Math.min(t.length-e,2);i>>8*(r?i:1-i)}function U(t,n,e,r){n<0&&(n=4294967295+n+1);for(var i=0,o=Math.min(t.length-e,4);i>>8*(r?i:3-i)&255}function N(t,n,e,r,i,o){if(e+r>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function F(t,n,e,r,i){return i||N(t,n,e,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(t,n,e,r,23,4),e+4}function K(t,n,e,r,i){return i||N(t,n,e,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(t,n,e,r,52,8),e+8}function Y(t){if(t=q(t).replace(nt,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function q(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function z(t){return t<16?"0"+t.toString(16):t.toString(16)}function H(t,n){n=n||1/0;for(var e,r=t.length,i=null,o=[],u=0;u55295&&e<57344){if(!i){if(e>56319){(n-=3)>-1&&o.push(239,191,189);continue}if(u+1===r){(n-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(n-=3)>-1&&o.push(239,191,189),i=e;continue}e=65536+(i-55296<<10|e-56320)}else i&&(n-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((n-=1)<0)break;o.push(e)}else if(e<2048){if((n-=2)<0)break;o.push(e>>6|192,63&e|128)}else if(e<65536){if((n-=3)<0)break;o.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((n-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return o}function G(t){for(var n=[],e=0;e>8,i=e%256,o.push(i),o.push(r);return o}function W(t){return $.toByteArray(Y(t))}function V(t,n,e,r){for(var i=0;i=n.length||i>=t.length);++i)n[i+e]=t[i];return i}function Q(t){return t!==t}/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ -var base64=__webpack_require__(104),ieee754=__webpack_require__(155),isArray=__webpack_require__(158);exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:typedArraySupport(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),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;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;iremaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)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":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=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,start<0?(start+=len,start<0&&(start=0)):start>len&&(start=len),end<0?(end+=len,end<0&&(end=0)):end>len&&(end=len),end0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?(255-this[offset]+1)*-1:this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,byteLength|=0,!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},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;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],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;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){return this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _promise=__webpack_require__(57),_promise2=_interopRequireDefault(_promise),_assign=__webpack_require__(6),_assign2=_interopRequireDefault(_assign),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),EventEmitter=__webpack_require__(28).EventEmitter,Log=__webpack_require__(91),Index=__webpack_require__(98),DefaultOptions={Index:Index,maxHistory:256},Store=function(){function Store(ipfs,id,dbname){var options=arguments.length>3&&void 0!==arguments[3]?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))}return(0,_createClass3.default)(Store,[{key:"_onLoadHistory",value:function(amount){this.events.emit("load.start",this.dbname,amount)}},{key:"_onLoadProgress",value:function(amount){this.events.emit("load.progress",this.dbname,amount)}},{key:"loadHistory",value:function(hash){var _this=this;return this._lastWrite.includes(hash)?_promise2.default.resolve([]):(hash&&this._lastWrite.push(hash),hash&&this.options.maxHistory>0?(this.events.emit("load",this.dbname,hash),Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this._oplog.join(log)}).then(function(merged){_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})):(this.events.emit("ready",this.dbname),_promise2.default.resolve(this)))}},{key:"sync",value:function(hash){var _this2=this;if(!hash||this._lastWrite.includes(hash))return _promise2.default.resolve(hash);var newItems=[];hash&&this._lastWrite.push(hash),this.events.emit("sync",this.dbname);(new Date).getTime();return Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this2._oplog.join(log)}).then(function(merged){newItems=merged,_this2._index.updateIndex(_this2._oplog,newItems),_this2.events.emit("load.end",_this2.dbname,newItems)}).then(function(){_this2.events.emit("history",_this2.dbname,newItems),newItems.slice().reverse().forEach(function(e){return _this2.events.emit("data",_this2.dbname,e)})}).then(function(){return Log.getIpfsHash(_this2._ipfs,_this2._oplog)})}},{key:"close",value:function(){this.delete(),this.events.emit("close",this.dbname)}},{key:"delete",value:function(){this._index=new this.options.Index(this.id),this._oplog=new Log(this._ipfs,this.id,this.options)}},{key:"_addOperation",value:function(data){var _this3=this,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})}}]),Store}();module.exports=Store},function(module,exports){module.exports=!0},function(module,exports){exports.f={}.propertyIsEnumerable},function(module,exports){module.exports=function(bitmap,value){return{enumerable:!(1&bitmap),configurable:!(2&bitmap),writable:!(4&bitmap),value:value}}},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){it&&!has(it=stat?it:it.prototype,TAG)&&def(it,TAG,{configurable:!0,value:tag})}},function(module,exports,__webpack_require__){var defined=__webpack_require__(38);module.exports=function(it){return Object(defined(it))}},function(module,exports){var id=0,px=Math.random();module.exports=function(key){return"Symbol(".concat(void 0===key?"":key,")_",(++id+px).toString(36))}},function(module,exports,__webpack_require__){module.exports={default:__webpack_require__(106),__esModule:!0}},function(module,exports){module.exports=function(it){if("function"!=typeof it)throw TypeError(it+" is not a function!");return it}},function(module,exports){module.exports=function(it){if(void 0==it)throw TypeError("Can't call method on "+it);return it}},function(module,exports,__webpack_require__){var isObject=__webpack_require__(20),document=__webpack_require__(4).document,is=isObject(document)&&isObject(document.createElement);module.exports=function(it){return is?document.createElement(it):{}}},function(module,exports){module.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(module,exports,__webpack_require__){var anObject=__webpack_require__(7),dPs=__webpack_require__(133),enumBugKeys=__webpack_require__(40),IE_PROTO=__webpack_require__(44)("IE_PROTO"),Empty=function(){},PROTOTYPE="prototype",createDict=function(){var iframeDocument,iframe=__webpack_require__(39)("iframe"),i=enumBugKeys.length,lt="<",gt=">";for(iframe.style.display="none",__webpack_require__(61).appendChild(iframe),iframe.src="javascript:",iframeDocument=iframe.contentWindow.document,iframeDocument.open(),iframeDocument.write(lt+"script"+gt+"document.F=Object"+lt+"/script"+gt),iframeDocument.close(),createDict=iframeDocument.F;i--;)delete createDict[PROTOTYPE][enumBugKeys[i]];return createDict()};module.exports=Object.create||function(O,Properties){var result;return null!==O?(Empty[PROTOTYPE]=anObject(O),result=new Empty,Empty[PROTOTYPE]=null,result[IE_PROTO]=O):result=createDict(),void 0===Properties?result:dPs(result,Properties)}},function(module,exports){exports.f=Object.getOwnPropertySymbols},function(module,exports,__webpack_require__){var $export=__webpack_require__(9),core=__webpack_require__(2),fails=__webpack_require__(19);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)}},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))}},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]={})}},function(module,exports){var ceil=Math.ceil,floor=Math.floor;module.exports=function(it){return isNaN(it=+it)?0:(it>0?floor:ceil)(it)}},function(module,exports,__webpack_require__){var isObject=__webpack_require__(20);module.exports=function(it,S){if(!isObject(it))return it;var fn,val;if(S&&"function"==typeof(fn=it.toString)&&!isObject(val=fn.call(it)))return val;if("function"==typeof(fn=it.valueOf)&&!isObject(val=fn.call(it)))return val;if(!S&&"function"==typeof(fn=it.toString)&&!isObject(val=fn.call(it)))return val;throw TypeError("Can't convert object to primitive value")}},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||{});"_"==name.charAt(0)||name in $Symbol||defineProperty($Symbol,name,{value:wksExt.f(name)})}},function(module,exports,__webpack_require__){exports.f=__webpack_require__(3)},function(module,exports,__webpack_require__){"use strict";var drain=__webpack_require__(26);module.exports=function(reducer,acc,cb){cb||(cb=acc,acc=null);var sink=drain(function(data){acc=reducer(acc,data)},function(err){cb(err,acc)});return 2===arguments.length?function(source){source(null,function(end,data){if(end)return cb(end===!0?null:end);acc=data,sink(source)})}:sink}},function(module,exports,__webpack_require__){"use strict";var abortCb=__webpack_require__(80);module.exports=function(array,onAbort){if(!array)return function(abort,cb){return abort?abortCb(cb,abort,onAbort):cb(!0)};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);i>=array.length?cb(!0):cb(null,array[i++])}}},function(module,exports,__webpack_require__){"use strict";var tester=__webpack_require__(81);module.exports=function(test){return test=tester(test),function(read){return function next(end,cb){for(var sync,loop=!0;loop;)loop=!1,sync=!0,read(end,function(end,data){if(!end&&!test(data))return sync?loop=!0:next(end,cb);cb(end,data)}),sync=!1}}}},function(module,exports,__webpack_require__){function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}var apply=Function.prototype.apply;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){timeout&&timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},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;msecs>=0&&(item._idleTimeoutId=setTimeout(function(){item._onTimeout&&item._onTimeout()},msecs))},__webpack_require__(192),exports.setImmediate=setImmediate,exports.clearImmediate=clearImmediate},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _defineProperty2=__webpack_require__(103),_defineProperty3=_interopRequireDefault(_defineProperty2),_iterator2=__webpack_require__(58),_iterator3=_interopRequireDefault(_iterator2),_getPrototypeOf=__webpack_require__(15),_getPrototypeOf2=_interopRequireDefault(_getPrototypeOf),_assign=__webpack_require__(6),_assign2=_interopRequireDefault(_assign),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),_possibleConstructorReturn2=__webpack_require__(17),_possibleConstructorReturn3=_interopRequireDefault(_possibleConstructorReturn2),_inherits2=__webpack_require__(16),_inherits3=_interopRequireDefault(_inherits2),take=(__webpack_require__(163),__webpack_require__(76)),findIndex=__webpack_require__(161),Store=__webpack_require__(29),EventIndex=__webpack_require__(55),EventStore=function(_Store){function EventStore(ipfs,id,dbname){var options=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return(0,_classCallCheck3.default)(this,EventStore),void 0===options.Index&&(0,_assign2.default)(options,{Index:EventIndex}),(0,_possibleConstructorReturn3.default)(this,(EventStore.__proto__||(0,_getPrototypeOf2.default)(EventStore)).call(this,ipfs,id,dbname,options))}return(0,_inherits3.default)(EventStore,_Store),(0,_createClass3.default)(EventStore,[{key:"add",value:function(data){return this._addOperation({op:"ADD",key:null,value:data,meta:{ts:(new Date).getTime()}})}},{key:"get",value:function(hash){return this.iterator({gte:hash,limit:1}).collect()[0]}},{key:"iterator",value:function(options){var _iterator,messages=this._query(options),currentIndex=0;return _iterator={},(0,_defineProperty3.default)(_iterator,_iterator3.default,function(){return this}),(0,_defineProperty3.default)(_iterator,"next",function(){var item={value:null,done:!0};return currentIndex-1?opts.limit:this._index.get().length:1,events=this._index.get();return opts.gt||opts.gte?this._read(events,opts.gt?opts.gt:opts.gte,amount,!!opts.gte):this._read(events.reverse(),opts.lt?opts.lt:opts.lte,amount,opts.lte||!opts.lt).reverse()}},{key:"_read",value:function(ops,hash,amount,inclusive){var startIndex=Math.max(findIndex(ops,function(e){return e.hash===hash}),0);return startIndex+=inclusive?0:1,take(ops.slice(startIndex),amount)}}]),EventStore}(Store);module.exports=EventStore},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _keys=__webpack_require__(14),_keys2=_interopRequireDefault(_keys),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),EventIndex=function(){function EventIndex(){(0,_classCallCheck3.default)(this,EventIndex),this._index={}}return(0,_createClass3.default)(EventIndex,[{key:"get",value:function(){var _this=this;return(0,_keys2.default)(this._index).map(function(f){return _this._index[f]})}},{key:"updateIndex",value:function(oplog,added){var _this2=this;added.reduce(function(handled,item){return handled.includes(item.hash)||(handled.push(item.hash),"ADD"===item.payload.op&&(_this2._index[item.hash]=item)),handled},[])}}]),EventIndex}();module.exports=EventIndex},function(module,exports,__webpack_require__){module.exports={default:__webpack_require__(109),__esModule:!0}},function(module,exports,__webpack_require__){module.exports={default:__webpack_require__(114),__esModule:!0}},function(module,exports,__webpack_require__){module.exports={default:__webpack_require__(116),__esModule:!0}},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.__esModule=!0;var _iterator=__webpack_require__(58),_iterator2=_interopRequireDefault(_iterator),_symbol=__webpack_require__(102),_symbol2=_interopRequireDefault(_symbol),_typeof="function"==typeof _symbol2.default&&"symbol"==typeof _iterator2.default?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof _symbol2.default&&obj.constructor===_symbol2.default&&obj!==_symbol2.default.prototype?"symbol":typeof obj};exports.default="function"==typeof _symbol2.default&&"symbol"===_typeof(_iterator2.default)?function(obj){return void 0===obj?"undefined":_typeof(obj)}:function(obj){return obj&&"function"==typeof _symbol2.default&&obj.constructor===_symbol2.default&&obj!==_symbol2.default.prototype?"symbol":void 0===obj?"undefined":_typeof(obj)}},function(module,exports,__webpack_require__){var cof=__webpack_require__(22),TAG=__webpack_require__(3)("toStringTag"),ARG="Arguments"==cof(function(){return arguments}()),tryGet=function(it,key){try{return it[key]}catch(e){}};module.exports=function(it){var O,T,B;return void 0===it?"Undefined":null===it?"Null":"string"==typeof(T=tryGet(O=Object(it),TAG))?T:ARG?cof(O):"Object"==(B=cof(O))&&"function"==typeof O.callee?"Arguments":B}},function(module,exports,__webpack_require__){module.exports=__webpack_require__(4).document&&document.documentElement},function(module,exports,__webpack_require__){module.exports=!__webpack_require__(8)&&!__webpack_require__(19)(function(){return 7!=Object.defineProperty(__webpack_require__(39)("div"),"a",{get:function(){return 7}}).a})},function(module,exports,__webpack_require__){var cof=__webpack_require__(22);module.exports=Object("z").propertyIsEnumerable(0)?Object:function(it){return"String"==cof(it)?it.split(""):Object(it)}},function(module,exports,__webpack_require__){"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()),KEYS="keys",VALUES="values",returnThis=function(){return this};module.exports=function(Base,NAME,Constructor,next,DEFAULT,IS_SET,FORCED){$iterCreate(Constructor,NAME,next);var methods,key,IteratorPrototype,getMethod=function(kind){if(!BUGGY&&kind in proto)return proto[kind];switch(kind){case KEYS:return function(){return new Constructor(this,kind)};case VALUES:return function(){return new Constructor(this,kind)}}return function(){return new Constructor(this,kind)}},TAG=NAME+" Iterator",DEF_VALUES=DEFAULT==VALUES,VALUES_BUG=!1,proto=Base.prototype,$native=proto[ITERATOR]||proto["@@iterator"]||DEFAULT&&proto[DEFAULT],$default=$native||getMethod(DEFAULT),$entries=DEFAULT?DEF_VALUES?getMethod("entries"):$default:void 0,$anyNative="Array"==NAME?proto.entries||$native:$native;if($anyNative&&(IteratorPrototype=getPrototypeOf($anyNative.call(new Base)),IteratorPrototype!==Object.prototype&&(setToStringTag(IteratorPrototype,TAG,!0),LIBRARY||has(IteratorPrototype,ITERATOR)||hide(IteratorPrototype,ITERATOR,returnThis))),DEF_VALUES&&$native&&$native.name!==VALUES&&(VALUES_BUG=!0,$default=function(){return $native.call(this)}),LIBRARY&&!FORCED||!BUGGY&&!VALUES_BUG&&proto[ITERATOR]||hide(proto,ITERATOR,$default),Iterators[NAME]=$default,Iterators[TAG]=returnThis,DEFAULT)if(methods={values:DEF_VALUES?$default:getMethod(VALUES),keys:IS_SET?$default:getMethod(KEYS),entries:$entries},FORCED)for(key in methods)key in proto||redefine(proto,key,methods[key]);else $export($export.P+$export.F*(BUGGY||VALUES_BUG),NAME,methods);return methods}},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(O,P){if(O=toIObject(O),P=toPrimitive(P,!0),IE8_DOM_DEFINE)try{return gOPD(O,P)}catch(e){}if(has(O,P))return createDesc(!pIE.f.call(O,P),O[P])}},function(module,exports,__webpack_require__){var toIObject=__webpack_require__(13),gOPN=__webpack_require__(67).f,toString={}.toString,windowNames="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],getWindowNames=function(it){try{return gOPN(it)}catch(e){return windowNames.slice()}};module.exports.f=function(it){return windowNames&&"[object Window]"==toString.call(it)?getWindowNames(it):gOPN(toIObject(it))}},function(module,exports,__webpack_require__){var $keys=__webpack_require__(69),hiddenKeys=__webpack_require__(40).concat("length","prototype");exports.f=Object.getOwnPropertyNames||function(O){return $keys(O,hiddenKeys)}},function(module,exports,__webpack_require__){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){return O=toObject(O),has(O,IE_PROTO)?O[IE_PROTO]:"function"==typeof O.constructor&&O instanceof O.constructor?O.constructor.prototype:O instanceof Object?ObjectProto:null}},function(module,exports,__webpack_require__){var has=__webpack_require__(11),toIObject=__webpack_require__(13),arrayIndexOf=__webpack_require__(119)(!1),IE_PROTO=__webpack_require__(44)("IE_PROTO");module.exports=function(object,names){var key,O=toIObject(object),i=0,result=[];for(key in O)key!=IE_PROTO&&has(O,key)&&result.push(key);for(;names.length>i;)has(O,key=names[i++])&&(~arrayIndexOf(result,key)||result.push(key));return result}},function(module,exports,__webpack_require__){module.exports=__webpack_require__(12)},function(module,exports,__webpack_require__){var defer,channel,port,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",run=function(){var id=+this;if(queue.hasOwnProperty(id)){var fn=queue[id];delete queue[id],fn()}},listener=function(event){run.call(event.data)};setTask&&clearTask||(setTask=function(fn){for(var args=[],i=1;arguments.length>i;)args.push(arguments[i++]);return queue[++counter]=function(){invoke("function"==typeof fn?fn:Function(fn),args)},defer(counter),counter},clearTask=function(id){delete queue[id]},"process"==__webpack_require__(22)(process)?defer=function(id){process.nextTick(ctx(run,id,1))}:MessageChannel?(channel=new MessageChannel,port=channel.port2,channel.port1.onmessage=listener,defer=ctx(port.postMessage,port,1)):global.addEventListener&&"function"==typeof postMessage&&!global.importScripts?(defer=function(id){global.postMessage(id+"","*")},global.addEventListener("message",listener,!1)):defer=ONREADYSTATECHANGE in cel("script")?function(id){html.appendChild(cel("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this),run.call(id)}}:function(id){setTimeout(ctx(run,id,1),0)}),module.exports={set:setTask,clear:clearTask}},function(module,exports,__webpack_require__){var toInteger=__webpack_require__(46),min=Math.min;module.exports=function(it){return it>0?min(toInteger(it),9007199254740991):0}},function(module,exports){},function(module,exports,__webpack_require__){"use strict";var $at=__webpack_require__(138)(!0);__webpack_require__(64)(String,"String",function(iterated){this._t=String(iterated),this._i=0},function(){var point,O=this._t,index=this._i;return index>=O.length?{value:void 0,done:!0}:(point=$at(O,index),this._i+=point.length,{value:point,done:!1})})},function(module,exports,__webpack_require__){__webpack_require__(141);for(var global=__webpack_require__(4),hide=__webpack_require__(12),Iterators=__webpack_require__(24),TO_STRING_TAG=__webpack_require__(3)("toStringTag"),collections=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],i=0;i<5;i++){var NAME=collections[i],Collection=global[NAME],proto=Collection&&Collection.prototype;proto&&!proto[TO_STRING_TAG]&&hide(proto,TO_STRING_TAG,NAME),Iterators[NAME]=Iterators.Array}},function(module,exports){function baseSlice(array,start,end){var index=-1,length=array.length;start<0&&(start=-start>length?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index1&&void 0!==arguments[1]?arguments[1]:"orbit-db.cache";return cache={},cachePath?(store=new BlobStore(cachePath),filePath=cacheFile,new _promise2.default(function(resolve,reject){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()})))})})})):_promise2.default.resolve()}},{key:"reset",value:function(){cache={},store=null}}]),Cache}();module.exports=Cache}).call(exports,__webpack_require__(18).Buffer)},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _getPrototypeOf=__webpack_require__(15),_getPrototypeOf2=_interopRequireDefault(_getPrototypeOf),_assign=__webpack_require__(6),_assign2=_interopRequireDefault(_assign),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),_possibleConstructorReturn2=__webpack_require__(17),_possibleConstructorReturn3=_interopRequireDefault(_possibleConstructorReturn2),_inherits2=__webpack_require__(16),_inherits3=_interopRequireDefault(_inherits2),Store=__webpack_require__(29),CounterIndex=__webpack_require__(93),CounterStore=function(_Store){function CounterStore(ipfs,id,dbname){var options=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return(0,_classCallCheck3.default)(this,CounterStore),options.Index||(0,_assign2.default)(options,{Index:CounterIndex}),(0,_possibleConstructorReturn3.default)(this,(CounterStore.__proto__||(0,_getPrototypeOf2.default)(CounterStore)).call(this,ipfs,id,dbname,options))}return(0,_inherits3.default)(CounterStore,_Store),(0,_createClass3.default)(CounterStore,[{key:"inc",value:function(amount){var counter=this._index.get();if(counter)return counter.increment(amount),this._addOperation({op:"COUNTER",key:null,value:counter.payload,meta:{ts:(new Date).getTime()}})}},{key:"value",get:function(){return this._index.get().value}}]),CounterStore}(Store);module.exports=CounterStore},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _keys=__webpack_require__(14),_keys2=_interopRequireDefault(_keys),_getPrototypeOf=__webpack_require__(15),_getPrototypeOf2=_interopRequireDefault(_getPrototypeOf),_assign=__webpack_require__(6),_assign2=_interopRequireDefault(_assign),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),_possibleConstructorReturn2=__webpack_require__(17),_possibleConstructorReturn3=_interopRequireDefault(_possibleConstructorReturn2),_inherits2=__webpack_require__(16),_inherits3=_interopRequireDefault(_inherits2),Store=__webpack_require__(29),DocumentIndex=__webpack_require__(94),DocumentStore=function(_Store){function DocumentStore(ipfs,id,dbname,options){return(0,_classCallCheck3.default)(this,DocumentStore),options||(options={}),options.indexBy||(0,_assign2.default)(options,{indexBy:"_id"}),options.Index||(0,_assign2.default)(options,{Index:DocumentIndex}),(0,_possibleConstructorReturn3.default)(this,(DocumentStore.__proto__||(0,_getPrototypeOf2.default)(DocumentStore)).call(this,ipfs,id,dbname,options))}return(0,_inherits3.default)(DocumentStore,_Store),(0,_createClass3.default)(DocumentStore,[{key:"get",value:function(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(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(doc){return this._addOperation({op:"PUT",key:doc[this.options.indexBy],value:doc,meta:{ts:(new Date).getTime()}})}},{key:"del",value:function(key){return this._addOperation({op:"DEL",key:key,value:null,meta:{ts:(new Date).getTime()}})}}]),DocumentStore}(Store);module.exports=DocumentStore},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _getPrototypeOf=__webpack_require__(15),_getPrototypeOf2=_interopRequireDefault(_getPrototypeOf),_assign=__webpack_require__(6),_assign2=_interopRequireDefault(_assign),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),_possibleConstructorReturn2=__webpack_require__(17),_possibleConstructorReturn3=_interopRequireDefault(_possibleConstructorReturn2),_inherits2=__webpack_require__(16),_inherits3=_interopRequireDefault(_inherits2),EventStore=__webpack_require__(54),FeedIndex=__webpack_require__(95),FeedStore=function(_EventStore){function FeedStore(ipfs,id,dbname,options){return(0,_classCallCheck3.default)(this,FeedStore),options||(options={}),options.Index||(0,_assign2.default)(options,{Index:FeedIndex}),(0,_possibleConstructorReturn3.default)(this,(FeedStore.__proto__||(0,_getPrototypeOf2.default)(FeedStore)).call(this,ipfs,id,dbname,options))}return(0,_inherits3.default)(FeedStore,_EventStore),(0,_createClass3.default)(FeedStore,[{key:"remove",value:function(hash){var operation={op:"DEL",key:null,value:hash,meta:{ts:(new Date).getTime()}};return this._addOperation(operation)}}]),FeedStore}(EventStore);module.exports=FeedStore},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _getPrototypeOf=__webpack_require__(15),_getPrototypeOf2=_interopRequireDefault(_getPrototypeOf),_assign=__webpack_require__(6),_assign2=_interopRequireDefault(_assign),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),_possibleConstructorReturn2=__webpack_require__(17),_possibleConstructorReturn3=_interopRequireDefault(_possibleConstructorReturn2),_inherits2=__webpack_require__(16),_inherits3=_interopRequireDefault(_inherits2),Store=__webpack_require__(29),KeyValueIndex=__webpack_require__(96),KeyValueStore=function(_Store){function KeyValueStore(ipfs,id,dbname,options){(0,_classCallCheck3.default)(this,KeyValueStore);var opts=(0,_assign2.default)({},{Index:KeyValueIndex});return(0,_assign2.default)(opts,options),(0,_possibleConstructorReturn3.default)(this,(KeyValueStore.__proto__||(0,_getPrototypeOf2.default)(KeyValueStore)).call(this,ipfs,id,dbname,opts))}return(0,_inherits3.default)(KeyValueStore,_Store),(0,_createClass3.default)(KeyValueStore,[{key:"get",value:function(key){return this._index.get(key)}},{key:"set",value:function(key,data){this.put(key,data)}},{key:"put",value:function(key,data){return this._addOperation({op:"PUT",key:key,value:data,meta:{ts:(new Date).getTime()}})}},{key:"del",value:function(key){return this._addOperation({op:"DEL",key:key,value:null,meta:{ts:(new Date).getTime()}})}}]),KeyValueStore}(Store);module.exports=KeyValueStore},function(module,exports,__webpack_require__){"use strict";module.exports=__webpack_require__(97)},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _keys=__webpack_require__(14),_keys2=_interopRequireDefault(_keys),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),isEqual=__webpack_require__(89).isEqual,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}return(0,_createClass3.default)(GCounter,[{key:"increment",value:function(amount){amount||(amount=1),this._counters[this.id]=this._counters[this.id]+amount}},{key:"compare",value:function(other){return other.id===this.id&&isEqual(other._counters,this._counters)}},{key:"merge",value:function(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(){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(){return{id:this.id,counters:this._counters}}}],[{key:"from",value:function(payload){return new GCounter(payload.id,payload.counters)}}]),GCounter}();module.exports=GCounter},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _getOwnPropertyNames=__webpack_require__(100),_getOwnPropertyNames2=_interopRequireDefault(_getOwnPropertyNames);exports.isEqual=function(a,b){var propsA=(0,_getOwnPropertyNames2.default)(a),propsB=(0,_getOwnPropertyNames2.default)(b);if(propsA.length!==propsB.length)return!1;for(var i=0;i2&&void 0!==arguments[2]?arguments[2]:[];if(!ipfs)throw new Error("Entry requires ipfs instance");var nexts=null!==next&&next instanceof Array?next.map(function(e){return e.hash?e.hash:e}):[null!==next&&next.hash?next.hash:next],entry={hash:null,payload:data,next:nexts};return Entry.toIpfsHash(ipfs,entry).then(function(hash){return entry.hash=hash,entry})}},{key:"toIpfsHash",value:function(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})}},{key:"fromIpfsHash",value:function(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);return{hash:hash,payload:data.payload,next:data.next}})}},{key:"hasChild",value:function(entry1,entry2){return entry1.next.includes(entry2.hash)}},{key:"compare",value:function(a,b){return a.hash===b.hash}}]),Entry}()}).call(exports,__webpack_require__(18).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _stringify=__webpack_require__(36),_stringify2=_interopRequireDefault(_stringify),_assign=__webpack_require__(6),_assign2=_interopRequireDefault(_assign),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),EventEmitter=__webpack_require__(28).EventEmitter,unionWith=__webpack_require__(164),differenceWith=__webpack_require__(160),flatten=__webpack_require__(162),take=__webpack_require__(76),Promise=__webpack_require__(105),Entry=__webpack_require__(90),MaxBatchSize=10,MaxHistory=256,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}return(0,_createClass3.default)(Log,[{key:"add",value:function(data){var _this=this;return this._currentBatch.length>=MaxBatchSize&&this._commit(),Entry.create(this._ipfs,data,this._heads).then(function(entry){return _this._heads=[entry.hash],_this._currentBatch.push(entry),entry})}},{key:"join",value:function(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)),diff=differenceWith(newItems,this.items,Entry.compare),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);return final.length>0&&this.events.emit("history",this.options.maxHistory),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){return history.forEach(function(b){return _this2._insert(b)}),history})},{concurrency:1}).then(function(res){return _this2._heads=Log.findHeads(_this2),flatten(res).concat(diff)})}},{key:"_insert",value:function(entry){var _this3=this,indices=entry.next.map(function(next){return _this3._items.map(function(f){return f.hash}).indexOf(next)}),index=indices.length>0?Math.max(Math.max.apply(null,indices)+1,0):0;return this._items.splice(index,0,entry),entry}},{key:"_commit",value:function(){this._items=this._items.concat(this._currentBatch),this._currentBatch=[]}},{key:"_fetchRecursive",value:function(ipfs,hash,all,amount,depth){var _this4=this,isReferenced=function(list,item){return void 0!==list.reverse().find(function(f){return f===item})},result=[];return this.events.emit("progress",1),isReferenced(all,hash)||depth>=amount?Promise.resolve(result):Entry.fromIpfsHash(ipfs,hash).then(function(entry){return result.push(entry),all.push(hash),depth++,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(){return this._items.concat(this._currentBatch)}},{key:"snapshot",get:function(){return{id:this.id,items:this._heads}}}],[{key:"getIpfsHash",value:function(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(ipfs,hash,options){if(!ipfs)throw new Error("Ipfs instance not defined");if(!hash)throw new Error("Invalid hash: "+hash);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(log){return log.items.reverse().filter(function(f){return!Log.isReferencedInChain(log,f)}).map(function(f){return f.hash})}},{key:"isReferencedInChain",value:function(log,item){return void 0!==log.items.reverse().find(function(e){return Entry.hasChild(e,item)})}},{key:"batchSize",get:function(){return MaxBatchSize}}]),Log}();module.exports=Log}).call(exports,__webpack_require__(18).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(process){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _keys=__webpack_require__(14),_keys2=_interopRequireDefault(_keys),_assign=__webpack_require__(6),_assign2=_interopRequireDefault(_assign),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),fs=__webpack_require__(197),format=__webpack_require__(195).format,EventEmitter=__webpack_require__(28).EventEmitter,isNodejs=!!process.version,LogLevels={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR",NONE:"NONE"},GlobalLogLevel=LogLevels.DEBUG,GlobalLogfile=null,GlobalEvents=new EventEmitter,Colors={Black:0,Red:1,Green:2,Yellow:3,Blue:4,Magenta:5,Cyan:6,Grey:7,White:9,Default:9};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],defaultOptions={useColors:!0,color:Colors.Default,showTimestamp:!0,showLevel:!0,filename:GlobalLogfile,appendFile:!0},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}return(0,_createClass3.default)(Logger,[{key:"debug",value:function(){this._shouldLog(LogLevels.DEBUG)&&this._write(LogLevels.DEBUG,format.apply(null,arguments))}},{key:"log",value:function(){this._shouldLog(LogLevels.DEBUG)&&this.debug.apply(this,arguments)}},{key:"info",value:function(){this._shouldLog(LogLevels.INFO)&&this._write(LogLevels.INFO,format.apply(null,arguments))}},{key:"warn",value:function(){this._shouldLog(LogLevels.WARN)&&this._write(LogLevels.WARN,format.apply(null,arguments))}},{key:"error",value:function(){this._shouldLog(LogLevels.ERROR)&&this._write(LogLevels.ERROR,format.apply(null,arguments))}},{key:"_write",value:function(level,text){(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),unformattedText=this._createLogMessage(level,text),formattedText=this._createLogMessage(level,text,format.timestamp,format.level,format.category,format.text);this.fileWriter&&isNodejs&&fs.writeSync(this.fileWriter,unformattedText+"\n",null,"utf-8"),isNodejs||!this.options.useColors?(console.log(formattedText),GlobalEvents.emit("data",this.category,level,text)):level===LogLevels.ERROR?this.options.showTimestamp&&this.options.showLevel?console.error(formattedText,format.timestamp,format.level,format.category,format.text):this.options.showTimestamp&&!this.options.showLevel?console.error(formattedText,format.timestamp,format.category,format.text):!this.options.showTimestamp&&this.options.showLevel?console.error(formattedText,format.level,format.category,format.text):console.error(formattedText,format.category,format.text):this.options.showTimestamp&&this.options.showLevel?console.log(formattedText,format.timestamp,format.level,format.category,format.text):this.options.showTimestamp&&!this.options.showLevel?console.log(formattedText,format.timestamp,format.category,format.text):!this.options.showTimestamp&&this.options.showLevel?console.log(formattedText,format.level,format.category,format.text):console.log(formattedText,format.category,format.text)}},{key:"_format",value:function(level,text){var timestampFormat="",levelFormat="",categoryFormat="",textFormat=": ";if(this.options.useColors){var levelColor=(0,_keys2.default)(LogLevels).map(function(f){return LogLevels[f]}).indexOf(level),categoryColor=this.options.color;isNodejs?(this.options.showTimestamp&&(timestampFormat="[3"+Colors.Grey+"m"),this.options.showLevel&&(levelFormat="[3"+loglevelColors[levelColor]+";22m"),categoryFormat="[3"+categoryColor+";1m",textFormat=": "):(this.options.showTimestamp&&(timestampFormat="color:"+Colors.Grey),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(level,text,timestampFormat,levelFormat,categoryFormat,textFormat){timestampFormat=timestampFormat||"",levelFormat=levelFormat||"",categoryFormat=categoryFormat||"",textFormat=textFormat||": ",!isNodejs&&this.options.useColors&&(this.options.showTimestamp&&(timestampFormat="%c"),this.options.showLevel&&(levelFormat="%c"),categoryFormat="%c",textFormat=": %c");var result="";return this.options.showTimestamp&&(result+=(new Date).toISOString()+" "),result=timestampFormat+result,this.options.showLevel&&(result+=levelFormat+"["+level+"]"+(level===LogLevels.INFO||level===LogLevels.WARN?" ":"")+" "),result+=categoryFormat+this.category,result+=textFormat+text}},{key:"_shouldLog",value:function(level){var envLogLevel=void 0!==process&&void 0!==process.env&&void 0!==process.env.LOG?process.env.LOG.toUpperCase():null;envLogLevel="undefined"!=typeof window&&window.LOG?window.LOG.toUpperCase():envLogLevel;var logLevel=envLogLevel||GlobalLogLevel,levels=(0,_keys2.default)(LogLevels).map(function(f){return LogLevels[f]});return levels.indexOf(level)>=levels.indexOf(logLevel)}}]),Logger}();module.exports={Colors:Colors,LogLevels:LogLevels,setLogLevel:function(level){GlobalLogLevel=level},setLogfile:function(filename){GlobalLogfile=filename},create:function(category,options){return new Logger(category,options)},forceBrowserMode:function(force){return isNodejs=!force},events:GlobalEvents}}).call(exports,__webpack_require__(25))},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),Counter=__webpack_require__(88),CounterIndex=function(){function CounterIndex(id){(0,_classCallCheck3.default)(this,CounterIndex),this._counter=new Counter(id)}return(0,_createClass3.default)(CounterIndex,[{key:"get",value:function(){return this._counter}},{key:"updateIndex",value:function(oplog,added){var _this=this;this._counter&&added.filter(function(f){return f&&"COUNTER"===f.payload.op}).map(function(f){return Counter.from(f.payload.value)}).forEach(function(f){return _this._counter.merge(f)})}}]),CounterIndex}();module.exports=CounterIndex},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),DocumentIndex=function(){function DocumentIndex(){(0,_classCallCheck3.default)(this,DocumentIndex),this._index={}}return(0,_createClass3.default)(DocumentIndex,[{key:"get",value:function(key){return this._index[key]}},{key:"updateIndex",value:function(oplog,added){var _this=this;added.reverse().reduce(function(handled,item){return handled.indexOf(item.payload.key)===-1&&(handled.push(item.payload.key),"PUT"===item.payload.op?_this._index[item.payload.key]=item.payload.value:"DEL"===item.payload.op&&delete _this._index[item.payload.key]),handled},[])}}]),DocumentIndex}();module.exports=DocumentIndex},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _getPrototypeOf=__webpack_require__(15),_getPrototypeOf2=_interopRequireDefault(_getPrototypeOf),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),_possibleConstructorReturn2=__webpack_require__(17),_possibleConstructorReturn3=_interopRequireDefault(_possibleConstructorReturn2),_inherits2=__webpack_require__(16),_inherits3=_interopRequireDefault(_inherits2),EventIndex=__webpack_require__(55),FeedIndex=function(_EventIndex){function FeedIndex(){return(0,_classCallCheck3.default)(this,FeedIndex),(0,_possibleConstructorReturn3.default)(this,(FeedIndex.__proto__||(0,_getPrototypeOf2.default)(FeedIndex)).apply(this,arguments))}return(0,_inherits3.default)(FeedIndex,_EventIndex),(0,_createClass3.default)(FeedIndex,[{key:"updateIndex",value:function(oplog,added){var _this2=this;added.reduce(function(handled,item){return handled.includes(item.hash)||(handled.push(item.hash),"ADD"===item.payload.op?_this2._index[item.hash]=item:"DEL"===item.payload.op&&delete _this2._index[item.payload.value]),handled},[])}}]),FeedIndex}(EventIndex);module.exports=FeedIndex},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),KeyValueIndex=function(){function KeyValueIndex(){(0,_classCallCheck3.default)(this,KeyValueIndex),this._index={}}return(0,_createClass3.default)(KeyValueIndex,[{key:"get",value:function(key){return this._index[key]}},{key:"updateIndex",value:function(oplog,added){var _this=this;added.reverse().reduce(function(handled,item){return handled.includes(item.payload.key)||(handled.push(item.payload.key),"PUT"===item.payload.op?_this._index[item.payload.key]=item.payload.value:"DEL"===item.payload.op&&delete _this._index[item.payload.key]),handled},[])}}]),KeyValueIndex}();module.exports=KeyValueIndex},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _keys=__webpack_require__(14),_keys2=_interopRequireDefault(_keys),_classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),Logger=__webpack_require__(92),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={},null===this._ipfs.pubsub&&logger.error("The provided version of ipfs doesn't have pubsub support. Messages will not be exchanged.")}return(0,_createClass3.default)(IPFSPubsub,[{key:"subscribe",value:function(hash,onMessageCallback){this._subscriptions[hash]||(this._subscriptions[hash]={onMessage:onMessageCallback},this._ipfs.pubsub&&this._ipfs.pubsub.subscribe(hash,{discover:!0},this._handleMessage.bind(this)))}},{key:"unsubscribe",value:function(hash){this._subscriptions[hash]&&(this._ipfs.pubsub.unsubscribe(hash,this._handleMessage),delete this._subscriptions[hash],logger.debug("Unsubscribed from '"+hash+"'"))}},{key:"publish",value:function(hash,message){this._subscriptions[hash]&&this._ipfs.pubsub&&this._ipfs.pubsub.publish(hash,new Buffer(message))}},{key:"disconnect",value:function(){var _this=this;(0,_keys2.default)(this._subscriptions).forEach(function(e){return _this.unsubscribe(e)})}},{key:"_handleMessage",value:function(message){var hash=message.topicCIDs[0],data=message.data.toString(),subscription=this._subscriptions[hash];subscription&&subscription.onMessage&&data&&subscription.onMessage(hash,data)}}]),IPFSPubsub}();module.exports=IPFSPubsub}).call(exports,__webpack_require__(18).Buffer)},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _classCallCheck2=__webpack_require__(0),_classCallCheck3=_interopRequireDefault(_classCallCheck2),_createClass2=__webpack_require__(1),_createClass3=_interopRequireDefault(_createClass2),Index=function(){function Index(id){(0,_classCallCheck3.default)(this,Index),this.id=id,this._index=[]}return(0,_createClass3.default)(Index,[{key:"get",value:function(){return this._index}},{key:"updateIndex",value:function(oplog,entries){this._index=oplog.ops}}]),Index}();module.exports=Index},function(module,exports,__webpack_require__){module.exports={default:__webpack_require__(108),__esModule:!0}},function(module,exports,__webpack_require__){module.exports={default:__webpack_require__(110),__esModule:!0}},function(module,exports,__webpack_require__){module.exports={default:__webpack_require__(113),__esModule:!0}},function(module,exports,__webpack_require__){module.exports={default:__webpack_require__(115),__esModule:!0}},function(module,exports,__webpack_require__){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.__esModule=!0;var _defineProperty=__webpack_require__(56),_defineProperty2=_interopRequireDefault(_defineProperty);exports.default=function(obj,key,value){return key in obj?(0,_defineProperty2.default)(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}},function(module,exports,__webpack_require__){"use strict";function placeHoldersCount(b64){var len=b64.length;if(len%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===b64[len-2]?2:"="===b64[len-1]?1:0}function byteLength(b64){return 3*b64.length/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr,len=b64.length;placeHolders=placeHoldersCount(b64),arr=new Arr(3*len/4-placeHolders),l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255,arr[L++]=tmp>>8&255,arr[L++]=255&tmp;return 2===placeHolders?(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[L++]=255&tmp):1===placeHolders&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[L++]=tmp>>8&255,arr[L++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],output+=lookup[tmp>>2],output+=lookup[tmp<<4&63],output+="=="):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],output+=lookup[tmp>>10],output+=lookup[tmp>>4&63],output+=lookup[tmp<<2&63],output+="="),parts.push(output),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i0;){var fn=queue.shift();if("function"==typeof fn){var receiver=queue.shift(),arg=queue.shift();fn.call(receiver,arg)}else fn._settlePromises()}},Async.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},Async.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},Async.prototype._reset=function(){this._isTickUsed=!1},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=!1,rejectThis=function(_,e){this._reject(e)},targetRejected=function(e,context){context.promiseRejectionQueued=!0,context.bindingPromise._then(rejectThis,rejectThis,null,this,e)},bindingResolved=function(thisArg,context){0===(50397184&this._bitField)&&this._resolveCallback(context.target)},bindingRejected=function(e,context){context.promiseRejectionQueued||this._reject(e)};Promise.prototype.bind=function(thisArg){calledBind||(calledBind=!0,Promise.prototype._propagateFrom=debug.propagateFromFunction(),Promise.prototype._boundValue=debug.boundValueFunction());var maybePromise=tryConvertToPromise(thisArg),ret=new Promise(INTERNAL);ret._propagateFrom(this,1);var target=this._target();if(ret._setBoundTo(maybePromise),maybePromise instanceof Promise){var context={promiseRejectionQueued:!1,promise:ret,target:target,bindingPromise:maybePromise};target._then(INTERNAL,targetRejected,void 0,ret,context),maybePromise._then(bindingResolved,bindingRejected,void 0,ret,context),ret._setOnCancel(maybePromise)}else ret._resolveCallback(target);return ret},Promise.prototype._setBoundTo=function(obj){void 0!==obj?(this._bitField=2097152|this._bitField,this._boundTo=obj):this._bitField=this._bitField&-2097153},Promise.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},Promise.bind=function(thisArg,value){return Promise.resolve(value).bind(thisArg)}}},{}],4:[function(_dereq_,module,exports){"use strict";function noConflict(){try{Promise===bluebird&&(Promise=old)}catch(e){}return bluebird}var old;"undefined"!=typeof Promise&&(old=Promise);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),getterCache=cr(null);callerCache[" size"]=getterCache[" size"]=0}module.exports=function(Promise){function ensureMethod(obj,methodName){var fn;if(null!=obj&&(fn=obj[methodName]),"function"!=typeof fn){var message="Object "+util.classString(obj)+" has no method '"+util.toString(methodName)+"'";throw new Promise.TypeError(message)}return fn}function caller(obj){return ensureMethod(obj,this.pop()).apply(obj,this)}function namedGetter(obj){return obj[this]}function indexedGetter(obj){var index=+this;return index<0&&(index=Math.max(0,index+obj.length)),obj[index]}var getGetter,util=_dereq_("./util"),canEvaluate=util.canEvaluate;util.isIdentifier;Promise.prototype.call=function(methodName){var args=[].slice.call(arguments,1);return args.push(methodName),this._then(caller,void 0,void 0,args,void 0)},Promise.prototype.get=function(propertyName){var getter,isIndex="number"==typeof propertyName;if(isIndex)getter=indexedGetter;else if(canEvaluate){var maybeGetter=getGetter(propertyName);getter=null!==maybeGetter?maybeGetter:namedGetter}else getter=namedGetter;return this._then(getter,void 0,void 0,propertyName,void 0)}}},{"./util":36}],6:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,debug){var util=_dereq_("./util"),tryCatch=util.tryCatch,errorObj=util.errorObj,async=Promise._async;Promise.prototype.break=Promise.prototype.cancel=function(){if(!debug.cancellation())return this._warn("cancellation is disabled");for(var promise=this,child=promise;promise._isCancellable();){if(!promise._cancelBy(child)){child._isFollowing()?child._followee().cancel():child._cancelBranched();break}var parent=promise._cancellationParent;if(null==parent||!parent._isCancellable()){promise._isFollowing()?promise._followee().cancel():promise._cancelBranched();break}promise._isFollowing()&&promise._followee().cancel(),promise._setWillBeCancelled(),child=promise,promise=parent}},Promise.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},Promise.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},Promise.prototype._cancelBy=function(canceller){return canceller===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},Promise.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},Promise.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),async.invoke(this._cancelPromises,this,void 0))},Promise.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},Promise.prototype._unsetOnCancel=function(){this._onCancelField=void 0},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=0)return contextStack[lastIndex]}var longStackTraces=!1,contextStack=[];return Promise.prototype._promiseCreated=function(){},Promise.prototype._pushContext=function(){},Promise.prototype._popContext=function(){return null},Promise._peekContext=Promise.prototype._peekContext=function(){},Context.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,contextStack.push(this._trace))},Context.prototype._popContext=function(){if(void 0!==this._trace){var trace=contextStack.pop(),ret=trace._promiseCreated;return trace._promiseCreated=null,ret}return null},Context.CapturedTrace=null,Context.create=createContext,Context.deactivateLongStackTraces=function(){},Context.activateLongStackTraces=function(){var Promise_pushContext=Promise.prototype._pushContext,Promise_popContext=Promise.prototype._popContext,Promise_PeekContext=Promise._peekContext,Promise_peekContext=Promise.prototype._peekContext,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=!1},longStackTraces=!0,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();ctx&&null==ctx._promiseCreated&&(ctx._promiseCreated=this)}},Context}},{}],9:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,Context){function generatePromiseLifecycleEventObject(name,promise){return{promise:promise}}function defaultFireEvent(){return!1}function cancellationExecute(executor,resolve,reject){var promise=this;try{executor(resolve,reject,function(onCancel){if("function"!=typeof onCancel)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();void 0!==previousOnCancel?util.isArray(previousOnCancel)?previousOnCancel.push(onCancel):this._setOnCancel([previousOnCancel,onCancel]):this._setOnCancel(onCancel)}function cancellationOnCancel(){return this._onCancelField}function cancellationSetOnCancel(onCancel){this._onCancelField=onCancel}function cancellationClearCancellationData(){this._cancellationParent=void 0,this._onCancelField=void 0}function cancellationPropagateFrom(parent,flags){if(0!==(1&flags)){this._cancellationParent=parent;var branchesRemainingToCancel=parent._branchesRemainingToCancel;void 0===branchesRemainingToCancel&&(branchesRemainingToCancel=0),parent._branchesRemainingToCancel=branchesRemainingToCancel+1}0!==(2&flags)&&parent._isBound()&&this._setBoundTo(parent._boundTo)}function bindingPropagateFrom(parent,flags){0!==(2&flags)&&parent._isBound()&&this._setBoundTo(parent._boundTo)}function boundValueFunction(){var ret=this._boundTo;return void 0!==ret&&ret instanceof Promise?ret.isFulfilled()?ret.value():void 0:ret}function longStackTracesCaptureStackTrace(){this._trace=new CapturedTrace(this._peekContext())}function longStackTracesAttachExtraTrace(error,ignoreSelf){if(canAttachTrace(error)){var trace=this._trace;if(void 0!==trace&&ignoreSelf&&(trace=trace._parent),void 0!==trace)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__",!0)}}}function checkForgottenReturns(returnValue,promiseCreated,name,promise,parent){if(void 0===returnValue&&null!==promiseCreated&&wForgottenReturn){if(void 0!==parent&&parent._returnedNonUndefined())return;if(0===(65535&promise._bitField))return;name&&(name+=" ");var handlerLine="",creatorLine="";if(promiseCreated._trace){for(var traceLines=promiseCreated._trace.stack.split("\n"),stack=cleanStack(traceLines),i=stack.length-1;i>=0;--i){var line=stack[i];if(!nodeFramePattern.test(line)){var lineMatches=line.match(parseLinePattern);lineMatches&&(handlerLine="at "+lineMatches[1]+":"+lineMatches[2]+":"+lineMatches[3]+" ");break}}if(stack.length>0)for(var firstUserLine=stack[0],i=0;i0&&(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,!0,promiseCreated)}}function deprecated(name,replacement){var message=name+" is deprecated and will be removed in a future version.";return replacement&&(message+=" Use "+replacement+" instead."),warn(message)}function warn(message,shouldUseOwnTrace,promise){if(config.warnings){var ctx,warning=new Warning(message);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")}activeFireEvent("warning",warning)||formatAndLogError(warning,"",!0)}}function reconstructStack(message,stacks){for(var i=0;i=0;--j)if(prev[j]===currentLastLine){commonRootMeetPoint=j;break}for(var j=commonRootMeetPoint;j>=0;--j){var line=prev[j];if(current[currentLastIndex]!==line)break;current.pop(),currentLastIndex--}current=prev}}function cleanStack(stack){for(var ret=[],i=0;i0&&"SyntaxError"!=error.name&&(stack=stack.slice(i)),stack}function parseStackAndMessage(error){var stack=error.stack,message=error.toString();return stack="string"==typeof stack&&stack.length>0?stackFramesAsArray(error):[" (No stack trace)"],{message:message,stack:"SyntaxError"==error.name?stack:cleanStack(stack)}}function formatAndLogError(error,title,isSoft){if("undefined"!=typeof console){var message;if(util.isObject(error)){message=title+formatStack(error.stack,error)}else message=title+String(error);"function"==typeof printWarning?printWarning(message,isSoft):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(message)}}function fireRejectionEvent(name,localHandler,reason,promise){var localEventFired=!1;try{"function"==typeof localHandler&&(localEventFired=!0,"rejectionHandled"===name?localHandler(promise):localHandler(reason,promise))}catch(e){async.throwLater(e)}"unhandledRejection"===name?activeFireEvent(name,reason,promise)||localEventFired||formatAndLogError(reason,"Unhandled rejection "):activeFireEvent(name,promise)}function formatNonError(obj){var str;if("function"==typeof obj)str="[function "+(obj.name||"anonymous")+"]";else{str=obj&&"function"==typeof obj.toString?obj.toString():util.toString(obj);if(/\[object [a-zA-Z0-9$_]+\]/.test(str))try{str=JSON.stringify(obj)}catch(e){}0===str.length&&(str="(empty array)")}return"(<"+snip(str)+">, no stack trace)"}function snip(str){var maxChars=41;return str.length=lastIndex||(shouldIgnore=function(line){if(bluebirdFramePattern.test(line))return!0;var info=parseLineInfo(line);return!!(info&&info.fileName===firstFileName&&firstIndex<=info.line&&info.line<=lastIndex)})}}function CapturedTrace(parent){this._parent=parent,this._promisesCreated=0;var length=this._length=1+(void 0===parent?0:parent._length);captureStackTrace(this,CapturedTrace),length>32&&this.uncycle()}var unhandledRejectionHandled,possiblyUnhandledRejection,printWarning,getDomain=Promise._getDomain,async=Promise._async,Warning=_dereq_("./errors").Warning,util=_dereq_("./util"),canAttachTrace=util.canAttachTrace,bluebirdFramePattern=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,nodeFramePattern=/\((?:timers\.js):\d+:\d+\)/,parseLinePattern=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,stackFramePattern=null,formatStack=null,indentStackFrames=!1,debugging=!(0==util.env("BLUEBIRD_DEBUG")),warnings=!(0==util.env("BLUEBIRD_WARNINGS")||!debugging&&!util.env("BLUEBIRD_WARNINGS")),longStackTraces=!(0==util.env("BLUEBIRD_LONG_STACK_TRACES")||!debugging&&!util.env("BLUEBIRD_LONG_STACK_TRACES")),wForgottenReturn=0!=util.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(warnings||!!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));Promise.prototype.suppressUnhandledRejections=function(){var target=this._target();target._bitField=target._bitField&-1048577|524288},Promise.prototype._ensurePossibleRejectionHandled=function(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),async.invokeLater(this._notifyUnhandledRejection,this,void 0))},Promise.prototype._notifyUnhandledRejectionIsHandled=function(){fireRejectionEvent("rejectionHandled",unhandledRejectionHandled,void 0,this)},Promise.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},Promise.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},Promise.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var reason=this._settledValue();this._setUnhandledRejectionIsNotified(),fireRejectionEvent("unhandledRejection",possiblyUnhandledRejection,reason,this)}},Promise.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},Promise.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=this._bitField&-262145},Promise.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},Promise.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},Promise.prototype._unsetRejectionIsUnhandled=function(){this._bitField=this._bitField&-1048577,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},Promise.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},Promise.prototype._warn=function(message,shouldUseOwnTrace,promise){return warn(message,shouldUseOwnTrace,promise||this)},Promise.onPossiblyUnhandledRejection=function(fn){var domain=getDomain();possiblyUnhandledRejection="function"==typeof fn?null===domain?fn:util.domainBind(domain,fn):void 0},Promise.onUnhandledRejectionHandled=function(fn){var domain=getDomain();unhandledRejectionHandled="function"==typeof fn?null===domain?fn:util.domainBind(domain,fn):void 0};var disableLongStackTraces=function(){};Promise.longStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!config.longStackTraces&&longStackTracesIsSupported()){var Promise_captureStackTrace=Promise.prototype._captureStackTrace,Promise_attachExtraTrace=Promise.prototype._attachExtraTrace;config.longStackTraces=!0,disableLongStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");Promise.prototype._captureStackTrace=Promise_captureStackTrace,Promise.prototype._attachExtraTrace=Promise_attachExtraTrace,Context.deactivateLongStackTraces(),async.enableTrampoline(),config.longStackTraces=!1},Promise.prototype._captureStackTrace=longStackTracesCaptureStackTrace,Promise.prototype._attachExtraTrace=longStackTracesAttachExtraTrace,Context.activateLongStackTraces(),async.disableTrampolineIfNecessary()}},Promise.hasLongStackTraces=function(){return config.longStackTraces&&longStackTracesIsSupported()};var fireDomEvent=function(){try{if("function"==typeof CustomEvent){var event=new CustomEvent("CustomEvent");return util.global.dispatchEvent(event),function(name,event){var domEvent=new CustomEvent(name.toLowerCase(),{detail:event,cancelable:!0});return!util.global.dispatchEvent(domEvent)}}if("function"==typeof Event){var event=new Event("CustomEvent");return util.global.dispatchEvent(event),function(name,event){var domEvent=new Event(name.toLowerCase(),{cancelable:!0});return domEvent.detail=event,!util.global.dispatchEvent(domEvent)}}var event=document.createEvent("CustomEvent");return event.initCustomEvent("testingtheevent",!1,!0,{}),util.global.dispatchEvent(event),function(name,event){var domEvent=document.createEvent("CustomEvent");return domEvent.initCustomEvent(name.toLowerCase(),!1,!0,event),!util.global.dispatchEvent(domEvent)}}catch(e){}return function(){return!1}}(),fireGlobalEvent=function(){return util.isNode?function(){return process.emit.apply(process,arguments)}:util.global?function(name){var methodName="on"+name.toLowerCase(),method=util.global[methodName];return!!method&&(method.apply(util.global,[].slice.call(arguments,1)),!0)}:function(){return!1}}(),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},activeFireEvent=function(name){var globalEventFired=!1;try{globalEventFired=fireGlobalEvent.apply(null,arguments)}catch(e){async.throwLater(e),globalEventFired=!0}var domEventFired=!1;try{domEventFired=fireDomEvent(name,eventToObjectGenerator[name].apply(null,arguments))}catch(e){async.throwLater(e),domEventFired=!0}return domEventFired||globalEventFired};Promise.config=function(opts){if(opts=Object(opts),"longStackTraces"in opts&&(opts.longStackTraces?Promise.longStackTraces():!opts.longStackTraces&&Promise.hasLongStackTraces()&&disableLongStackTraces()),"warnings"in opts){var warningsOption=opts.warnings;config.warnings=!!warningsOption,wForgottenReturn=config.warnings,util.isObject(warningsOption)&&"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=!0}return"monitoring"in opts&&(opts.monitoring&&!config.monitoring?(config.monitoring=!0,Promise.prototype._fireEvent=activeFireEvent):!opts.monitoring&&config.monitoring&&(config.monitoring=!1,Promise.prototype._fireEvent=defaultFireEvent)),Promise},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){};var propagateFromFunction=bindingPropagateFrom,shouldIgnore=function(){return!1},parseLineInfoRegex=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;util.inherits(CapturedTrace,Error),Context.CapturedTrace=CapturedTrace,CapturedTrace.prototype.uncycle=function(){var length=this._length;if(!(length<2)){for(var nodes=[],stackToIndex={},i=0,node=this;void 0!==node;++i)nodes.push(node),node=node._parent;length=this._length=i;for(var i=length-1;i>=0;--i){var stack=nodes[i].stack;void 0===stackToIndex[stack]&&(stackToIndex[stack]=i)}for(var i=0;i0&&(nodes[index-1]._parent=void 0,nodes[index-1]._length=1),nodes[i]._parent=void 0,nodes[i]._length=1;var cycleEdgeNode=i>0?nodes[i-1]:this;index=0;--j)nodes[j]._length=currentChildLength,currentChildLength++;return}}}},CapturedTrace.prototype.attachExtraTrace=function(error){if(!error.__stackCleaned__){this.uncycle();for(var parsed=parseStackAndMessage(error),message=parsed.message,stacks=[parsed.stack],trace=this;void 0!==trace;)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__",!0)}};var captureStackTrace=function(){var v8stackFramePattern=/^\s*at\s*/,v8stackFormatter=function(stack,error){return"string"==typeof stack?stack:void 0!==error.name&&void 0!==error.message?error.toString():formatNonError(error)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter;var captureStackTrace=Error.captureStackTrace;return shouldIgnore=function(line){return bluebirdFramePattern.test(line)},function(receiver,ignoreUntil){Error.stackTraceLimit+=6,captureStackTrace(receiver,ignoreUntil),Error.stackTraceLimit-=6}}var err=new Error;if("string"==typeof err.stack&&err.stack.split("\n")[0].indexOf("stackDetection@")>=0)return stackFramePattern=/@/,formatStack=v8stackFormatter,indentStackFrames=!0,function(o){o.stack=(new Error).stack};var hasStackAfterThrow;try{throw new Error}catch(e){hasStackAfterThrow="stack"in e}return"stack"in err||!hasStackAfterThrow||"number"!=typeof Error.stackTraceLimit?(formatStack=function(stack,error){return"string"==typeof stack?stack:"object"!=typeof error&&"function"!=typeof error||void 0===error.name||void 0===error.message?formatNonError(error):error.toString()},null):(stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter,function(o){Error.stackTraceLimit+=6;try{throw new Error}catch(e){o.stack=e.stack}Error.stackTraceLimit-=6})}();"undefined"!=typeof console&&void 0!==console.warn&&(printWarning=function(message){console.warn(message)},util.isNode&&process.stderr.isTTY?printWarning=function(message,isSoft){var color=isSoft?"":"";console.warn(color+message+"\n")}:util.isNode||"string"!=typeof(new Error).stack||(printWarning=function(message,isSoft){console.warn("%c"+message,isSoft?"color: darkorange":"color: red")}));var config={warnings:warnings,longStackTraces:!1,cancellation:!1,monitoring:!1};return longStackTraces&&Promise.longStackTraces(),{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){return value instanceof Promise&&value.suppressUnhandledRejections(),this._then(returner,void 0,void 0,{value:value},void 0)},Promise.prototype.throw=Promise.prototype.thenThrow=function(reason){return this._then(thrower,void 0,void 0,{reason:reason},void 0)},Promise.prototype.catchThrow=function(reason){if(arguments.length<=1)return this._then(void 0,thrower,void 0,{reason:reason},void 0);var _reason=arguments[1],handler=function(){throw _reason};return this.caught(reason,handler)},Promise.prototype.catchReturn=function(value){if(arguments.length<=1)return value instanceof Promise&&value.suppressUnhandledRejections(),this._then(void 0,returner,void 0,{value:value},void 0);var _value=arguments[1];_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){function promiseAllThis(){return PromiseAll(this)}function PromiseMapSeries(promises,fn){return PromiseReduce(promises,fn,INTERNAL,INTERNAL)}var PromiseReduce=Promise.reduce,PromiseAll=Promise.all;Promise.prototype.each=function(fn){return PromiseReduce(this,fn,INTERNAL,0)._then(promiseAllThis,void 0,void 0,this,void 0)},Promise.prototype.mapSeries=function(fn){return PromiseReduce(this,fn,INTERNAL,INTERNAL)},Promise.each=function(promises,fn){return PromiseReduce(promises,fn,INTERNAL,0)._then(promiseAllThis,void 0,void 0,promises,void 0)},Promise.mapSeries=PromiseMapSeries}},{}],12:[function(_dereq_,module,exports){"use strict";function subError(nameProperty,defaultMessage){function SubError(message){if(!(this instanceof SubError))return new SubError(message);notEnumerableProp(this,"message","string"==typeof message?message:defaultMessage),notEnumerableProp(this,"name",nameProperty),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return inherits(SubError,Error),SubError}function OperationalError(message){if(!(this instanceof OperationalError))return new OperationalError(message);notEnumerableProp(this,"name","OperationalError"),notEnumerableProp(this,"message",message),this.cause=message,this.isOperational=!0,message instanceof Error?(notEnumerableProp(this,"message",message.message),notEnumerableProp(this,"stack",message.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}var _TypeError,_RangeError,es5=_dereq_("./es5"),Objectfreeze=es5.freeze,util=_dereq_("./util"),inherits=util.inherits,notEnumerableProp=util.notEnumerableProp,Warning=subError("Warning","warning"),CancellationError=subError("CancellationError","cancellation error"),TimeoutError=subError("TimeoutError","timeout error"),AggregateError=subError("AggregateError","aggregate error");try{_TypeError=TypeError,_RangeError=RangeError}catch(e){_TypeError=subError("TypeError","type error"),_RangeError=subError("RangeError","range error")}for(var methods="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),i=0;i1?ctx.cancelPromise._reject(reason):ctx.cancelPromise._cancel(),ctx.cancelPromise=null,!0)}function succeed(){return finallyHandler.call(this,this.promise._target()._settledValue())}function fail(reason){if(!checkCancel(this,reason))return errorObj.e=reason,errorObj}function finallyHandler(reasonOrValue){var promise=this.promise,handler=this.handler;if(!this.called){this.called=!0;var ret=this.isFinallyHandler()?handler.call(promise._boundValue()):handler.call(promise._boundValue(),reasonOrValue);if(void 0!==ret){promise._setReturnedNonUndefined();var maybePromise=tryConvertToPromise(ret,promise);if(maybePromise instanceof Promise){if(null!=this.cancelPromise){if(maybePromise._isCancelled()){var reason=new CancellationError("late cancellation observer");return promise._attachExtraTrace(reason),errorObj.e=reason,errorObj}maybePromise.isPending()&&maybePromise._attachCancellationCallback(new FinallyHandlerCancelReaction(this))}return maybePromise._then(succeed,fail,void 0,this,void 0)}}}return promise.isRejected()?(checkCancel(this),errorObj.e=reasonOrValue,errorObj):(checkCancel(this),reasonOrValue)}var util=_dereq_("./util"),CancellationError=Promise.CancellationError,errorObj=util.errorObj;return PassThroughHandlerContext.prototype.isFinallyHandler=function(){return 0===this.type},FinallyHandlerCancelReaction.prototype._resultCancelled=function(){checkCancel(this.finallyHandler)},Promise.prototype._passThrough=function(handler,type,success,fail){return"function"!=typeof handler?this.then():this._then(success,fail,void 0,new PassThroughHandlerContext(this,type,handler),void 0)},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)},PassThroughHandlerContext}},{"./util":36}],16:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug){function promiseFromYieldHandler(value,yieldHandlers,traceParent){for(var i=0;i0&&"function"==typeof arguments[last]){fn=arguments[last];var ret}var args=[].slice.call(arguments);fn&&args.pop();var ret=new PromiseArray(args).promise();return void 0!==fn?ret.spread(fn):ret}}},{"./util":36}],18:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){function MappingPromiseArray(promises,fn,limit,_filter){this.constructor$(promises),this._promise._captureStackTrace();var domain=getDomain();this._callback=null===domain?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,void 0)}function map(promises,fn,options,_filter){if("function"!=typeof fn)return apiRejection("expecting a function but got "+util.classString(fn));var limit=0;if(void 0!==options){if("object"!=typeof options||null===options)return Promise.reject(new TypeError("options argument must be an object but it is "+util.classString(options)));if("number"!=typeof options.concurrency)return Promise.reject(new TypeError("'concurrency' must be a number but it is "+util.classString(options.concurrency)));limit=options.concurrency}return limit="number"==typeof limit&&isFinite(limit)&&limit>=1?limit:0,new MappingPromiseArray(promises,fn,limit,_filter).promise()}var getDomain=Promise._getDomain,util=_dereq_("./util"),tryCatch=util.tryCatch,errorObj=util.errorObj,async=Promise._async;util.inherits(MappingPromiseArray,PromiseArray),MappingPromiseArray.prototype._asyncInit=function(){this._init$(void 0,-2)},MappingPromiseArray.prototype._init=function(){},MappingPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values,length=this.length(),preservedValues=this._preservedValues,limit=this._limit;if(index<0){if(index=index*-1-1,values[index]=value,limit>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(limit>=1&&this._inFlight>=limit)return values[index]=value,this._queue.push(index),!1;null!==preservedValues&&(preservedValues[index]=value);var promise=this._promise,callback=this._callback,receiver=promise._boundValue();promise._pushContext();var ret=tryCatch(callback).call(receiver,value,index,length),promiseCreated=promise._popContext();if(debug.checkForgottenReturns(ret,promiseCreated,null!==preservedValues?"Promise.filter":"Promise.map",promise),ret===errorObj)return this._reject(ret.e),!0;var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();var bitField=maybePromise._bitField;if(0===(50397184&bitField))return limit>=1&&this._inFlight++,values[index]=maybePromise,maybePromise._proxy(this,(index+1)*-1),!1;if(0===(33554432&bitField))return 0!==(16777216&bitField)?(this._reject(maybePromise._reason()),!0):(this._cancel(),!0);ret=maybePromise._value()}values[index]=ret}return++this._totalResolved>=length&&(null!==preservedValues?this._filter(values,preservedValues):this._resolve(values),!0)},MappingPromiseArray.prototype._drainQueue=function(){for(var queue=this._queue,limit=this._limit,values=this._values;queue.length>0&&this._inFlight1){debug.deprecated("calling Promise.try with more than 1 argument");var arg=arguments[1],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();return debug.checkForgottenReturns(value,promiseCreated,"Promise.try",ret),ret._resolveFromSyncValue(value),ret},Promise.prototype._resolveFromSyncValue=function(value){value===util.errorObj?this._rejectCallback(value.e,!1):this._resolveCallback(value,!0)}}},{"./util":36}],20:[function(_dereq_,module,exports){"use strict";function isUntypedError(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype}function wrapAsOperationalError(obj){var ret;if(isUntypedError(obj)){ret=new OperationalError(obj),ret.name=obj.name,ret.message=obj.message,ret.stack=obj.stack;for(var keys=es5.keys(obj),i=0;i1){var i,catchInstances=new Array(len-1),j=0;for(i=0;i0&&"function"!=typeof didFulfill&&"function"!=typeof didReject){var msg=".then() only accepts functions but was passed: "+util.classString(didFulfill);arguments.length>1&&(msg+=", "+util.classString(didReject)),this._warn(msg)}return this._then(didFulfill,didReject,void 0,void 0,void 0)},Promise.prototype.done=function(didFulfill,didReject){this._then(didFulfill,didReject,void 0,void 0,void 0)._setIsFinal()},Promise.prototype.spread=function(fn){return"function"!=typeof fn?apiRejection("expecting a function but got "+util.classString(fn)):this.all()._then(fn,void 0,void 0,APPLY,void 0)},Promise.prototype.toJSON=function(){var ret={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(ret.fulfillmentValue=this.value(),ret.isFulfilled=!0):this.isRejected()&&(ret.rejectionReason=this.reason(),ret.isRejected=!0),ret},Promise.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),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,result=tryCatch(fn)(nodebackForPromise(ret,multiArgs));return result===errorObj&&ret._rejectCallback(result.e,!0),ret._isFateSealed()||ret._setAsyncGuaranteed(),ret},Promise.all=function(promises){return new PromiseArray(promises).promise()},Promise.cast=function(obj){var ret=tryConvertToPromise(obj);return ret instanceof Promise||(ret=new Promise(INTERNAL),ret._captureStackTrace(),ret._setFulfilled(),ret._rejectionHandler0=obj),ret},Promise.resolve=Promise.fulfilled=Promise.cast,Promise.reject=Promise.rejected=function(reason){var ret=new Promise(INTERNAL);return ret._captureStackTrace(),ret._rejectCallback(reason,!0),ret},Promise.setScheduler=function(fn){if("function"!=typeof fn)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=void 0!==internalData,promise=haveInternalData?internalData:new Promise(INTERNAL),target=this._target(),bitField=target._bitField;haveInternalData||(promise._propagateFrom(this,3),promise._captureStackTrace(),void 0===receiver&&0!==(2097152&this._bitField)&&(receiver=0!==(50397184&bitField)?this._boundValue():target===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,promise));var domain=getDomain();if(0!==(50397184&bitField)){var handler,value,settler=target._settlePromiseCtx;0!==(33554432&bitField)?(value=target._rejectionHandler0,handler=didFulfill):0!==(16777216&bitField)?(value=target._fulfillmentHandler0,handler=didReject,target._unsetRejectionIsUnhandled()):(settler=target._settlePromiseLateCancellationObserver,value=new CancellationError("late cancellation observer"),target._attachExtraTrace(value),handler=didReject),async.invoke(settler,target,{handler:null===domain?handler:"function"==typeof handler&&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 65535&this._bitField},Promise.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},Promise.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},Promise.prototype._setLength=function(len){this._bitField=this._bitField&-65536|65535&len},Promise.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},Promise.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},Promise.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},Promise.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},Promise.prototype._isFinal=function(){return(4194304&this._bitField)>0},Promise.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},Promise.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},Promise.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},Promise.prototype._setAsyncGuaranteed=function(){async.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},Promise.prototype._receiverAt=function(index){var ret=0===index?this._receiver0:this[4*index-4+3];if(ret!==UNDEFINED_BINDING)return void 0===ret&&this._isBound()?this._boundValue():ret},Promise.prototype._promiseAt=function(index){return this[4*index-4+2]},Promise.prototype._fulfillmentHandlerAt=function(index){return this[4*index-4+0]},Promise.prototype._rejectionHandlerAt=function(index){return this[4*index-4+1]},Promise.prototype._boundValue=function(){},Promise.prototype._migrateCallback0=function(follower){var fulfill=(follower._bitField,follower._fulfillmentHandler0),reject=follower._rejectionHandler0,promise=follower._promise0,receiver=follower._receiverAt(0);void 0===receiver&&(receiver=UNDEFINED_BINDING),this._addCallbacks(fulfill,reject,promise,receiver,null)},Promise.prototype._migrateCallbackAt=function(follower,index){var fulfill=follower._fulfillmentHandlerAt(index),reject=follower._rejectionHandlerAt(index),promise=follower._promiseAt(index),receiver=follower._receiverAt(index);void 0===receiver&&(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>=65531&&(index=0,this._setLength(0)),0===index)this._promise0=promise,this._receiver0=receiver,"function"==typeof fulfill&&(this._fulfillmentHandler0=null===domain?fulfill:util.domainBind(domain,fulfill)),"function"==typeof reject&&(this._rejectionHandler0=null===domain?reject:util.domainBind(domain,reject));else{var base=4*index-4;this[base+2]=promise,this[base+3]=receiver,"function"==typeof fulfill&&(this[base+0]=null===domain?fulfill:util.domainBind(domain,fulfill)),"function"==typeof reject&&(this[base+1]=null===domain?reject:util.domainBind(domain,reject))}return this._setLength(index+1),index},Promise.prototype._proxy=function(proxyable,arg){this._addCallbacks(void 0,void 0,arg,proxyable,null)},Promise.prototype._resolveCallback=function(value,shouldBind){if(0===(117506048&this._bitField)){if(value===this)return this._rejectCallback(makeSelfResolutionError(),!1);var maybePromise=tryConvertToPromise(value,this);if(!(maybePromise instanceof Promise))return this._fulfill(value);shouldBind&&this._propagateFrom(maybePromise,2);var promise=maybePromise._target();if(promise===this)return void this._reject(makeSelfResolutionError());var bitField=promise._bitField;if(0===(50397184&bitField)){var len=this._length();len>0&&promise._migrateCallback0(this);for(var i=1;i>>16)){if(value===this){var err=makeSelfResolutionError();return this._attachExtraTrace(err),this._reject(err)}this._setFulfilled(),this._rejectionHandler0=value,(65535&bitField)>0&&(0!==(134217728&bitField)?this._settlePromises():async.settlePromises(this))}},Promise.prototype._reject=function(reason){var bitField=this._bitField;if(!((117506048&bitField)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=reason,this._isFinal())return async.fatalError(reason,util.isNode);(65535&bitField)>0?async.settlePromises(this):this._ensurePossibleRejectionHandled()}},Promise.prototype._fulfillPromises=function(len,value){for(var i=1;i0){if(0!==(16842752&bitField)){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;return 0!==(33554432&bitField)?this._rejectionHandler0:0!==(16777216&bitField)?this._fulfillmentHandler0:void 0},Promise.defer=Promise.pending=function(){return debug.deprecated("Promise.defer","new Promise"),{promise:new Promise(INTERNAL),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),fillTypes({a:1}),fillTypes({b:2}),fillTypes({c:3}),fillTypes(1),fillTypes(function(){}),fillTypes(void 0),fillTypes(!1),fillTypes(new Promise(INTERNAL)),debug.setBounds(Async.firstLineError,util.lastLineError),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){function toResolutionValue(val){switch(val){case-2:return[];case-3:return{}}}function PromiseArray(values){var promise=this._promise=new Promise(INTERNAL);values instanceof Promise&&promise._propagateFrom(values,3),promise._setOnCancel(this),this._values=values,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var util=_dereq_("./util");util.isArray;return 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;if(this._values=values,0===(50397184&bitField))return this._promise._setAsyncGuaranteed(),values._then(init,this._reject,void 0,this,resolveValueIfEmpty);if(0===(33554432&bitField))return 0!==(16777216&bitField)?this._reject(values._reason()):this._cancel();values=values._value()}if(values=util.asArray(values),null===values){var err=apiRejection("expecting an array or an iterable object but got "+util.classString(values)).reason();return void this._promise._rejectCallback(err,!1)}if(0===values.length)return void(resolveValueIfEmpty===-5?this._resolveEmptyArray():this._resolve(toResolutionValue(resolveValueIfEmpty)));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;for(var result=this._promise,isResolved=!1,bitField=null,i=0;i=this._length&&(this._resolve(this._values),!0)},PromiseArray.prototype._promiseCancelled=function(){return this._cancel(),!0},PromiseArray.prototype._promiseRejected=function(reason){return this._totalResolved++,this._reject(reason),!0},PromiseArray.prototype._resultCancelled=function(){if(!this._isResolved()){var values=this._values;if(this._cancel(),values instanceof Promise)values.cancel();else for(var i=0;i=this._length){var val;if(this._isMap)val=entriesToMap(this._values);else{val={};for(var keyOffset=this.length(),i=0,len=this.length();i>1},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=this._length&&(this._resolve(this._values),!0)},SettledPromiseArray.prototype._promiseFulfilled=function(value,index){var ret=new PromiseInspection;return ret._bitField=33554432,ret._settledValueField=value,this._promiseResolved(index,ret)},SettledPromiseArray.prototype._promiseRejected=function(reason,index){var ret=new PromiseInspection;return ret._bitField=16777216,ret._settledValueField=reason,this._promiseResolved(index,ret)},Promise.settle=function(promises){return debug.deprecated(".settle()",".reflect()"),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){function SomePromiseArray(values){this.constructor$(values),this._howMany=0,this._unwrap=!1,this._initialized=!1}function some(promises,howMany){if((0|howMany)!==howMany||howMany<0)return apiRejection("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var ret=new SomePromiseArray(promises),promise=ret.promise();return ret.setHowMany(howMany),ret.init(),promise}var util=_dereq_("./util"),RangeError=_dereq_("./errors").RangeError,AggregateError=_dereq_("./errors").AggregateError,isArray=util.isArray,CANCELLATION={};util.inherits(SomePromiseArray,PromiseArray),SomePromiseArray.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var isArrayResolved=isArray(this._values);!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},SomePromiseArray.prototype.init=function(){this._initialized=!0,this._init()},SomePromiseArray.prototype.setUnwrap=function(){this._unwrap=!0},SomePromiseArray.prototype.howMany=function(){return this._howMany},SomePromiseArray.prototype.setHowMany=function(count){this._howMany=count},SomePromiseArray.prototype._promiseFulfilled=function(value){return this._addFulfilled(value),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},SomePromiseArray.prototype._promiseRejected=function(reason){return this._addRejected(reason),this._checkOutcome()},SomePromiseArray.prototype._promiseCancelled=function(){return this._values instanceof Promise||null==this._values?this._cancel():(this._addRejected(CANCELLATION),this._checkOutcome())},SomePromiseArray.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var e=new AggregateError,i=this.length();i0?this._reject(e):this._cancel(),!0}return!1},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){return new RangeError("Input array must contain at least "+this._howMany+" items but contains only "+count+" items")},SomePromiseArray.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},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){void 0!==promise?(promise=promise._target(),this._bitField=promise._bitField,this._settledValueField=promise._isFateSealed()?promise._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}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\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},reason=PromiseInspection.prototype.error=PromiseInspection.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},isFulfilled=PromiseInspection.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},isRejected=PromiseInspection.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},isPending=PromiseInspection.prototype.isPending=function(){return 0===(50397184&this._bitField)},isResolved=PromiseInspection.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};PromiseInspection.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},Promise.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},Promise.prototype._isCancelled=function(){return this._target().__isCancelled()},Promise.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},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();return target._unsetRejectionIsUnhandled(),reason.call(target)},Promise.prototype._value=function(){return this._settledValue()},Promise.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},Promise.PromiseInspection=PromiseInspection}},{}],33:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL){function tryConvertToPromise(obj,context){if(isObject(obj)){if(obj instanceof Promise)return obj;var then=getThen(obj);if(then===errorObj){context&&context._pushContext();var ret=Promise.reject(then.e);return context&&context._popContext(),ret}if("function"==typeof then){if(isAnyBluebirdPromise(obj)){var ret=new Promise(INTERNAL);return obj._then(ret._fulfill,ret._reject,void 0,ret,null),ret}return doThenable(obj,then,context)}}return obj}function doGetThen(obj){return obj.then}function getThen(obj){try{return doGetThen(obj)}catch(e){return errorObj.e=e,errorObj}}function isAnyBluebirdPromise(obj){try{return hasProp.call(obj,"_promise0")}catch(e){return!1}}function doThenable(x,then,context){function resolve(value){promise&&(promise._resolveCallback(value),promise=null)}function reject(reason){promise&&(promise._rejectCallback(reason,synchronous,!0),promise=null)}var promise=new Promise(INTERNAL),ret=promise;context&&context._pushContext(),promise._captureStackTrace(),context&&context._popContext();var synchronous=!0,result=util.tryCatch(then).call(x,resolve,reject);return synchronous=!1,promise&&result===errorObj&&(promise._rejectCallback(result.e,!0,!0),promise=null),ret}var util=_dereq_("./util"),errorObj=util.errorObj,isObject=util.isObject,hasProp={}.hasOwnProperty;return tryConvertToPromise}},{"./util":36}],34:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,INTERNAL,debug){function HandleWrapper(handle){this.handle=handle}function successClear(value){return clearTimeout(this.handle),value}function failureClear(reason){throw clearTimeout(this.handle),reason}var util=_dereq_("./util"),TimeoutError=Promise.TimeoutError;HandleWrapper.prototype._resultCancelled=function(){clearTimeout(this.handle)};var afterValue=function(value){return delay(+this).thenReturn(value)},delay=Promise.delay=function(ms,value){var ret,handle;return void 0!==value?(ret=Promise.resolve(value)._then(afterValue,null,null,ms,void 0),debug.cancellation()&&value instanceof Promise&&ret._setOnCancel(value)):(ret=new Promise(INTERNAL),handle=setTimeout(function(){ret._fulfill()},+ms),debug.cancellation()&&ret._setOnCancel(new HandleWrapper(handle)),ret._captureStackTrace()),ret._setAsyncGuaranteed(),ret};Promise.prototype.delay=function(ms){return delay(ms,this)};var afterTimeout=function(promise,message,parent){var err;err="string"!=typeof message?message instanceof Error?message:new TimeoutError("operation timed out"):new TimeoutError(message),util.markAsOriginatingFromRejection(err),promise._attachExtraTrace(err),promise._reject(err),null!=parent&&parent.cancel()};Promise.prototype.timeout=function(ms,message){ms=+ms;var ret,parent,handleWrapper=new HandleWrapper(setTimeout(function(){ret.isPending()&&afterTimeout(ret,message,parent)},ms));return debug.cancellation()?(parent=this.then(),ret=parent._then(successClear,failureClear,void 0,handleWrapper,void 0),ret._setOnCancel(handleWrapper)):ret=this._then(successClear,failureClear,void 0,handleWrapper,void 0),ret}}},{"./util":36}],35:[function(_dereq_,module,exports){"use strict";module.exports=function(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug){function thrower(e){setTimeout(function(){throw e},0)}function castPreservingDisposable(thenable){var maybePromise=tryConvertToPromise(thenable);return maybePromise!==thenable&&"function"==typeof thenable._isDisposable&&"function"==typeof thenable._getDisposer&&thenable._isDisposable()&&maybePromise._setDisposable(thenable._getDisposer()),maybePromise}function dispose(resources,inspection){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()}var i=0,len=resources.length,ret=new Promise(INTERNAL);return iterator(),ret}function Disposer(data,promise,context){this._data=data,this._promise=promise,this._context=context}function FunctionDisposer(fn,promise,context){this.constructor$(fn,promise,context)}function maybeUnwrapDisposer(value){return Disposer.isDisposer(value)?(this.resources[this.index]._setDisposable(value),value.promise()):value}function ResourceList(length){this.length=length,this.promise=null,this[length-1]=null}var util=_dereq_("./util"),TypeError=_dereq_("./errors").TypeError,inherits=_dereq_("./util").inherits,errorObj=util.errorObj,tryCatch=util.tryCatch,NULL={};Disposer.prototype.data=function(){return this._data},Disposer.prototype.promise=function(){return this._promise},Disposer.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():NULL},Disposer.prototype.tryDispose=function(inspection){var resource=this.resource(),context=this._context;void 0!==context&&context._pushContext();var ret=resource!==NULL?this.doDispose(resource,inspection):null;return void 0!==context&&context._popContext(),this._promise._unsetDisposable(),this._data=null,ret},Disposer.isDisposer=function(d){return null!=d&&"function"==typeof d.resource&&"function"==typeof d.tryDispose},inherits(FunctionDisposer,Disposer),FunctionDisposer.prototype.doDispose=function(resource,inspection){return this.data().call(resource,resource,inspection)},ResourceList.prototype._resultCancelled=function(){for(var len=this.length,i=0;i0},Promise.prototype._getDisposer=function(){return this._disposer},Promise.prototype._unsetDisposable=function(){this._bitField=this._bitField&-131073,this._disposer=void 0},Promise.prototype.disposer=function(fn){if("function"==typeof fn)return new FunctionDisposer(fn,this,createContext());throw new TypeError}}},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){"use strict";function tryCatcher(){try{var target=tryCatchTarget;return tryCatchTarget=null,target.apply(this,arguments)}catch(e){return errorObj.e=e,errorObj}}function tryCatch(fn){return tryCatchTarget=fn,tryCatcher}function isPrimitive(val){return null==val||val===!0||val===!1||"string"==typeof val||"number"==typeof val}function isObject(value){return"function"==typeof value||"object"==typeof value&&null!==value}function maybeWrapAsError(maybeError){return isPrimitive(maybeError)?new Error(safeToString(maybeError)):maybeError}function withAppended(target,appendee){var i,len=target.length,ret=new Array(len+1);for(i=0;i1,hasMethodsOtherThanConstructor=keys.length>0&&!(1===keys.length&&"constructor"===keys[0]),hasThisAssignmentAndStaticMethods=thisAssignmentPattern.test(fn+"")&&es5.names(fn).length>0;if(hasMethods||hasMethodsOtherThanConstructor||hasThisAssignmentAndStaticMethods)return!0}return!1}catch(e){return!1}}function toFastProperties(obj){function FakeConstructor(){}FakeConstructor.prototype=obj;for(var l=8;l--;)new FakeConstructor;return obj}function isIdentifier(str){return rident.test(str)}function filledRange(count,prefix,suffix){for(var ret=new Array(count),i=0;i10||version[0]>0}(),ret.isNode&&ret.toFastProperties(process);try{throw new Error}catch(e){ret.lastLineError=e}module.exports=ret},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(exports,__webpack_require__(25),__webpack_require__(5),__webpack_require__(53).setImmediate)},function(module,exports,__webpack_require__){var core=__webpack_require__(2),$JSON=core.JSON||(core.JSON={stringify:JSON.stringify});module.exports=function(it){return $JSON.stringify.apply($JSON,arguments)}},function(module,exports,__webpack_require__){__webpack_require__(142),module.exports=__webpack_require__(2).Object.assign},function(module,exports,__webpack_require__){__webpack_require__(143);var $Object=__webpack_require__(2).Object;module.exports=function(P,D){return $Object.create(P,D)}},function(module,exports,__webpack_require__){__webpack_require__(144);var $Object=__webpack_require__(2).Object;module.exports=function(it,key,desc){return $Object.defineProperty(it,key,desc)}},function(module,exports,__webpack_require__){__webpack_require__(145);var $Object=__webpack_require__(2).Object;module.exports=function(it){return $Object.getOwnPropertyNames(it)}},function(module,exports,__webpack_require__){__webpack_require__(146),module.exports=__webpack_require__(2).Object.getPrototypeOf},function(module,exports,__webpack_require__){__webpack_require__(147),module.exports=__webpack_require__(2).Object.keys},function(module,exports,__webpack_require__){__webpack_require__(148),module.exports=__webpack_require__(2).Object.setPrototypeOf},function(module,exports,__webpack_require__){__webpack_require__(73),__webpack_require__(74),__webpack_require__(75),__webpack_require__(149),module.exports=__webpack_require__(2).Promise},function(module,exports,__webpack_require__){__webpack_require__(150),__webpack_require__(73),__webpack_require__(151),__webpack_require__(152),module.exports=__webpack_require__(2).Symbol},function(module,exports,__webpack_require__){__webpack_require__(74),__webpack_require__(75),module.exports=__webpack_require__(49).f("iterator")},function(module,exports){module.exports=function(){}},function(module,exports){module.exports=function(it,Constructor,name,forbiddenField){if(!(it instanceof Constructor)||void 0!==forbiddenField&&forbiddenField in it)throw TypeError(name+": incorrect invocation!");return it}},function(module,exports,__webpack_require__){var toIObject=__webpack_require__(13),toLength=__webpack_require__(72),toIndex=__webpack_require__(139);module.exports=function(IS_INCLUDES){return function($this,el,fromIndex){var value,O=toIObject($this),length=toLength(O.length),index=toIndex(fromIndex,length);if(IS_INCLUDES&&el!=el){for(;length>index;)if(value=O[index++],value!=value)return!0}else for(;length>index;index++)if((IS_INCLUDES||index in O)&&O[index]===el)return IS_INCLUDES||index||0;return!IS_INCLUDES&&-1}}},function(module,exports,__webpack_require__){var getKeys=__webpack_require__(21),gOPS=__webpack_require__(42),pIE=__webpack_require__(31);module.exports=function(it){var result=getKeys(it),getSymbols=gOPS.f;if(getSymbols)for(var key,symbols=getSymbols(it),isEnum=pIE.f,i=0;symbols.length>i;)isEnum.call(it,key=symbols[i++])&&result.push(key);return result}},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={},exports=module.exports=function(iterable,entries,fn,that,ITERATOR){var length,step,iterator,result,iterFn=ITERATOR?function(){return iterable}:getIterFn(iterable),f=ctx(fn,that,entries?2:1),index=0;if("function"!=typeof iterFn)throw TypeError(iterable+" is not iterable!");if(isArrayIter(iterFn)){for(length=toLength(iterable.length);length>index;index++)if(result=entries?f(anObject(step=iterable[index])[0],step[1]):f(iterable[index]),result===BREAK||result===RETURN)return result}else for(iterator=iterFn.call(iterable);!(step=iterator.next()).done;)if(result=call(iterator,f,step.value,entries),result===BREAK||result===RETURN)return result};exports.BREAK=BREAK,exports.RETURN=RETURN},function(module,exports){module.exports=function(fn,args,that){var un=void 0===that;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)}},function(module,exports,__webpack_require__){var Iterators=__webpack_require__(24),ITERATOR=__webpack_require__(3)("iterator"),ArrayProto=Array.prototype;module.exports=function(it){return void 0!==it&&(Iterators.Array===it||ArrayProto[ITERATOR]===it)}},function(module,exports,__webpack_require__){var cof=__webpack_require__(22);module.exports=Array.isArray||function(arg){return"Array"==cof(arg)}},function(module,exports,__webpack_require__){var anObject=__webpack_require__(7);module.exports=function(iterator,fn,value,entries){try{return entries?fn(anObject(value)[0],value[1]):fn(value)}catch(e){var ret=iterator.return;throw void 0!==ret&&anObject(ret.call(iterator)),e}}},function(module,exports,__webpack_require__){"use strict";var create=__webpack_require__(41),descriptor=__webpack_require__(32),setToStringTag=__webpack_require__(33),IteratorPrototype={};__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")}},function(module,exports,__webpack_require__){var ITERATOR=__webpack_require__(3)("iterator"),SAFE_CLOSING=!1;try{var riter=[7][ITERATOR]();riter.return=function(){SAFE_CLOSING=!0},Array.from(riter,function(){throw 2})}catch(e){}module.exports=function(exec,skipClosing){if(!skipClosing&&!SAFE_CLOSING)return!1;var safe=!1;try{var arr=[7],iter=arr[ITERATOR]();iter.next=function(){return{done:safe=!0}},arr[ITERATOR]=function(){return iter},exec(arr)}catch(e){}return safe}},function(module,exports){module.exports=function(done,value){return{value:value,done:!!done}}},function(module,exports,__webpack_require__){var getKeys=__webpack_require__(21),toIObject=__webpack_require__(13);module.exports=function(object,el){for(var key,O=toIObject(object),keys=getKeys(O),length=keys.length,index=0;length>index;)if(O[key=keys[index++]]===el)return key}},function(module,exports,__webpack_require__){var META=__webpack_require__(35)("meta"),isObject=__webpack_require__(20),has=__webpack_require__(11),setDesc=__webpack_require__(10).f,id=0,isExtensible=Object.isExtensible||function(){return!0},FREEZE=!__webpack_require__(19)(function(){return isExtensible(Object.preventExtensions({}))}),setMeta=function(it){setDesc(it,META,{value:{i:"O"+ ++id,w:{}}})},fastKey=function(it,create){if(!isObject(it))return"symbol"==typeof it?it:("string"==typeof it?"S":"P")+it;if(!has(it,META)){if(!isExtensible(it))return"F";if(!create)return"E";setMeta(it)}return it[META].i},getWeak=function(it,create){if(!has(it,META)){if(!isExtensible(it))return!0;if(!create)return!1;setMeta(it)}return it[META].w},onFreeze=function(it){return FREEZE&&meta.NEED&&isExtensible(it)&&!has(it,META)&&setMeta(it),it},meta=module.exports={KEY:META,NEED:!1,fastKey:fastKey,getWeak:getWeak,onFreeze:onFreeze}},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="process"==__webpack_require__(22)(process);module.exports=function(){var head,last,notify,flush=function(){var parent,fn;for(isNode&&(parent=process.domain)&&parent.exit();head;){fn=head.fn,head=head.next;try{fn()}catch(e){throw head?notify():last=void 0,e}}last=void 0,parent&&parent.enter()};if(isNode)notify=function(){process.nextTick(flush)};else if(Observer){var toggle=!0,node=document.createTextNode("");new Observer(flush).observe(node,{characterData:!0}),notify=function(){node.data=toggle=!toggle}}else if(Promise&&Promise.resolve){var promise=Promise.resolve();notify=function(){promise.then(flush)}}else notify=function(){macrotask.call(global,flush)};return function(fn){var task={fn:fn,next:void 0};last&&(last.next=task),head||(head=task,notify()),last=task}}},function(module,exports,__webpack_require__){"use strict";var getKeys=__webpack_require__(21),gOPS=__webpack_require__(42),pIE=__webpack_require__(31),toObject=__webpack_require__(34),IObject=__webpack_require__(63),$assign=Object.assign;module.exports=!$assign||__webpack_require__(19)(function(){var A={},B={},S=Symbol(),K="abcdefghijklmnopqrst";return A[S]=7,K.split("").forEach(function(k){B[k]=k}),7!=$assign({},A)[S]||Object.keys($assign({},B)).join("")!=K})?function(target,source){for(var T=toObject(target),aLen=arguments.length,index=1,getSymbols=gOPS.f,isEnum=pIE.f;aLen>index;)for(var key,S=IObject(arguments[index++]),keys=getSymbols?getKeys(S).concat(getSymbols(S)):getKeys(S),length=keys.length,j=0;length>j;)isEnum.call(S,key=keys[j++])&&(T[key]=S[key]);return T}:$assign},function(module,exports,__webpack_require__){var dP=__webpack_require__(10),anObject=__webpack_require__(7),getKeys=__webpack_require__(21);module.exports=__webpack_require__(8)?Object.defineProperties:function(O,Properties){anObject(O);for(var P,keys=getKeys(Properties),length=keys.length,i=0;length>i;)dP.f(O,P=keys[i++],Properties[P]);return O}},function(module,exports,__webpack_require__){var hide=__webpack_require__(12);module.exports=function(target,src,safe){for(var key in src)safe&&target[key]?target[key]=src[key]:hide(target,key,src[key]);return target}},function(module,exports,__webpack_require__){var isObject=__webpack_require__(20),anObject=__webpack_require__(7),check=function(O,proto){if(anObject(O),!isObject(proto)&&null!==proto)throw TypeError(proto+": can't set as prototype!")};module.exports={set:Object.setPrototypeOf||("__proto__"in{}?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=!0}return function(O,proto){return check(O,proto),buggy?O.__proto__=proto:set(O,proto),O}}({},!1):void 0),check:check}},function(module,exports,__webpack_require__){"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="function"==typeof core[KEY]?core[KEY]:global[KEY];DESCRIPTORS&&C&&!C[SPECIES]&&dP.f(C,SPECIES,{configurable:!0,get:function(){return this}})}},function(module,exports,__webpack_require__){var anObject=__webpack_require__(7),aFunction=__webpack_require__(37),SPECIES=__webpack_require__(3)("species");module.exports=function(O,D){var S,C=anObject(O).constructor;return void 0===C||void 0==(S=anObject(C)[SPECIES])?D:aFunction(S)}},function(module,exports,__webpack_require__){var toInteger=__webpack_require__(46),defined=__webpack_require__(38);module.exports=function(TO_STRING){return function(that,pos){var a,b,s=String(defined(that)),i=toInteger(pos),l=s.length;return i<0||i>=l?TO_STRING?"":void 0:(a=s.charCodeAt(i),a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?TO_STRING?s.charAt(i):a:TO_STRING?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536)}}},function(module,exports,__webpack_require__){var toInteger=__webpack_require__(46),max=Math.max,min=Math.min;module.exports=function(index,length){return index=toInteger(index),index<0?max(index+length,0):min(index,length)}},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(void 0!=it)return it[ITERATOR]||it["@@iterator"]||Iterators[classof(it)]}},function(module,exports,__webpack_require__){"use strict";var addToUnscopables=__webpack_require__(117),step=__webpack_require__(128),Iterators=__webpack_require__(24),toIObject=__webpack_require__(13);module.exports=__webpack_require__(64)(Array,"Array",function(iterated,kind){this._t=toIObject(iterated),this._i=0,this._k=kind},function(){var O=this._t,kind=this._k,index=this._i++;return!O||index>=O.length?(this._t=void 0,step(1)):"keys"==kind?step(0,index):"values"==kind?step(0,O[index]):step(0,[index,O[index]])},"values"),Iterators.Arguments=Iterators.Array,addToUnscopables("keys"),addToUnscopables("values"),addToUnscopables("entries")},function(module,exports,__webpack_require__){var $export=__webpack_require__(9);$export($export.S+$export.F,"Object",{assign:__webpack_require__(132)})},function(module,exports,__webpack_require__){var $export=__webpack_require__(9);$export($export.S,"Object",{create:__webpack_require__(41)})},function(module,exports,__webpack_require__){var $export=__webpack_require__(9);$export($export.S+$export.F*!__webpack_require__(8),"Object",{defineProperty:__webpack_require__(10).f})},function(module,exports,__webpack_require__){__webpack_require__(43)("getOwnPropertyNames",function(){return __webpack_require__(66).f})},function(module,exports,__webpack_require__){var toObject=__webpack_require__(34),$getPrototypeOf=__webpack_require__(68);__webpack_require__(43)("getPrototypeOf",function(){return function(it){return $getPrototypeOf(toObject(it))}})},function(module,exports,__webpack_require__){var toObject=__webpack_require__(34),$keys=__webpack_require__(21);__webpack_require__(43)("keys",function(){return function(it){return $keys(toObject(it))}})},function(module,exports,__webpack_require__){var $export=__webpack_require__(9);$export($export.S,"Object",{setPrototypeOf:__webpack_require__(135).set})},function(module,exports,__webpack_require__){"use strict";var Internal,GenericPromiseCapability,Wrapper,LIBRARY=__webpack_require__(30),global=__webpack_require__(4),ctx=__webpack_require__(23),classof=__webpack_require__(60),$export=__webpack_require__(9),isObject=__webpack_require__(20),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="process"==classof(process),empty=function(){},USE_NATIVE=!!function(){try{var promise=$Promise.resolve(1),FakePromise=(promise.constructor={})[__webpack_require__(3)("species")]=function(exec){exec(empty,empty)};return(isNode||"function"==typeof PromiseRejectionEvent)&&promise.then(empty)instanceof FakePromise}catch(e){}}(),sameConstructor=function(a,b){return a===b||a===$Promise&&b===Wrapper},isThenable=function(it){var then;return!(!isObject(it)||"function"!=typeof(then=it.then))&&then},newPromiseCapability=function(C){return sameConstructor($Promise,C)?new PromiseCapability(C):new GenericPromiseCapability(C)},PromiseCapability=GenericPromiseCapability=function(C){var resolve,reject;this.promise=new C(function($$resolve,$$reject){if(void 0!==resolve||void 0!==reject)throw TypeError("Bad Promise constructor");resolve=$$resolve,reject=$$reject}),this.resolve=aFunction(resolve),this.reject=aFunction(reject)},perform=function(exec){try{exec()}catch(e){return{error:e}}},notify=function(promise,isReject){if(!promise._n){promise._n=!0;var chain=promise._c;microtask(function(){for(var value=promise._v,ok=1==promise._s,i=0,run=function(reaction){var result,then,handler=ok?reaction.ok:reaction.fail,resolve=reaction.resolve,reject=reaction.reject,domain=reaction.domain;try{handler?(ok||(2==promise._h&&onHandleUnhandled(promise),promise._h=1),handler===!0?result=value:(domain&&domain.enter(),result=handler(value),domain&&domain.exit()),result===reaction.promise?reject(TypeError("Promise-chain cycle")):(then=isThenable(result))?then.call(result,resolve,reject):resolve(result)):reject(value)}catch(e){reject(e)}};chain.length>i;)run(chain[i++]);promise._c=[],promise._n=!1,isReject&&!promise._h&&onUnhandled(promise)})}},onUnhandled=function(promise){task.call(global,function(){var abrupt,handler,console,value=promise._v;if(isUnhandled(promise)&&(abrupt=perform(function(){isNode?process.emit("unhandledRejection",value,promise):(handler=global.onunhandledrejection)?handler({promise:promise,reason:value}):(console=global.console)&&console.error&&console.error("Unhandled promise rejection",value)}),promise._h=isNode||isUnhandled(promise)?2:1),promise._a=void 0,abrupt)throw abrupt.error})},isUnhandled=function(promise){if(1==promise._h)return!1;for(var reaction,chain=promise._a||promise._c,i=0;chain.length>i;)if(reaction=chain[i++],reaction.fail||!isUnhandled(reaction.promise))return!1;return!0},onHandleUnhandled=function(promise){task.call(global,function(){var handler;isNode?process.emit("rejectionHandled",promise):(handler=global.onrejectionhandled)&&handler({promise:promise,reason:promise._v})})},$reject=function(value){var promise=this;promise._d||(promise._d=!0,promise=promise._w||promise,promise._v=value,promise._s=2,promise._a||(promise._a=promise._c.slice()),notify(promise,!0))},$resolve=function(value){var then,promise=this;if(!promise._d){promise._d=!0,promise=promise._w||promise;try{if(promise===value)throw TypeError("Promise can't be resolved itself");(then=isThenable(value))?microtask(function(){var wrapper={_w:promise,_d:!1};try{then.call(value,ctx($resolve,wrapper,1),ctx($reject,wrapper,1))}catch(e){$reject.call(wrapper,e)}}):(promise._v=value,promise._s=1,notify(promise,!1))}catch(e){$reject.call({_w:promise,_d:!1},e)}}};USE_NATIVE||($Promise=function(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(executor){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},Internal.prototype=__webpack_require__(134)($Promise.prototype,{then:function(onFulfilled,onRejected){var reaction=newPromiseCapability(speciesConstructor(this,$Promise));return reaction.ok="function"!=typeof onFulfilled||onFulfilled,reaction.fail="function"==typeof onRejected&&onRejected,reaction.domain=isNode?process.domain:void 0,this._c.push(reaction),this._a&&this._a.push(reaction),this._s&¬ify(this,!1),reaction.promise},catch:function(onRejected){return this.then(void 0,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],$export($export.S+$export.F*!USE_NATIVE,PROMISE,{reject:function(r){var capability=newPromiseCapability(this);return(0,capability.reject)(r),capability.promise}}),$export($export.S+$export.F*(LIBRARY||!USE_NATIVE),PROMISE,{resolve:function(x){if(x instanceof $Promise&&sameConstructor(x.constructor,this))return x;var capability=newPromiseCapability(this);return(0,capability.resolve)(x),capability.promise}}),$export($export.S+$export.F*!(USE_NATIVE&&__webpack_require__(127)(function(iter){$Promise.all(iter).catch(empty)})),PROMISE,{all:function(iterable){var C=this,capability=newPromiseCapability(C),resolve=capability.resolve,reject=capability.reject,abrupt=perform(function(){var values=[],index=0,remaining=1;forOf(iterable,!1,function(promise){var $index=index++,alreadyCalled=!1;values.push(void 0),remaining++,C.resolve(promise).then(function(value){alreadyCalled||(alreadyCalled=!0,values[$index]=value,--remaining||resolve(values))},reject)}),--remaining||resolve(values)});return abrupt&&reject(abrupt.error),capability.promise},race:function(iterable){var C=this,capability=newPromiseCapability(C),reject=capability.reject,abrupt=perform(function(){forOf(iterable,!1,function(promise){C.resolve(promise).then(capability.resolve,reject)})});return abrupt&&reject(abrupt.error),capability.promise}})},function(module,exports,__webpack_require__){"use strict";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__(19),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__(21),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="function"==typeof $Symbol,QObject=global.QObject,setter=!QObject||!QObject[PROTOTYPE]||!QObject[PROTOTYPE].findChild,setSymbolDesc=DESCRIPTORS&&$fails(function(){return 7!=_create(dP({},"a",{get:function(){return dP(this,"a",{value:7}).a}})).a})?function(it,key,D){var protoDesc=gOPD(ObjectProto,key);protoDesc&&delete ObjectProto[key],dP(it,key,D),protoDesc&&it!==ObjectProto&&dP(ObjectProto,key,protoDesc)}:dP,wrap=function(tag){var sym=AllSymbols[tag]=_create($Symbol[PROTOTYPE]);return sym._k=tag,sym},isSymbol=USE_NATIVE&&"symbol"==typeof $Symbol.iterator?function(it){return"symbol"==typeof it}:function(it){return it instanceof $Symbol},$defineProperty=function(it,key,D){return it===ObjectProto&&$defineProperty(OPSymbols,key,D),anObject(it),key=toPrimitive(key,!0),anObject(D),has(AllSymbols,key)?(D.enumerable?(has(it,HIDDEN)&&it[HIDDEN][key]&&(it[HIDDEN][key]=!1),D=_create(D,{enumerable:createDesc(0,!1)})):(has(it,HIDDEN)||dP(it,HIDDEN,createDesc(1,{})),it[HIDDEN][key]=!0),setSymbolDesc(it,key,D)):dP(it,key,D)},$defineProperties=function(it,P){anObject(it);for(var key,keys=enumKeys(P=toIObject(P)),i=0,l=keys.length;l>i;)$defineProperty(it,key=keys[i++],P[key]);return it},$create=function(it,P){return void 0===P?_create(it):$defineProperties(_create(it),P)},$propertyIsEnumerable=function(key){var E=isEnum.call(this,key=toPrimitive(key,!0));return!(this===ObjectProto&&has(AllSymbols,key)&&!has(OPSymbols,key))&&(!(E||!has(this,key)||!has(AllSymbols,key)||has(this,HIDDEN)&&this[HIDDEN][key])||E)},$getOwnPropertyDescriptor=function(it,key){if(it=toIObject(it),key=toPrimitive(key,!0),it!==ObjectProto||!has(AllSymbols,key)||has(OPSymbols,key)){var D=gOPD(it,key);return!D||!has(AllSymbols,key)||has(it,HIDDEN)&&it[HIDDEN][key]||(D.enumerable=!0),D}},$getOwnPropertyNames=function(it){for(var key,names=gOPN(toIObject(it)),result=[],i=0;names.length>i;)has(AllSymbols,key=names[i++])||key==HIDDEN||key==META||result.push(key);return result},$getOwnPropertySymbols=function(it){for(var key,IS_OP=it===ObjectProto,names=gOPN(IS_OP?OPSymbols:toIObject(it)),result=[],i=0;names.length>i;)!has(AllSymbols,key=names[i++])||IS_OP&&!has(ObjectProto,key)||result.push(AllSymbols[key]);return result};USE_NATIVE||($Symbol=function(){if(this instanceof $Symbol)throw TypeError("Symbol is not a constructor!");var tag=uid(arguments.length>0?arguments[0]:void 0),$set=function(value){this===ObjectProto&&$set.call(OPSymbols,value),has(this,HIDDEN)&&has(this[HIDDEN],tag)&&(this[HIDDEN][tag]=!1),setSymbolDesc(this,tag,createDesc(1,value))};return DESCRIPTORS&&setter&&setSymbolDesc(ObjectProto,tag,{configurable:!0,set:$set}),wrap(tag)},redefine($Symbol[PROTOTYPE],"toString",function(){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,DESCRIPTORS&&!__webpack_require__(30)&&redefine(ObjectProto,"propertyIsEnumerable",$propertyIsEnumerable,!0),wksExt.f=function(name){return wrap(wks(name))}),$export($export.G+$export.W+$export.F*!USE_NATIVE,{Symbol:$Symbol});for(var symbols="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",{for:function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=$Symbol(key)},keyFor:function(key){if(isSymbol(key))return keyOf(SymbolRegistry,key);throw TypeError(key+" is not a symbol!")},useSetter:function(){setter=!0},useSimple:function(){setter=!1}}),$export($export.S+$export.F*!USE_NATIVE,"Object",{create:$create,defineProperty:$defineProperty,defineProperties:$defineProperties,getOwnPropertyDescriptor:$getOwnPropertyDescriptor,getOwnPropertyNames:$getOwnPropertyNames,getOwnPropertySymbols:$getOwnPropertySymbols}),$JSON&&$export($export.S+$export.F*(!USE_NATIVE||$fails(function(){var S=$Symbol();return"[null]"!=_stringify([S])||"{}"!=_stringify({a:S})||"{}"!=_stringify(Object(S))})),"JSON",{stringify:function(it){if(void 0!==it&&!isSymbol(it)){for(var replacer,$replacer,args=[it],i=1;arguments.length>i;)args.push(arguments[i++]);return replacer=args[1],"function"==typeof replacer&&($replacer=replacer),!$replacer&&isArray(replacer)||(replacer=function(key,value){if($replacer&&(value=$replacer.call(this,key,value)),!isSymbol(value))return value}),args[1]=replacer,_stringify.apply($JSON,args)}}}),$Symbol[PROTOTYPE][TO_PRIMITIVE]||__webpack_require__(12)($Symbol[PROTOTYPE],TO_PRIMITIVE,$Symbol[PROTOTYPE].valueOf),setToStringTag($Symbol,"Symbol"),setToStringTag(Math,"Math",!0),setToStringTag(global.JSON,"JSON",!0)},function(module,exports,__webpack_require__){__webpack_require__(48)("asyncIterator")},function(module,exports,__webpack_require__){__webpack_require__(48)("observable")},function(module,exports,__webpack_require__){(function(global,setImmediate){!function(global,factory){module.exports=factory()}(this,function(){"use strict";function extend(obj,extension){return"object"!=typeof extension?obj:(keys(extension).forEach(function(key){obj[key]=extension[key]}),obj)}function hasOwn(obj,prop){return _hasOwn.call(obj,prop)}function props(proto,extension){"function"==typeof extension&&(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")&&"function"==typeof functionOrGetSet.get?{get:functionOrGetSet.get,set:functionOrGetSet.set,configurable:!0}:{value:functionOrGetSet,configurable:!0,writable:!0},options))}function derive(Child){return{from:function(Parent){return Child.prototype=Object.create(Parent.prototype),setProp(Child.prototype,"constructor",Child),{extend:props.bind(null,Child.prototype)}}}}function getPropertyDescriptor(obj,prop){var proto,pd=getOwnPropertyDescriptor(obj,prop);return pd||(proto=getProto(obj))&&getPropertyDescriptor(proto,prop)}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,1e3);clearTimeout(to)}function assert(b){if(!b)throw new Error("Assertion Failed")}function asap(fn){_global.setImmediate?setImmediate(fn):setTimeout(fn,0)}function arrayToObject(array,extractor){return array.reduce(function(result,item,i){var nameAndValue=extractor(item,i);return nameAndValue&&(result[nameAndValue[0]]=nameAndValue[1]),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){if(hasOwn(obj,keyPath))return obj[keyPath];if(!keyPath)return obj;if("string"!=typeof keyPath){for(var rv=[],i=0,l=keyPath.length;i0;)for(callbacks=microtickQueue,microtickQueue=[],l=callbacks.length,i=0;i0);isOutsideMicroTick=!0,needsNewPhysicalTick=!0}function finalizePhysicalTick(){var unhandledErrs=unhandledErrors;unhandledErrors=[],unhandledErrs.forEach(function(p){p._PSD.onunhandled.call(null,p._value,p)});for(var finalizers=tickFinalizers.slice(0),i=finalizers.length;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(){0===--numScheduledCalls&&finalizePhysicalTick()},[])}function addPossiblyUnhandledError(promise){unhandledErrors.some(function(p){return p._value===promise._value})||unhandledErrors.push(promise)}function markErrorAsHandled(promise){for(var i=unhandledErrors.length;i;)if(unhandledErrors[--i]._value===promise._value)return void unhandledErrors.splice(i,1)}function defaultErrorHandler(e){console.warn("Unhandled rejection: "+(e.stack||e))}function PromiseReject(reason){return new Promise(INTERNAL,!1,reason)}function wrap(fn,errorCatcher){var psd=PSD;return function(){var wasRootExec=beginMicroTickScope(),outerScope=PSD;try{return outerScope!==psd&&(PSD=psd),fn.apply(this,arguments)}catch(e){errorCatcher&&errorCatcher(e)}finally{outerScope!==psd&&(PSD=outerScope),wasRootExec&&endMicroTickScope()}}}function newScope(fn,a1,a2,a3){var parent=PSD,psd=Object.create(parent);psd.parent=parent,psd.ref=0,psd.global=!1,++parent.ref,psd.finalize=function(){--this.parent.ref||this.parent.finalize()};var rv=usePSD(psd,fn,a1,a2,a3);return 0===psd.ref&&psd.finalize(),rv}function usePSD(psd,fn,a1,a2,a3){var outerScope=PSD;try{return psd!==outerScope&&(PSD=psd),fn(a1,a2,a3)}finally{psd!==outerScope&&(PSD=outerScope)}}function globalError(err,promise){var rv;try{rv=promise.onuncatched(err)}catch(e){}if(rv!==!1)try{var event,eventData={promise:promise,reason:err};if(_global.document&&document.createEvent?(event=document.createEvent("Event"),event.initEvent(UNHANDLEDREJECTION,!0,!0),extend(event,eventData)):_global.CustomEvent&&(event=new CustomEvent(UNHANDLEDREJECTION,{detail:eventData}),extend(event,eventData)),event&&_global.dispatchEvent&&(dispatchEvent(event),!_global.PromiseRejectionEvent&&_global.onunhandledrejection))try{_global.onunhandledrejection(event)}catch(_){}event.defaultPrevented||Promise.on.error.fire(err,promise)}catch(e){}}function rejection(err,uncaughtHandler){var rv=Promise.reject(err);return uncaughtHandler?rv.uncaught(uncaughtHandler):rv}function Dexie(dbName,options){function init(){db.on("versionchange",function(ev){ev.newVersion>0?console.warn("Another connection wants to upgrade database '"+db.name+"'. Closing db now to resume the upgrade."):console.warn("Another connection wants to delete database '"+db.name+"'. Closing db now to resume the delete request."),db.close()}),db.on("blocked",function(ev){!ev.newVersion||ev.newVersionoldVersion}).forEach(function(version){queue.push(function(){var oldSchema=globalSchema,newSchema=version._cfg.dbschema;adjustToExistingIndexNames(oldSchema,idbtrans),adjustToExistingIndexNames(newSchema,idbtrans),globalSchema=db._dbSchema=newSchema;var diff=getSchemaDiff(oldSchema,newSchema);if(diff.add.forEach(function(tuple){createTable(idbtrans,tuple[0],tuple[1].primKey,tuple[1].indexes)}),diff.change.forEach(function(change){if(change.recreate)throw new exceptions.Upgrade("Not yet support for changing primary key");var store=idbtrans.objectStore(change.name);change.add.forEach(function(idx){addIndex(store,idx)}),change.change.forEach(function(idx){store.deleteIndex(idx.name),addIndex(store,idx)}),change.del.forEach(function(idxName){store.deleteIndex(idxName)})}),version._cfg.contentUpgrade)return anyContentUpgraderHasRun=!0,Promise.follow(function(){version._cfg.contentUpgrade(trans)})}),queue.push(function(idbtrans){anyContentUpgraderHasRun&&hasIEDeleteObjectStoreBug||deleteRemovedTables(version._cfg.dbschema,idbtrans)})}),runQueue().then(function(){createMissingTables(globalSchema,idbtrans)})}function getSchemaDiff(oldSchema,newSchema){var diff={del:[],add:[],change:[]};for(var table in oldSchema)newSchema[table]||diff.del.push(table);for(table in newSchema){var oldDef=oldSchema[table],newDef=newSchema[table];if(oldDef){var change={name:table,def:newDef,recreate:!1,del:[],add:[],change:[]};if(oldDef.primKey.src!==newDef.primKey.src)change.recreate=!0,diff.change.push(change);else{var oldIndexes=oldDef.idxByName,newIndexes=newDef.idxByName;for(var idxName in oldIndexes)newIndexes[idxName]||change.del.push(idxName);for(idxName in newIndexes){var oldIdx=oldIndexes[idxName],newIdx=newIndexes[idxName];oldIdx?oldIdx.src!==newIdx.src&&change.change.push(newIdx):change.add.push(newIdx)}(change.del.length>0||change.add.length>0||change.change.length>0)&&diff.change.push(change)}}else diff.add.push([table,newDef])}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});return indexes.forEach(function(idx){addIndex(store,idx)}),store}function createMissingTables(newSchema,idbtrans){keys(newSchema).forEach(function(tableName){idbtrans.db.objectStoreNames.contains(tableName)||createTable(idbtrans,tableName,newSchema[tableName].primKey,newSchema[tableName].indexes)})}function deleteRemovedTables(newSchema,idbtrans){for(var i=0;i0?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 ab?-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(){if(db.verno=idbdb.version/10,db._dbSchema=globalSchema={},dbStoreNames=slice(idbdb.objectStoreNames,0),0!==dbStoreNames.length){var trans=idbdb.transaction(safariMultiStoreFix(dbStoreNames),"readonly");dbStoreNames.forEach(function(storeName){for(var store=trans.objectStore(storeName),keyPath=store.keyPath,dotted=keyPath&&"string"==typeof keyPath&&keyPath.indexOf(".")!==-1,primKey=new IndexSpec(keyPath,keyPath||"",!1,!1,!!store.autoIncrement,keyPath&&"string"!=typeof keyPath,dotted),indexes=[],j=0;j0&&(autoSchema=!1),!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(10*db.verno));if(!req)throw new exceptions.MissingAPI("IndexedDB API not available");req.onerror=wrap(eventRejectHandler(reject)),req.onblocked=wrap(fireOnBlocked),req.onupgradeneeded=wrap(function(e){if(upgradeTransaction=req.transaction,autoSchema&&!db._allowEmptyDB){req.onerror=preventDefault,upgradeTransaction.abort(),req.result.close();var delreq=indexedDB.deleteDatabase(dbName);delreq.onsuccess=delreq.onerror=wrap(function(){reject(new exceptions.NoSuchDatabase("Database "+dbName+" doesnt exist"))})}else{upgradeTransaction.onerror=wrap(eventRejectHandler(reject));runUpgraders((e.oldVersion>Math.pow(2,62)?0:e.oldVersion)/10,upgradeTransaction,reject,req)}},reject),req.onsuccess=wrap(function(){if(upgradeTransaction=null,idbdb=req.result,connections.push(db),autoSchema)readGlobalSchema();else if(idbdb.objectStoreNames.length>0)try{adjustToExistingIndexNames(globalSchema,idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames),READONLY))}catch(e){}idbdb.onversionchange=wrap(function(ev){db._vcFired=!0,db.on("versionchange").fire(ev)}),hasNativeGetDatabaseNames||globalDatabaseList(function(databaseNames){if(databaseNames.indexOf(dbName)===-1)return databaseNames.push(dbName)}),resolve()},reject)})]).then(function(){return Dexie.vip(db.on.ready.fire)}).then(function(){return isBeingOpened=!1,db}).catch(function(err){try{upgradeTransaction&&upgradeTransaction.abort()}catch(e){}return isBeingOpened=!1,db.close(),dbOpenError=err,rejection(dbOpenError,dbUncaught)}).finally(function(){openComplete=!0,resolveDbReady()})},this.close=function(){var idx=connections.indexOf(db);if(idx>=0&&connections.splice(idx,1),idbdb){try{idbdb.close()}catch(e){}idbdb=null}autoOpen=!1,dbOpenError=new exceptions.DatabaseClosed,isBeingOpened&&cancelOpen(dbOpenError),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){function doDelete(){db.close();var req=indexedDB.deleteDatabase(dbName);req.onsuccess=wrap(function(){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}if(hasArguments)throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()");isBeingOpened?dbReadyPromise.then(doDelete):doDelete()}).uncaught(dbUncaught)},this.backendDB=function(){return idbdb},this.isOpen=function(){return null!==idbdb},this.hasFailed=function(){return null!==dbOpenError},this.dynamicallyOpened=function(){return autoSchema},this.name=dbName,setProp(this,"tables",{get:function(){return keys(allTables).map(function(name){return allTables[name]})}}),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(){openComplete?(dbOpenError||Promise.resolve().then(subscriber),bSticky&&subscribe(subscriber)):(subscribe(subscriber),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){function enterTransactionScope(resolve){var parentPSD=PSD;resolve(Promise.resolve().then(function(){return newScope(function(){PSD.transless=PSD.transless||parentPSD;var trans=db._createTransaction(mode,storeNames,globalSchema,parentTransaction);PSD.trans=trans,parentTransaction?trans.idbtrans=parentTransaction.idbtrans:trans.create();var tableArgs=storeNames.map(function(name){return allTables[name]});tableArgs.push(trans);var returnValue;return Promise.follow(function(){if(returnValue=scopeFunc.apply(trans,tableArgs))if("function"==typeof returnValue.next&&"function"==typeof returnValue.throw)returnValue=awaitIterator(returnValue);else if("function"==typeof returnValue.then&&!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(){return parentTransaction&&trans._resolve(),trans._completion}).then(function(){return returnValue}).catch(function(e){return trans._reject(e),rejection(e)})})}))}var i=arguments.length;if(i<2)throw new exceptions.InvalidArgument("Too few arguments");for(var args=new Array(i-1);--i;)args[i-1]=arguments[i];scopeFunc=args.pop();var tables=flatten(args),parentTransaction=PSD.trans;parentTransaction&&parentTransaction.db===db&&mode.indexOf("!")===-1||(parentTransaction=null);var onlyIfCompatible=mode.indexOf("?")!==-1;mode=mode.replace("!","").replace("?","");try{var storeNames=tables.map(function(table){var storeName=table instanceof Table?table.name:table;if("string"!=typeof storeName)throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return storeName});if("r"==mode||mode==READONLY)mode=READONLY;else{if("rw"!=mode&&mode!=READWRITE)throw new exceptions.InvalidArgument("Invalid transaction mode: "+mode);mode=READWRITE}if(parentTransaction){if(parentTransaction.mode===READONLY&&mode===READWRITE){if(!onlyIfCompatible)throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");parentTransaction=null}parentTransaction&&storeNames.forEach(function(storeName){if(parentTransaction&&parentTransaction.storeNames.indexOf(storeName)===-1){if(!onlyIfCompatible)throw new exceptions.SubTransaction("Table "+storeName+" not included in parent transaction.");parentTransaction=null}})}}catch(e){return parentTransaction?parentTransaction._promise(null,function(_,reject){reject(e)}):rejection(e,dbUncaught)}return parentTransaction?parentTransaction._promise(mode,enterTransactionScope,"lock"):db._whenReady(enterTransactionScope)},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]},props(Table.prototype,{_trans:function(mode,fn,writeLocked){var trans=PSD.trans;return trans&&trans.db===db?trans._promise(mode,fn,writeLocked):tempTransaction(mode,[this.name],fn)},_idbstore:function(mode,fn,writeLocked){function supplyIdbStore(resolve,reject,trans){fn(resolve,reject,trans.idbtrans.objectStore(tableName),trans)}if(fake)return new Promise(fn);var trans=PSD.trans,tableName=this.name;return trans&&trans.db===db?trans._promise(mode,supplyIdbStore,writeLocked):tempTransaction(mode,[this.name],supplyIdbStore)},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){this.schema.mappedClass=constructor;var instanceTemplate=Object.create(constructor.prototype);structure&&applyStructure(instanceTemplate,structure),this.schema.instanceTemplate=instanceTemplate;var readHook=function(obj){if(!obj)return obj;var res=Object.create(constructor.prototype);for(var m in obj)if(hasOwn(obj,m))try{res[m]=obj[m]}catch(_){}return res};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=readHook,this.hook("reading",readHook),constructor},defineClass:function(structure){return this.mapToClass(Dexie.defineClass(structure),structure)}}),derive(WriteableTable).from(Table).extend({bulkDelete:function(keys$$1){return this.hook.deleting.fire===nop?this._idbstore(READWRITE,function(resolve,reject,idbstore,trans){resolve(bulkDelete(idbstore,trans,keys$$1,!1,nop))}):this.where(":id").anyOf(keys$$1).delete().then(function(){})},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(0===objects.length)return resolve();var req,errorHandler,done=function(result){0===errorList.length?resolve(result):reject(new BulkError(_this.name+".bulkPut(): "+errorList.length+" of "+numObjs+" operations failed",errorList))},errorList=[],numObjs=objects.length,table=_this;if(_this.hook.creating.fire===nop&&_this.hook.updating.fire===nop){errorHandler=BulkErrorHandlerCatchAll(errorList);for(var i=0,l=objects.length;i=0;--i){var key=effectiveKeys[i];(null==key||objectLookup[key])&&(objsToAdd.push(objects[i]),keys$$1&&keysToAdd.push(key),null!=key&&(objectLookup[key]=null))}return objsToAdd.reverse(),keys$$1&&keysToAdd.reverse(),table.bulkAdd(objsToAdd,keysToAdd)}).then(function(lastAddedKey){var lastEffectiveKey=effectiveKeys[effectiveKeys.length-1];return null!=lastEffectiveKey?lastEffectiveKey:lastAddedKey}):table.bulkAdd(objects)).then(done).catch(BulkError,function(e){errorList=errorList.concat(e.failures),done()}).catch(reject)}},"locked")},bulkAdd:function(objects,keys$$1){var self=this,creatingHook=this.hook.creating.fire;return this._idbstore(READWRITE,function(resolve,reject,idbstore,trans){function done(result){0===errorList.length?resolve(result):reject(new BulkError(self.name+".bulkAdd(): "+errorList.length+" of "+numObjs+" operations failed",errorList))}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(0===objects.length)return resolve();var req,errorHandler,successHandler,errorList=[],numObjs=objects.length;if(creatingHook!==nop){var hookCtx,keyPath=idbstore.keyPath;errorHandler=BulkErrorHandlerCatchAll(errorList,null,!0),successHandler=hookedEventSuccessHandler(null),tryCatch(function(){for(var i=0,l=objects.length;i0&&!this._locked();){var fnAndPSD=this._blockedFuncs.shift();try{usePSD(fnAndPSD[1],fnAndPSD[0])}catch(e){}}return this},_locked:function(){return this._reculock&&PSD.lockOwnerFor!==this},create:function(idbtrans){var _this3=this;if(assert(!this.idbtrans),!idbtrans&&!idbdb)switch(dbOpenError&&dbOpenError.name){case"DatabaseClosedError":throw new exceptions.DatabaseClosed(dbOpenError);case"MissingAPIError":throw new exceptions.MissingAPI(dbOpenError.message,dbOpenError);default:throw new exceptions.OpenFailed(dbOpenError)}if(!this.active)throw new exceptions.TransactionInactive;return assert(null===this._completion._state),idbtrans=this.idbtrans=idbtrans||idbdb.transaction(safariMultiStoreFix(this.storeNames),this.mode),idbtrans.onerror=wrap(function(ev){preventDefault(ev),_this3._reject(idbtrans.error)}),idbtrans.onabort=wrap(function(ev){preventDefault(ev),_this3.active&&_this3._reject(new exceptions.Abort),_this3.active=!1,_this3.on("abort").fire(ev)}),idbtrans.oncomplete=wrap(function(){_this3.active=!1,_this3._resolve()}),this},_promise:function(mode,fn,bWriteLock){var self=this,p=self._locked()?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");!self.idbtrans&&mode&&self.create(),bWriteLock&&self._lock(),fn(resolve,reject,self)}):rejection(new exceptions.TransactionInactive);return self.active&&bWriteLock&&p_.finally(function(){self._unlock()}),p_});return p._lib=!0,p.uncaught(dbUncaught)},abort:function(){this.active&&this._reject(new exceptions.Abort),this.active=!1},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]})}),props(WhereClause.prototype,function(){function fail(collectionOrWhereClause,err,T){var collection=collectionOrWhereClause instanceof WhereClause?new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause):collectionOrWhereClause;return collection._ctx.error=T?new T(err):new TypeError(err),collection}function emptyCollection(whereClause){return new whereClause._ctx.collClass(whereClause,function(){return IDBKeyRange.only("")}).limit(0)}function upperFactory(dir){return"next"===dir?function(s){return s.toUpperCase()}:function(s){return s.toLowerCase()}}function lowerFactory(dir){return"next"===dir?function(s){return s.toLowerCase()}:function(s){return s.toUpperCase()}}function nextCasing(key,lowerKey,upperNeedle,lowerNeedle,cmp,dir){for(var length=Math.min(key.length,lowerNeedle.length),llp=-1,i=0;i=0?key.substr(0,llp)+lowerKey[llp]+upperNeedle.substr(llp+1):null;cmp(key[i],lwrKeyChar)<0&&(llp=i)}return length0)&&(lowestPossibleCasing=casing)}return advance(null!==lowestPossibleCasing?function(){cursor.continue(lowestPossibleCasing+nextKeySuffix)}:resolve),!1}),c}return{between:function(lower,upper,includeLower,includeUpper){includeLower=includeLower!==!1,includeUpper=includeUpper===!0;try{return cmp(lower,upper)>0||0===cmp(lower,upper)&&(includeLower||includeUpper)&&(!includeLower||!includeUpper)?emptyCollection(this):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,!0)})},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,!0)})},belowOrEqual:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.upperBound(value)})},startsWith:function(str){return"string"!=typeof str?fail(this,STRING_EXPECTED):this.between(str,str+maxString,!0,!0)},startsWithIgnoreCase:function(str){return""===str?this.startsWith(str):addIgnoreCaseAlgorithm(this,function(x,a){return 0===x.indexOf(a[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);return 0===set.length?emptyCollection(this):addIgnoreCaseAlgorithm(this,function(x,a){return a.indexOf(x)!==-1},set,"")},startsWithAnyOfIgnoreCase:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);return 0===set.length?emptyCollection(this):addIgnoreCaseAlgorithm(this,function(x,a){return a.some(function(n){return 0===x.indexOf(n)})},set,maxString)},anyOf:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments),compare=ascending;try{set.sort(compare)}catch(e){return fail(this,INVALID_KEY_ARGUMENT)}if(0===set.length)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="next"===direction?ascending:descending,set.sort(compare)};var i=0;return c._addAlgorithm(function(cursor,advance,resolve){for(var key=cursor.key;compare(key,set[i])>0;)if(++i,i===set.length)return advance(resolve),!1;return 0===compare(key,set[i])||(advance(function(){cursor.continue(set[i])}),!1)}),c},notEqual:function(value){return this.inAnyRange([[-(1/0),value],[value,maxKey]],{includeLowers:!1,includeUppers:!1})},noneOf:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);if(0===set.length)return new this._ctx.collClass(this);try{set.sort(ascending)}catch(e){return fail(this,INVALID_KEY_ARGUMENT)}var ranges=set.reduce(function(res,val){return res?res.concat([[res[res.length-1][1],val]]):[[-(1/0),val]]},null);return ranges.push([set[set.length-1],maxKey]),this.inAnyRange(ranges,{includeLowers:!1,includeUppers:!1})},inAnyRange:function(ranges,options){function addRange(ranges,newRange){for(var i=0,l=ranges.length;i0){range[0]=min(range[0],newRange[0]),range[1]=max(range[1],newRange[1]);break}}return i===l&&ranges.push(newRange),ranges}function rangeSorter(a,b){return sortDirection(a[0],b[0])}function keyWithinCurrentRange(key){return!keyIsBeyondCurrentEntry(key)&&!keyIsBeforeCurrentEntry(key)}var ctx=this._ctx;if(0===ranges.length)return emptyCollection(this);if(!ranges.every(function(range){return void 0!==range[0]&&void 0!==range[1]&&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 set,includeLowers=!options||options.includeLowers!==!1,includeUppers=options&&options.includeUppers===!0,sortDirection=ascending;try{set=ranges.reduce(addRange,[]),set.sort(rangeSorter)}catch(ex){return fail(this,INVALID_KEY_ARGUMENT)}var i=0,keyIsBeyondCurrentEntry=includeUppers?function(key){return ascending(key,set[i][1])>0}:function(key){return ascending(key,set[i][1])>=0},keyIsBeforeCurrentEntry=includeLowers?function(key){return descending(key,set[i][0])>0}:function(key){return descending(key,set[i][0])>=0},checkKey=keyIsBeyondCurrentEntry,c=new ctx.collClass(this,function(){return IDBKeyRange.bound(set[0][0],set[set.length-1][1],!includeLowers,!includeUppers)});return c._ondirectionchange=function(direction){"next"===direction?(checkKey=keyIsBeyondCurrentEntry,sortDirection=ascending):(checkKey=keyIsBeforeCurrentEntry,sortDirection=descending),set.sort(rangeSorter)},c._addAlgorithm(function(cursor,advance,resolve){for(var key=cursor.key;checkKey(key);)if(++i,i===set.length)return advance(resolve),!1;return!!keyWithinCurrentRange(key)||0!==cmp(key,set[i][1])&&0!==cmp(key,set[i][0])&&(advance(function(){sortDirection===ascending?cursor.continue(set[i][0]):cursor.continue(set[i][1])}),!1)}),c},startsWithAnyOf:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);return set.every(function(s){return"string"==typeof s})?0===set.length?emptyCollection(this):this.inAnyRange(set.map(function(str){return[str,str+maxString]})):fail(this,"startsWithAnyOf() only works with strings")}}}),props(Collection.prototype,function(){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)}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)}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;ctx.or?function(){function resolveboth(){2===++resolved&&resolve()}function union(item,cursor,advance){if(!filter||filter(cursor,advance,resolveboth,reject)){var key=cursor.primaryKey.toString();hasOwn(set,key)||(set[key]=!0,fn(item,cursor,advance))}}var set={},resolved=0;ctx.or._iterate(union,resolveboth,reject,idbstore),iterate(openCursor(ctx,idbstore),ctx.algorithm,union,resolveboth,reject,!ctx.keysOnly&&ctx.valueMapper)}():iterate(openCursor(ctx,idbstore),combine(ctx.algorithm,filter),fn,resolve,reject,!ctx.keysOnly&&ctx.valueMapper)}function getInstanceTemplate(ctx){return ctx.table.schema.instanceTemplate}return{_read:function(fn,cb){var ctx=this._ctx;return ctx.error?ctx.table._trans(null,function(resolve,reject){reject(ctx.error)}):ctx.table._idbstore(READONLY,fn).then(cb)},_write:function(fn){var ctx=this._ctx;return ctx.error?ctx.table._trans(null,function(resolve,reject){reject(ctx.error)}):ctx.table._idbstore(READWRITE,fn,"locked")},_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);return props$$1&&extend(ctx,props$$1),rv._ctx=ctx,rv},raw:function(){return this._ctx.valueMapper=null,this},each:function(fn){var ctx=this._ctx;if(fake){var item=getInstanceTemplate(ctx),primKeyPath=ctx.table.schema.primKey.keyPath;fn(item,{key:getByKeyPath(item,ctx.index?ctx.table.schema.idxByName[ctx.index].keyPath:primKeyPath),primaryKey:getByKeyPath(item,primKeyPath)})}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,!0))return this._read(function(resolve,reject,idbstore){var idx=getIndexOrStore(ctx,idbstore),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);var count=0;return this._read(function(resolve,reject,idbstore){iter(ctx,function(){return++count,!1},function(){resolve(count)},reject,idbstore)},cb)},sortBy:function(keyPath,cb){function getval(obj,i){return i?getval(obj[parts[i]],i-1):obj[lastPart]}function sorter(a,b){var aVal=getval(a,lastIndex),bVal=getval(b,lastIndex);return aValbVal?order:0}var parts=keyPath.split(".").reverse(),lastPart=parts[0],lastIndex=parts.length-1,order="next"===this._ctx.dir?1:-1;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){if(fake&&resolve([getInstanceTemplate(ctx)]),hasGetAll&&"next"===ctx.dir&&isPlainKeyRange(ctx,!0)&&ctx.limit>0){var readingHook=ctx.table.hook.reading.fire,idxOrStore=getIndexOrStore(ctx,idbstore),req=ctx.limit<1/0?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{var a=[];iter(ctx,function(item){a.push(item)},function(){resolve(a)},reject,idbstore)}},cb)},offset:function(offset){var ctx=this._ctx;return offset<=0?this:(ctx.offset+=offset,isPlainKeyRange(ctx)?addReplayFilter(ctx,function(){var offsetLeft=offset;return function(cursor,advance){return 0===offsetLeft||(1===offsetLeft?(--offsetLeft,!1):(advance(function(){cursor.advance(offsetLeft),offsetLeft=0}),!1))}}):addReplayFilter(ctx,function(){var offsetLeft=offset;return function(){return--offsetLeft<0}}),this)},limit:function(numRows){return this._ctx.limit=Math.min(this._ctx.limit,numRows),addReplayFilter(this._ctx,function(){var rowsLeft=numRows;return function(cursor,advance,resolve){return--rowsLeft<=0&&advance(resolve),rowsLeft>=0}},!0),this},until:function(filterFunction,bIncludeStopEntry){var ctx=this._ctx;return fake&&filterFunction(getInstanceTemplate(ctx)),addFilter(this._ctx,function(cursor,advance,resolve){return!filterFunction(cursor.value)||(advance(resolve),bIncludeStopEntry)}),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){return fake&&filterFunction(getInstanceTemplate(this._ctx)),addFilter(this._ctx,function(cursor){return filterFunction(cursor.value)}),addMatchFilter(this._ctx,filterFunction),this},and:function(filterFunction){return this.filter(filterFunction)},or:function(indexName){return new WhereClause(this._ctx.table,indexName,this)},reverse:function(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},desc:function(){return this.reverse()},eachKey:function(cb){var ctx=this._ctx;return ctx.keysOnly=!ctx.isMatch,this.each(function(val,cursor){cb(cursor.key,cursor)})},eachUniqueKey:function(cb){return this._ctx.unique="unique",this.eachKey(cb)},eachPrimaryKey:function(cb){var ctx=this._ctx;return ctx.keysOnly=!ctx.isMatch,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&&"next"===ctx.dir&&isPlainKeyRange(ctx,!0)&&ctx.limit>0)return this._read(function(resolve,reject,idbstore){var idxOrStore=getIndexOrStore(ctx,idbstore),req=ctx.limit<1/0?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){return this._ctx.unique="unique",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;var set={};return addFilter(this._ctx,function(cursor){var strKey=cursor.primaryKey.toString(),found=hasOwn(set,strKey);return set[strKey]=!0,!found}),this}}}),derive(WriteableCollection).from(Collection).extend({modify:function(changes){var self=this,ctx=this._ctx,hook=ctx.table.hook,updatingHook=hook.updating.fire,deletingHook=hook.deleting.fire;return fake&&"function"==typeof changes&&changes.call({value:ctx.table.schema.instanceTemplate},ctx.table.schema.instanceTemplate),this._write(function(resolve,reject,idbstore,trans){function modifyItem(item,cursor){function onerror(e){return failures.push(e),failKeys.push(thisContext.primKey),checkFinished(),!0}currentKey=cursor.primaryKey;var thisContext={primKey:cursor.primaryKey,value:item,onsuccess:null,onerror:null};if(modifyer.call(thisContext,item,thisContext)!==!1){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 thisContext.onsuccess&&thisContext.onsuccess(thisContext.value)}function doReject(e){return e&&(failures.push(e),failKeys.push(currentKey)),reject(new ModifyError("Error modifying one or more objects",failures,successCount,failKeys))}function checkFinished(){iterationComplete&&successCount+failures.length===count&&(failures.length>0?doReject():resolve(successCount))}var modifyer;if("function"==typeof changes)modifyer=updatingHook===nop&&deletingHook===nop?changes:function(item){var origItem=deepClone(item);if(changes.call(this,item,this)===!1)return!1;if(hasOwn(this,"value")){var objectDiff=getObjectDiff(origItem,this.value),additionalChanges=updatingHook.call(this,objectDiff,this.primKey,origItem,trans);additionalChanges&&(item=this.value,keys(additionalChanges).forEach(function(keyPath){setByKeyPath(item,keyPath,additionalChanges[keyPath])}))}else deletingHook.call(this,this.primKey,item,trans)};else if(updatingHook===nop){var keyPaths=keys(changes),numKeys=keyPaths.length;modifyer=function(item){for(var anythingModified=!1,i=0;i99?queue.push(Buffer.concat(data)):queue[lastIndex(queue)]=Buffer.concat(last(queue).concat(data)),queue}if(err)return cb(err);var table=_this.table;d.resolve(pull(toWindow(100,10),_write(writer,reduce,100,cb)))}),d):(cb(new Error("Missing key")),d)}},{key:"read",value:function(key){var _this2=this,p=pushable();return key?(this.exists(key,function(err,exists){return err?p.end(err):exists?void _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()}):p.end(new Error("Not found"))}),p):(p.end(new Error("Missing key")),p)}},{key:"exists",value:function(key,cb){if(cb=cb||function(){},!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(key,cb){if(cb=cb||function(){},!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(){return this.db[this.path]}}]),IdbBlobStore}()}).call(exports,__webpack_require__(18).Buffer)},function(module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=Math.pow(2,mLen),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,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},function(module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},function(module,exports){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)]}module.exports=isTypedArray,isTypedArray.strict=isStrictTypedArray,isTypedArray.loose=isLooseTypedArray;var toString=Object.prototype.toString,names={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0}},function(module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},function(module,exports,__webpack_require__){(function(setImmediate){module.exports=function(){function _releaser(key,exec){return function(done){return function(){_release(key,exec),done&&done.apply(null,arguments)}}}function _release(key,exec){var i=locked[key].indexOf(exec);~i&&(locked[key].splice(i,1),isLocked(key)?next(function(){locked[key][0](_releaser(key,locked[key][0]))}):delete locked[key])}function _lock(key,exec){return isLocked(key)?(locked[key].push(exec),!1):(locked[key]=[exec],!0)}function lock(key,exec){function releaser(done){return function(){var args=[].slice.call(arguments);for(var key in l)_release(key,l[key]);done.apply(this,args)}}if(Array.isArray(key)){var keys=key.length,l={};return void key.forEach(function(key){function ready(){n++||--keys||exec(releaser)}var n=0;l[key]=ready,_lock(key,ready)&&ready()})}_lock(key,exec)&&exec(_releaser(key,exec))}function isLocked(key){return!!Array.isArray(locked[key])&&!!locked[key].length}var next=void 0===setImmediate?setTimeout:setImmediate,locked={};return lock.isLocked=isLocked,lock}}).call(exports,__webpack_require__(53).setImmediate)},function(module,exports,__webpack_require__){(function(global){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)}function arrayIncludes(array,value){return!!(array?array.length:0)&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function baseRest(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var differenceWith=baseRest(function(array,values){var comparator=last(values);return isArrayLikeObject(comparator)&&(comparator=void 0),isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,!0),void 0,comparator):[]}),isArray=Array.isArray;module.exports=differenceWith}).call(exports,__webpack_require__(5))},function(module,exports,__webpack_require__){(function(global,module){function arraySome(array,predicate){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++indexarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){return(value<0?-1:1)*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?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}function toString(value){return null==value?"":baseToString(value)}function get(object,path,defaultValue){var result=null==object?void 0:baseGet(object,path);return void 0===result?defaultValue:result}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function identity(value){return value}function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path)}var LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,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]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reTrim=/^\s+|\s+$/g,reEscapeChar=/\\(\\)?/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,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]=!1;var freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,nativeKeys=overArg(Object.keys,Object),nativeMax=Math.max,DataView=getNative(root,"DataView"),Map=getNative(root,"Map"),Promise=getNative(root,"Promise"),Set=getNative(root,"Set"),WeakMap=getNative(root,"WeakMap"),nativeCreate=getNative(Object,"create"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=Symbol?Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0,symbolToString=symbolProto?symbolProto.toString:void 0;Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var getTag=baseGetTag;(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:void 0,ctorString=Ctor?toSource(Ctor):void 0;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});var stringToPath=memoize(function(string){string=toString(string);var result=[];return reLeadingDot.test(string)&&result.push(""),string.replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,"$1"):number||match)}),result});memoize.Cache=MapCache;var isArray=Array.isArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module.exports=findIndex}).call(exports,__webpack_require__(5),__webpack_require__(196)(module))},function(module,exports,__webpack_require__){(function(global){function arrayPush(array,values){for(var index=-1,length=values.length,offset=array.length;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function flatten(array){return(array?array.length:0)?baseFlatten(array,1):[]}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,isArray=Array.isArray;module.exports=flatten}).call(exports,__webpack_require__(5))},function(module,exports){function baseSlice(array,start,end){var index=-1,length=array.length;start<0&&(start=-start>length?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){return(value<0?-1:1)*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?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}var INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,funcTag="[object Function]",genTag="[object GeneratorFunction]",symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString;module.exports=slice},function(module,exports,__webpack_require__){(function(global){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)}function arrayIncludes(array,value){return!!(array?array.length:0)&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function baseRest(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function noop(){}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),Set=getNative(root,"Set"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var createSet=Set&&1/setToArray(new Set([,-0]))[1]==INFINITY?function(values){return new Set(values)}:noop,unionWith=baseRest(function(arrays){var comparator=last(arrays);return isArrayLikeObject(comparator)&&(comparator=void 0),baseUniq(baseFlatten(arrays,1,isArrayLikeObject,!0),void 0,comparator)}),isArray=Array.isArray;module.exports=unionWith}).call(exports,__webpack_require__(5))},function(module,exports){module.exports=function(fun){return function next(a,b,c){var loop=!0,sync=!1;do sync=!0,loop=!1,fun.call(function(x,y,z){sync?(a=x,b=y,c=z,loop=!0):next(x,y,z)},a,b,c),sync=!1;while(loop)}}},function(module,exports,__webpack_require__){(function(process){function normalizeArray(parts,allowAboveRoot){for(var up=0,i=parts.length-1;i>=0;i--){var last=parts[i];"."===last?parts.splice(i,1):".."===last?(parts.splice(i,1),up++):up&&(parts.splice(i,1),up--)}if(allowAboveRoot)for(;up--;up)parts.unshift("..");return parts}function filter(xs,f){if(xs.filter)return xs.filter(f);for(var res=[],i=0;i=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if("string"!=typeof path)throw new TypeError("Arguments to path.resolve must be strings");path&&(resolvedPath=path+"/"+resolvedPath,resolvedAbsolute="/"===path.charAt(0))}return resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/"),(resolvedAbsolute?"/":"")+resolvedPath||"."},exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash="/"===substr(path,-1);return path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/"),path||isAbsolute||(path="."),path&&trailingSlash&&(path+="/"),(isAbsolute?"/":"")+path},exports.isAbsolute=function(path){return"/"===path.charAt(0)},exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if("string"!=typeof p)throw new TypeError("Arguments to path.join must be strings");return p}).join("/"))},exports.relative=function(from,to){function trim(arr){for(var start=0;start=0&&""===arr[end];end--);return start>end?[]:arr.slice(start,end-start+1)}from=exports.resolve(from).substr(1),to=exports.resolve(to).substr(1);for(var fromParts=trim(from.split("/")),toParts=trim(to.split("/")),length=Math.min(fromParts.length,toParts.length),samePartsLength=length,i=0;imax?cb(!0):void cb(null,i++)}}},function(module,exports,__webpack_require__){"use strict";module.exports=function(){return function(abort,cb){cb(!0)}}},function(module,exports,__webpack_require__){"use strict";module.exports=function(err){return function(abort,cb){cb(err)}}},function(module,exports,__webpack_require__){"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)}},function(module,exports,__webpack_require__){"use strict";module.exports=function(generate){return generate=generate||Math.random,function(end,cb){return end?cb&&cb(end):cb(null,generate())}}},function(module,exports,__webpack_require__){"use strict";var values=__webpack_require__(51);module.exports=function(object){return values(Object.keys(object))}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var prop=__webpack_require__(27);module.exports=function(map){if(!map)return id;map=prop(map);var abortCb,aborted,busy=!1;return function(read){return function next(abort,cb){if(aborted)return cb(aborted);abort?(aborted=abort,busy?read(abort,function(){busy?abortCb=cb:cb(abort)}):read(abort,cb)):read(null,function(end,data){end?cb(end):aborted?cb(aborted):(busy=!0,map(data,function(err,data){busy=!1,aborted?(cb(aborted),abortCb(aborted)):err?next(err,cb):cb(null,data)}))})}}}},function(module,exports,__webpack_require__){"use strict";var tester=__webpack_require__(81),filter=__webpack_require__(52);module.exports=function(test){return test=tester(test),filter(function(data){return!test(data)})}},function(module,exports,__webpack_require__){"use strict";var values=__webpack_require__(51),once=__webpack_require__(78);module.exports=function(){return function(read){var _read;return function(abort,cb){function nextChunk(){_read(null,function(err,data){err===!0?nextStream():err?read(!0,function(abortErr){cb(err)}):cb(null,data)})}function nextStream(){_read=null,read(null,function(end,stream){if(end)return cb(end);Array.isArray(stream)||stream&&"object"==typeof stream?stream=values(stream):"function"!=typeof stream&&(stream=once(stream)),_read=stream,nextChunk()})}abort?_read?_read(abort,function(err){read(err||abort,cb)}):read(abort,cb):_read?nextChunk():nextStream()}}}},function(module,exports,__webpack_require__){"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)}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var prop=__webpack_require__(27);module.exports=function(mapper){return mapper?(mapper=prop(mapper),function(read){return function(abort,cb){read(abort,function(end,data){try{data=end?null:mapper(data)}catch(err){return read(err,function(){return cb(err)})}cb(end,data)})}}):id}},function(module,exports,__webpack_require__){"use strict";var unique=__webpack_require__(79);module.exports=function(field){return unique(field,!0)}},function(module,exports,__webpack_require__){"use strict";module.exports=function(test,opts){opts=opts||{};var last=opts.last||!1,ended=!1;if("number"==typeof test){last=!0;var n=test;test=function(){return--n}}return function(read){function terminate(cb){read(!0,function(err){last=!1,cb(err||!0)})}return function(end,cb){ended?last?terminate(cb):cb(ended):(ended=end)?read(ended,cb):read(null,function(end,data){(ended=ended||end)?cb(ended):test(data)?cb(null,data):(ended=!0,last?cb(null,data):terminate(cb))})}}}},function(module,exports,__webpack_require__){"use strict";module.exports=function(op,onEnd){function once(abort){!a&&onEnd&&(a=!0,onEnd(abort===!0?null:abort))}var a=!1;return function(read){return function(end,cb){return end&&once(end),read(end,function(end,data){end?once(end):op&&op(data),cb(end,data)})}}}},function(module,exports,__webpack_require__){var looper=__webpack_require__(165),window=module.exports=function(init,start){return function(read){start=start||function(start,data){return{start:start,data:data}};var windows=[],output=[],ended=null,j=0;return function(abort,cb){if(output.length)return cb(null,output.shift());if(ended)return cb(ended);j++;read(abort,looper(function(end,data){function _update(end,_data){once||(once=!0,delete windows[windows.indexOf(update)],output.push(start(data,_data)))}var update,next=this,once=!1;return end&&(ended=end),ended||(update=init(data,_update)),update?windows.push(update):once=!0,windows.forEach(function(update,i){update(end,data)}),output.length?cb(null,output.shift()):ended?cb(ended):void read(null,next)}))}}};window.recent=function(size,time){var current=null;return window(function(data,cb){function done(){var _current=current;current=null,clearTimeout(timer),cb(null,_current)}if(!current){current=[];var timer;return time&&(timer=setTimeout(done,time)),function(end,data){if(end)return done();current.push(data),null!=size&¤t.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,i=0;k++;return function(end,data){end||(acc=reduce(acc,data),width<=++i&&cb(null,acc))}})}},function(module,exports){function append(array,item){return(array=array||[]).push(item),array}module.exports=function(write,reduce,max,cb){function reader(read){function more(){reading||ended||(reading=!0,read(null,function(err,data){reading=!1,next(err,data)}))}function flush(){if(!writing){var _queue=queue;queue=null,writing=!0,length=0,write(_queue,function(err){writing=!1,ended!==!0||length?ended&&ended!==!0?(cb(ended),_cb&&_cb()):err?read(ended=err,cb):length?flush():more():cb(err)})}}function next(end,data){ended||(ended=end,ended?writing||cb(ended===!0?null:ended):(queue=reduce(queue,data),length=queue&&queue.length||0,null!=queue&&flush(),length=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){base=" [Function"+(value.name?": "+value.name:"")+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;return output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];i1&&void 0!==arguments[1]?arguments[1]:"default",options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};(0,_classCallCheck3.default)(this,OrbitDB),this._ipfs=ipfs,this._pubsub=options&&options.broker?new options.broker(ipfs):new Pubsub(ipfs),this.user={id:id},this.network={name:defaultNetworkName},this.events=new EventEmitter,this.stores={}}return(0,_createClass3.default)(OrbitDB,[{key:"feed",value:function(dbname,options){return this._createStore(FeedStore,dbname,options)}},{key:"eventlog",value:function(dbname,options){return this._createStore(EventStore,dbname,options)}},{key:"kvstore",value:function(dbname,options){return this._createStore(KeyValueStore,dbname,options)}},{key:"counter",value:function(dbname,options){return this._createStore(CounterStore,dbname,options)}},{key:"docstore",value:function(dbname,options){return this._createStore(DocumentStore,dbname,options)}},{key:"disconnect",value:function(){var _this=this;this._pubsub&&this._pubsub.disconnect(),this.events.removeAllListeners("data"),(0,_keys2.default)(this.stores).map(function(e){return _this.stores[e]}).forEach(function(store){store.events.removeAllListeners("data"),store.events.removeAllListeners("write"),store.events.removeAllListeners("close")}),this.stores={},this.user=null,this.network=null}},{key:"_createStore",value:function(Store,dbname){var options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{subscribe:!0},store=new Store(this._ipfs,this.user.id,dbname,options);return this.stores[dbname]=store,this._subscribe(store,dbname,options.subscribe,options.cachePath)}},{key:"_subscribe",value:function(store,dbname){var subscribe=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],cachePath=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"./orbit-db";return store.events.on("data",this._onData.bind(this)),store.events.on("write",this._onWrite.bind(this)),store.events.on("close",this._onClose.bind(this)),subscribe&&this._pubsub?this._pubsub.subscribe(dbname,this._onMessage.bind(this),this._onConnected.bind(this),store.options.maxHistory>0):store.loadHistory().catch(function(e){return console.error(e.stack)}),Cache.loadCache(cachePath).then(function(){var hash=Cache.get(dbname);store.loadHistory(hash).catch(function(e){return console.error(e.stack)})}),store}},{key:"_onConnected",value:function(dbname,hash){this.stores[dbname].loadHistory(hash).catch(function(e){return console.error(e.stack)})}},{key:"_onMessage",value:function(dbname,hash){var _this2=this;this.stores[dbname].sync(hash).then(function(res){return Cache.set(dbname,res)}).then(function(){return _this2.events.emit("synced",dbname,hash)}).catch(function(e){return console.error(e.stack)})}},{key:"_onWrite",value:function(dbname,hash){if(!hash)throw new Error("Hash can't be null!");this._pubsub&&this._pubsub.publish(dbname,hash),Cache.set(dbname,hash)}},{key:"_onData",value:function(dbname,items){this.events.emit("data",dbname,items)}},{key:"_onClose",value:function(dbname){this._pubsub&&this._pubsub.unsubscribe(dbname),delete this.stores[dbname]}}]),OrbitDB}();module.exports=OrbitDB}]); \ No newline at end of file +var $=e(26),Z=e(31),X=e(37);n.Buffer=u,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50,u.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:r(),n.kMaxLength=i(),u.poolSize=8192,u._augment=function(t){return t.__proto__=u.prototype,t},u.from=function(t,n,e){return s(null,t,n,e)},u.TYPED_ARRAY_SUPPORT&&(u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0})),u.alloc=function(t,n,e){return a(null,t,n,e)},u.allocUnsafe=function(t){return f(null,t)},u.allocUnsafeSlow=function(t){return f(null,t)},u.isBuffer=function(t){return!(null==t||!t._isBuffer)},u.compare=function(t,n){if(!u.isBuffer(t)||!u.isBuffer(n))throw new TypeError("Arguments must be Buffers");if(t===n)return 0;for(var e=t.length,r=n.length,i=0,o=Math.min(e,r);i0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},u.prototype.compare=function(t,n,e,r,i){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===n&&(n=0),void 0===e&&(e=t?t.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),n<0||e>t.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&n>=e)return 0;if(r>=i)return-1;if(n>=e)return 1;if(n>>>=0,e>>>=0,r>>>=0,i>>>=0,this===t)return 0;for(var o=i-r,s=e-n,c=Math.min(o,s),a=this.slice(r,i),f=t.slice(n,e),h=0;hi)&&(e=i),t.length>0&&(e<0||n<0)||n>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return x(this,t,n,e);case"utf8":case"utf-8":return E(this,t,n,e);case"ascii":return k(this,t,n,e);case"latin1":case"binary":return A(this,t,n,e);case"base64":return O(this,t,n,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,n,e);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var tt=4096;u.prototype.slice=function(t,n){var e=this.length;t=~~t,n=void 0===n?e:~~n,t<0?(t+=e)<0&&(t=0):t>e&&(t=e),n<0?(n+=e)<0&&(n=0):n>e&&(n=e),n0&&(i*=256);)r+=this[t+--n]*i;return r},u.prototype.readUInt8=function(t,n){return n||C(t,1,this.length),this[t]},u.prototype.readUInt16LE=function(t,n){return n||C(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUInt16BE=function(t,n){return n||C(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUInt32LE=function(t,n){return n||C(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUInt32BE=function(t,n){return n||C(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readIntLE=function(t,n,e){t|=0,n|=0,e||C(t,n,this.length);for(var r=this[t],i=1,o=0;++o=i&&(r-=Math.pow(2,8*n)),r},u.prototype.readIntBE=function(t,n,e){t|=0,n|=0,e||C(t,n,this.length);for(var r=n,i=1,o=this[t+--r];r>0&&(i*=256);)o+=this[t+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*n)),o},u.prototype.readInt8=function(t,n){return n||C(t,1,this.length),128&this[t]?(255-this[t]+1)*-1:this[t]},u.prototype.readInt16LE=function(t,n){n||C(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},u.prototype.readInt16BE=function(t,n){n||C(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},u.prototype.readInt32LE=function(t,n){return n||C(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,n){return n||C(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readFloatLE=function(t,n){return n||C(t,4,this.length),Z.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,n){return n||C(t,4,this.length),Z.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,n){return n||C(t,8,this.length),Z.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,n){return n||C(t,8,this.length),Z.read(this,t,!1,52,8)},u.prototype.writeUIntLE=function(t,n,e,r){if(t=+t,n|=0,e|=0,!r){L(this,t,n,e,Math.pow(2,8*e)-1,0)}var i=1,o=0;for(this[n]=255&t;++o=0&&(o*=256);)this[n+i]=t/o&255;return n+e},u.prototype.writeUInt8=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,1,255,0),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[n]=255&t,n+1},u.prototype.writeUInt16LE=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8):M(this,t,n,!0),n+2},u.prototype.writeUInt16BE=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[n]=t>>>8,this[n+1]=255&t):M(this,t,n,!1),n+2},u.prototype.writeUInt32LE=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[n+3]=t>>>24,this[n+2]=t>>>16,this[n+1]=t>>>8,this[n]=255&t):U(this,t,n,!0),n+4},u.prototype.writeUInt32BE=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[n]=t>>>24,this[n+1]=t>>>16,this[n+2]=t>>>8,this[n+3]=255&t):U(this,t,n,!1),n+4},u.prototype.writeIntLE=function(t,n,e,r){if(t=+t,n|=0,!r){var i=Math.pow(2,8*e-1);L(this,t,n,e,i-1,-i)}var o=0,u=1,s=0;for(this[n]=255&t;++o>0)-s&255;return n+e},u.prototype.writeIntBE=function(t,n,e,r){if(t=+t,n|=0,!r){var i=Math.pow(2,8*e-1);L(this,t,n,e,i-1,-i)}var o=e-1,u=1,s=0;for(this[n+o]=255&t;--o>=0&&(u*=256);)t<0&&0===s&&0!==this[n+o+1]&&(s=1),this[n+o]=(t/u>>0)-s&255;return n+e},u.prototype.writeInt8=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,1,127,-128),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[n]=255&t,n+1},u.prototype.writeInt16LE=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8):M(this,t,n,!0),n+2},u.prototype.writeInt16BE=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[n]=t>>>8,this[n+1]=255&t):M(this,t,n,!1),n+2},u.prototype.writeInt32LE=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[n]=255&t,this[n+1]=t>>>8,this[n+2]=t>>>16,this[n+3]=t>>>24):U(this,t,n,!0),n+4},u.prototype.writeInt32BE=function(t,n,e){return t=+t,n|=0,e||L(this,t,n,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),u.TYPED_ARRAY_SUPPORT?(this[n]=t>>>24,this[n+1]=t>>>16,this[n+2]=t>>>8,this[n+3]=255&t):U(this,t,n,!1),n+4},u.prototype.writeFloatLE=function(t,n,e){return F(this,t,n,!0,e)},u.prototype.writeFloatBE=function(t,n,e){return F(this,t,n,!1,e)},u.prototype.writeDoubleLE=function(t,n,e){return K(this,t,n,!0,e)},u.prototype.writeDoubleBE=function(t,n,e){return K(this,t,n,!1,e)},u.prototype.copy=function(t,n,e,r){if(e||(e=0),r||0===r||(r=this.length),n>=t.length&&(n=t.length),n||(n=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),t.length-n=0;--i)t[i+n]=this[i+e];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,e=void 0===e?this.length:e>>>0,t||(t=0);var o;if("number"==typeof t)for(o=n;onew Error("Ipfs instance not defined");class u{static create(t,n,e,s,c=[],a){if(!i(t))throw o();if(!i(n))throw new Error("Entry requires an id");if(!i(s))throw new Error("Entry requires data");if(!i(c)||!Array.isArray(c))throw new Error("'next' argument is not an array");let f=c.filter(t=>void 0!==t&&null!==t).map(t=>t.hash?t.hash:t),h={hash:null,id:n,payload:s,next:f,v:0,clock:a?a.clone():new r(n)};return u.toMultihash(t,h).then(t=>{return h.hash=t,h})}static toMultihash(t,e){if(!t)throw o();const r=new n(JSON.stringify(e));return t.object.put(r).then(t=>t.toJSON().multihash)}static fromMultihash(t,n){if(!t)throw o();if(!n)throw new Error(`Invalid hash: ${n}`);return t.object.get(n,{enc:"base58"}).then(t=>JSON.parse(t.toJSON().data)).then(t=>{return{hash:n,id:t.id,payload:t.payload,next:t.next,v:t.v,clock:t.clock}})}static isEntry(t){return void 0!==t.id&&void 0!==t.next&&void 0!==t.hash&&void 0!==t.payload&&void 0!==t.v&&void 0!==t.clock}static compare(t,n){var e=r.compare(t.clock,n.clock);return 0===e?t.clock.id-1}}t.exports=u}).call(n,e(0).Buffer)},function(t,n,e){"use strict";(function(n){const r=e(6).EventEmitter,i=e(34),o=e(3),u=e(8),s=e(41),c=e(48),a={Index:c,maxHistory:256,cachePath:"./orbit-db"};class f{constructor(t,n,e,o){this.id=n,this.dbname=e||"",this.events=new r;let u=Object.assign({},a);Object.assign(u,o),this.options=u,this._ipfs=t,this._index=new this.options.Index(this.id),this._oplog=i.create(this.id),this._lastWrite=[],this._cache=new s(this.options.cachePath,this.dbname),this.syncing=!1,this.syncQueue=[],setInterval(()=>this._processQ(),16),this.syncedOnce=!1}load(t){let n;return this._cache.load().then(()=>this._cache.get(this.dbname)).then(e=>{return e?(n=e,this.events.emit("sync",this.dbname),i.fromMultihash(this._ipfs,e,t||this.options.maxHistory).then(t=>{return this._oplog=i.join(this._oplog,t,-1,this._oplog.id),this._index.updateIndex(this._oplog),this._oplog.heads})):Promise.resolve()}).then(t=>this.events.emit("ready",this.dbname,t))}loadMore(t){const n=this._oplog.items.length;return this.events.emit("sync",this.dbname),i.expand(this._ipfs,this._oplog,t).then(t=>{const e=t.items.length-n;return this._oplog=t,this._index.updateIndex(this._oplog),this.events.emit("synced",this.dbname),e})}loadMoreFrom(t,n){if(n&&!this.loadingMore){this.loadingMore=!0,this.events.emit("sync",this.dbname);const e=new u(this._oplog.tails),r=e.intersection(new u(n.reverse()));return e.keys.includes("QmdUMFtFdZTiaSmuomvB3QzrwpGakhqzvoJgmekHLZs2s6"),i.expandFrom(this._ipfs,this._oplog,r,t).then(t=>{this._oplog=t,this._index.updateIndex(this._oplog),this.loadingMore=!1,this.events.emit("synced",this.dbname)}).catch(t=>console.error(t))}}sync(t,n,e,r=!0,i=-1,o=0){r?this.syncQueue.splice(0,0,{heads:t,tails:n,length:e,max:i,count:o}):this.syncQueue.push({heads:t,tails:n,length:e,max:i,count:o})}_processQ(){if(this.syncQueue&&this.syncQueue.length>0&&!this.syncing){this.syncing=!0;const t=this.syncQueue.shift();t.heads?this._syncFromHeads(t.heads,t.length,t.max,t.count).then(()=>this.syncing=!1).catch(t=>this.events.emit("error",t)):t.tails&&this._syncFromTails(t.tails,t.length,t.max,t.count).then(()=>this.syncing=!1).catch(t=>this.events.emit("error",t))}}_syncFromHeads(t,e,r,u){if(!t)return Promise.resolve();const s=this._oplog.items.map(t=>t.hash);if(t=t.filter(t=>void 0!==t&&null!==t&&o.isEntry(t)),0===t.length||s.find(n=>t.map(t=>t.hash).indexOf(n)>-1))return Promise.resolve();this.events.emit("sync",this.dbname);const c=t=>{const e=Object.assign({},t);return e.hash=null,this._ipfs.object.put(new n(JSON.stringify(e))).then(t=>t.toJSON().multihash)};return e=e||this.options.maxHistory,u=u||0,r=r||this.options.maxHistory,Promise.all(t.map(c)).then(n=>{return i.fromEntry(this._ipfs,t,e,s,this._onLoadProgress.bind(this))}).then(t=>{const n=this._oplog.items.length;if(t.items.length>0){const e=this._oplog.tails.filter(t=>t.next.length>0),o=this._oplog.heads;this._oplog=i.join(this._oplog,t,-1,this._oplog.id),this._index.updateIndex(this._oplog);const s=this._oplog.items.length-n;if(u+=s,this.options.syncHistory&&(r===-1||ut.next.length>0),n=t.filter(t=>!e.map(t=>t.hash).includes(t.hash)),r=(n.map(n=>0!==t.map(t=>t.hash).indexOf(n)?n:null).filter(t=>null!==t),n.reduce((n,e)=>{return 0!==t.map(t=>t.hash).indexOf(e)},!1));if(r)return void this.sync(null,[t[t.length-1]],2*this.options.maxHistory,!1,32,u);const i=this._oplog.heads,c=o.length!==i.length||i.filter((t,n)=>t.hash!==o[n].hash).length>0;c&&s>1&&this.sync(i,null,2*this.options.maxHistory,!1,32,u)}}}).then(()=>i.toMultihash(this._ipfs,this._oplog)).then(t=>{return this._cache.set(this.dbname,t).then(()=>{return this.events.emit("synced",this.dbname),t})}).catch(t=>this.events.emit("error",t))}_syncFromTails(t,n,e,r){if(!t)return Promise.resolve();n=n||this.options.maxHistory,r=r||0,e=e||this.options.maxHistory;const o=this._oplog.items.map(t=>t.hash);this.events.emit("sync",this.dbname);const u=t=>i.fromEntry(this._ipfs,t,n,o,this._onLoadProgress.bind(this));return Promise.all(t.map(u)).then(t=>{const o=this._oplog.items.length,u=this._oplog.tails.filter(t=>t.next.length>0);this._oplog.heads;if(this._oplog=i.joinAll([this._oplog].concat(t),o+n,this._oplog.id),this._index.updateIndex(this._oplog),r+=this._oplog.items.length-o,e===-1||rt.next.length>0),n=t.filter(t=>!u.map(t=>t.hash).includes(t.hash)),e=n.map(n=>0!==t.map(t=>t.hash).indexOf(n)?n:null).filter(t=>null!==t),i=n.reduce((n,e)=>{return 0!==t.map(t=>t.hash).indexOf(e)},!1);i&&this.sync(null,e,2*this.options.maxHistory,!1,32,r)}}).then(()=>i.toMultihash(this._ipfs,this._oplog)).then(t=>{return this._cache.set(this.dbname,t).then(()=>{return this.events.emit("synced",this.dbname),t})}).catch(t=>this.events.emit("error",t))}_addOperation(t){let n;if(this._oplog)return i.append(this._ipfs,this._oplog,t).then(t=>{this._oplog=t}).then(()=>i.toMultihash(this._ipfs,this._oplog)).then(t=>n=t).then(()=>this._cache.set(this.dbname,n)).then(()=>{const t=this._oplog.items[this._oplog.items.length-1];return this._lastWrite.push(n),this._index.updateIndex(this._oplog),this.events.emit("write",this.dbname,n,t,this._oplog.heads),t.hash})}_onLoadProgress(t,n,e,r){this.events.emit("load.progress",this.dbname,r)}}t.exports=f}).call(n,e(0).Buffer)},function(t,n){var e;e=function(){return this}();try{e=e||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(e=window)}t.exports=e},function(t,n){function e(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(t){return"function"==typeof t}function i(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function u(t){return void 0===t}t.exports=e,e.EventEmitter=e,e.prototype._events=void 0,e.prototype._maxListeners=void 0,e.defaultMaxListeners=10,e.prototype.setMaxListeners=function(t){if(!i(t)||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},e.prototype.emit=function(t){var n,e,i,s,c,a;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if((n=arguments[1])instanceof Error)throw n;var f=new Error('Uncaught, unspecified "error" event. ('+n+")");throw f.context=n,f}if(e=this._events[t],u(e))return!1;if(r(e))switch(arguments.length){case 1:e.call(this);break;case 2:e.call(this,arguments[1]);break;case 3:e.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),e.apply(this,s)}else if(o(e))for(s=Array.prototype.slice.call(arguments,1),a=e.slice(),i=a.length,c=0;c0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},e.prototype.on=e.prototype.addListener,e.prototype.once=function(t,n){function e(){this.removeListener(t,e),i||(i=!0,n.apply(this,arguments))}if(!r(n))throw TypeError("listener must be a function");var i=!1;return e.listener=n,this.on(t,e),this},e.prototype.removeListener=function(t,n){var e,i,u,s;if(!r(n))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(e=this._events[t],u=e.length,i=-1,e===n||r(e.listener)&&e.listener===n)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,n);else if(o(e)){for(s=u;s-- >0;)if(e[s]===n||e[s].listener&&e[s].listener===n){i=s;break}if(i<0)return this;1===e.length?(e.length=0,delete this._events[t]):e.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,n)}return this},e.prototype.removeAllListeners=function(t){var n,e;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(n in this._events)"removeListener"!==n&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events={},this}if(e=this._events[t],r(e))this.removeListener(t,e);else if(e)for(;e.length;)this.removeListener(t,e[e.length-1]);return delete this._events[t],this},e.prototype.listeners=function(t){return this._events&&this._events[t]?r(this._events[t])?[this._events[t]]:this._events[t].slice():[]},e.prototype.listenerCount=function(t){if(this._events){var n=this._events[t];if(r(n))return 1;if(n)return n.length}return 0},e.listenerCount=function(t,n){return t.listenerCount(n)}},function(t,n,e){function r(t,n){this._id=t,this._clearFn=n}var i=Function.prototype.apply;n.setTimeout=function(){return new r(i.call(setTimeout,window,arguments),clearTimeout)},n.setInterval=function(){return new r(i.call(setInterval,window,arguments),clearInterval)},n.clearTimeout=n.clearInterval=function(t){t&&t.close()},r.prototype.unref=r.prototype.ref=function(){},r.prototype.close=function(){this._clearFn.call(window,this._id)},n.enroll=function(t,n){clearTimeout(t._idleTimeoutId),t._idleTimeout=n},n.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},n._unrefActive=n.active=function(t){clearTimeout(t._idleTimeoutId);var n=t._idleTimeout;n>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},n))},e(76),n.setImmediate=setImmediate,n.clearImmediate=clearImmediate},function(t,n,e){"use strict";const r=e(32),i=e(3),o=(t,n)=>t.concat(n);class u extends r{constructor(t){super(),this._values=t||[]}get values(){return this._values.slice()}get heads(){return u.findHeads(this.values)}get tails(){return u.findTails(this.values)}get tailHashes(){return u.findTailHashes(this.values)}get keys(){return this._values.map(t=>t.hash)}get length(){return this._values.length}append(t){const n=this.values;return n.push(t),new u(n)}has(t){var n=n=>i.isEqual(n,t);return void 0!==this.values.find(n)}get(t){var n=n=>n.hash===t;return this.values.find(n)}sort(){return new u(this.values.sort(i.compare))}last(t=1){return new u(t>-1?this.values.slice(-t):this.values)}slice(t,n){return new u(this.values.slice(t||0,n||this.values.length))}replaceInFront(t){var n=this.values.slice(t.length,this.values.length);return new u(t.values.concat(n))}clone(){return new u(this.values)}merge(t){var n=[];return n=Array.isArray(t)?this.values.reduce(o,[]):this.values.concat(t.values),new u(u._uniques(n)).sort()}difference(t){var n={},e={},r=t=>e[t.hash]=!0;this.values.forEach(r);var i=(t,r)=>{var i=void 0!==e[r.hash],o=void 0!==n[r.hash];return i||o||(t.push(r),n[r.hash]=!0),t};return new u(t.values.reduce(i,[]))}intersection(t){var n={},e={},r=t=>e[t.hash]=!0;this.values.forEach(r);var i=(t,r)=>{var i=void 0!==e[r.hash],o=void 0!==n[r.hash];return i&&!o&&(t.push(r),n[r.hash]=!0),t};return new u(t.values.reduce(i,[]))}static isSet(t){return void 0!==t&&void 0!==t.values&&Array.isArray(t.values)}static sort(t){return t.sort(i.compare)}static has(t,n){var e=t=>i.isEqual(t,n);return void 0!==t.find(e)}static findHeads(t){var n=(t,n,e,r)=>{var i=e=>t[e]=n.hash;return n.next.forEach(i),t},e=t.reduce(n,{}),r=t=>void 0===e[t.hash],i=(t,n)=>t.id>n.id;return t.filter(r).sort(i)}static findTails(t){var n={},e=[],r={},o=[],s=t=>{0===t.next.length&&e.push(t);var i=e=>{n[e]||(n[e]=[]),n[e].push(t)};t.next.forEach(i),o=o.concat(t.next),r[t.hash]=!0};t.forEach(s);var c=(t,n,e,r)=>t.concat(u._uniques(n)),a=t=>void 0===r[t],f=t=>n[t];const h=o.filter(a).map(f).reduce(c,[]).concat(e);return u._uniques(h).sort(i.compare)}static findTailHashes(t){var n={},e=t=>n[t.hash]=!0,r=(t,e,r,i)=>{var o=e=>{void 0===n[e]&&t.splice(0,0,e)};return e.next.reverse().forEach(o),t};return t.forEach(e),t.reduce(r,[])}static findChildren(t,n){for(var e=[],r=t.find(t=>i.isParent(n,t)),o=n;r;)e.push(r),o=r,r=t.find(t=>i.isParent(o,t));return e=e.sort((t,n)=>t.seq>n.seq)}static _uniques(t){const n=(t,n)=>{var e=t=>i.isEqual(t,n);return void 0!==t.find(e)},e=(t,e,r,i)=>{return n(t,e)||t.push(e),t};return t.reduce(e,[])}}t.exports=u},function(t,n,e){"use strict";class r{constructor(t,n){this.id=t,this.time=n||0}tick(){return++this.time}merge(t){return this.time=Math.max(this.time,t.time),this}clone(){return new r(this.id,this.time)}static compare(t,n){var e=t.time-n.time;return 0===e&&t.id!==n.id?t.id1)for(var e=1;e=t.length?o(!0):o(null,t[e++])}}},function(t,n,e){"use strict";var r=e(20);t.exports=function(t){return t=r(t),function(n){return function e(r,i){for(var o,u=!0;u;)u=!1,o=!0,n(r,function(n,r){if(!n&&!t(r))return o?u=!0:e(n,i);i(n,r)}),o=!1}}}},function(t,n,e){"use strict";const r=e(4),i=e(44);class o extends r{constructor(t,n,e,r={}){void 0===r.Index&&Object.assign(r,{Index:i}),super(t,n,e,r)}add(t){return this._addOperation({op:"ADD",key:null,value:t})}get(t){return this.iterator({gte:t,limit:1}).collect()[0]}iterator(t){const n=this._query(t);let e=0;return{[Symbol.iterator](){return this},next(){let t={value:null,done:!0};return en}}_query(t){t||(t={});const n=t.limit?t.limit>-1?t.limit:this._index.get().length:1,e=this._index.get().slice();return t.gt||t.gte?this._read(e,t.gt?t.gt:t.gte,n,!!t.gte):this._read(e.reverse(),t.lt?t.lt:t.lte,n,t.lte||!t.lt).reverse()}_read(t,n,e,r){const i=t.map(t=>t.hash).indexOf(n);let o=Math.max(i,0);return o+=r?0:1,t.slice(o).slice(0,e)}}t.exports=o},function(t,n,e){"use strict";const r=t=>void 0!==t&&null!==t;t.exports=r},function(t,n,e){"use strict";var r=e(63),i=e(57),o=e(69);n=t.exports=e(53);for(var u in r)n[u]=r[u];for(var u in o)n[u]=o[u];for(var u in i)n[u]=i[u]},function(t,n,e){"use strict";var r=e(19);t.exports=function(t,n){return function(e,i){if(e)return r(i,e,n);if(null!=t){var o=t;t=null,i(null,o)}else i(!0)}}},function(t,n,e){"use strict";function r(t){return t}var i=e(2),o=e(13);t.exports=function(t,n){t=i(t)||r;var e={};return o(function(r){var i=t(r);return e[i]?!!n:(e[i]=!0,!n)})}},function(t,n){t.exports=function(t,n,e){t(n),e&&e(n===!0?null:n)}},function(t,n,e){function r(t){return t}var i=e(2);t.exports=function(t){return"object"==typeof t&&"function"==typeof t.test?function(n){return t.test(n)}:i(t)||r}},function(t,n,e){"use strict";const r=e(4),i=e(42);class o extends r{constructor(t,n,e,r={}){r.Index||Object.assign(r,{Index:i}),super(t,n,e,r)}get value(){return this._index.get().value}inc(t){const n=this._index.get();if(n)return n.increment(t),this._addOperation({op:"COUNTER",key:null,value:n.payload,meta:{ts:(new Date).getTime()}})}}t.exports=o},function(t,n,e){"use strict";const r=e(4),i=e(43);class o extends r{constructor(t,n,e,r){r||(r={}),r.indexBy||Object.assign(r,{indexBy:"_id"}),r.Index||Object.assign(r,{Index:i}),super(t,n,e,r)}get(t){return Object.keys(this._index._index).filter(n=>n.indexOf(t)!==-1).map(t=>this._index.get(t))}query(t){return Object.keys(this._index._index).map(t=>this._index.get(t)).filter(n=>t(n))}put(t){return this._addOperation({op:"PUT",key:t[this.options.indexBy],value:t})}del(t){return this._addOperation({op:"DEL",key:t,value:null})}}t.exports=o},function(t,n,e){"use strict";const r=e(14),i=e(45);class o extends r{constructor(t,n,e,r){r||(r={}),r.Index||Object.assign(r,{Index:i}),super(t,n,e,r)}remove(t){const n={op:"DEL",key:null,value:t};return this._addOperation(n)}}t.exports=o},function(t,n,e){"use strict";const r=e(4),i=e(46);class o extends r{constructor(t,n,e,r){let o=Object.assign({},{Index:i});Object.assign(o,r),super(t,n,e,o)}get(t){return this._index.get(t)}set(t,n){return this.put(t,n)}put(t,n){return this._addOperation({op:"PUT",key:t,value:n})}del(t){return this._addOperation({op:"DEL",key:t,value:null})}}t.exports=o},function(t,n,e){t.exports=e(47)},function(t,n,e){"use strict";function r(t){var n=t.length;if(n%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[n-2]?2:"="===t[n-1]?1:0}function i(t){return 3*t.length/4-r(t)}function o(t){var n,e,i,o,u,s,c=t.length;u=r(t),s=new h(3*c/4-u),i=u>0?c-4:c;var a=0;for(n=0,e=0;n>16&255,s[a++]=o>>8&255,s[a++]=255&o;return 2===u?(o=f[t.charCodeAt(n)]<<2|f[t.charCodeAt(n+1)]>>4,s[a++]=255&o):1===u&&(o=f[t.charCodeAt(n)]<<10|f[t.charCodeAt(n+1)]<<4|f[t.charCodeAt(n+2)]>>2,s[a++]=o>>8&255,s[a++]=255&o),s}function u(t){return a[t>>18&63]+a[t>>12&63]+a[t>>6&63]+a[63&t]}function s(t,n,e){for(var r,i=[],o=n;of?f:c+u));return 1===r?(n=t[e-1],i+=a[n>>2],i+=a[n<<4&63],i+="=="):2===r&&(n=(t[e-2]<<8)+t[e-1],i+=a[n>>10],i+=a[n>>4&63],i+=a[n<<2&63],i+="="),o.push(i),o.join("")}n.byteLength=i,n.toByteArray=o,n.fromByteArray=c;for(var a=[],f=[],h="undefined"!=typeof Uint8Array?Uint8Array:Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,d=l.length;pthis._counters[t]).reduce((t,n)=>t+n,0)}get payload(){return{id:this.id,counters:this._counters}}compare(t){return t.id===this.id&&r(t._counters,this._counters)}merge(t){Object.keys(t._counters).forEach(n=>{this._counters[n]=Math.max(this._counters[n]?this._counters[n]:0,t._counters[n])})}static from(t){return new i(t.id,t.counters)}}t.exports=i},function(t,n,e){"use strict";n.isEqual=((t,n)=>{const e=Object.getOwnPropertyNames(t),r=Object.getOwnPropertyNames(n);if(e.length!==r.length)return!1;for(let r=0;r0;)for(t=an,an=[],e=t.length,n=0;n0);tn=!0,nn=!0}function nt(){var t=en;en=[],t.forEach(function(t){t._PSD.onunhandled.call(null,t._value,t)});for(var n=hn.slice(0),e=n.length;e;)n[--e]()}function et(t){function n(){t(),hn.splice(hn.indexOf(n),1)}hn.push(n),++fn,Xt(function(){0==--fn&&nt()},[])}function rt(t){en.some(function(n){return n._value===t._value})||en.push(t)}function it(t){for(var n=en.length;n;)if(en[--n]._value===t._value)return void en.splice(n,1)}function ot(t){console.warn("Unhandled rejection: "+(t.stack||t))}function ut(t){return new q(Vt,!1,t)}function st(t,n){var e=cn;return function(){var r=X(),i=cn;try{return i!==e&&(cn=e),t.apply(this,arguments)}catch(t){n&&n(t)}finally{i!==e&&(cn=i),r&&tt()}}}function ct(t,n,e,r){var i=cn,o=Object.create(i);o.parent=i,o.ref=0,o.global=!1,++i.ref,o.finalize=function(){--this.parent.ref||this.parent.finalize()};var u=at(o,t,n,e,r);return 0===o.ref&&o.finalize(),u}function at(t,n,e,r,i){var o=cn;try{return t!==o&&(cn=t),n(e,r,i)}finally{t!==o&&(cn=o)}}function ft(n,e){var r;try{r=e.onuncatched(n)}catch(t){}if(r!==!1)try{var i,o={promise:e,reason:n};if(Pt.document&&document.createEvent?(i=document.createEvent("Event"),i.initEvent(pn,!0,!0),t(i,o)):Pt.CustomEvent&&(i=new CustomEvent(pn,{detail:o}),t(i,o)),i&&Pt.dispatchEvent&&(dispatchEvent(i),!Pt.PromiseRejectionEvent&&Pt.onunhandledrejection))try{Pt.onunhandledrejection(i)}catch(t){}i.defaultPrevented||q.on.error.fire(n,e)}catch(t){}}function ht(t,n){var e=q.reject(t);return n?e.uncaught(n):e}function lt(n,e){function s(){rn.on("versionchange",function(t){t.newVersion>0?console.warn("Another connection wants to upgrade database '"+rn.name+"'. Closing db now to resume the upgrade."):console.warn("Another connection wants to delete database '"+rn.name+"'. Closing db now to resume the delete request."),rn.close()}),rn.on("blocked",function(t){!t.newVersion||t.newVersiont}).forEach(function(t){i.push(function(){var r=Jt,i=t._cfg.dbschema;Bt(r,e),Bt(i,e),Jt=rn._dbSchema=i;var o=j(r,i);if(o.add.forEach(function(t){B(e,t[0],t[1].primKey,t[1].indexes)}),o.change.forEach(function(t){if(t.recreate)throw new Gt.Upgrade("Not yet support for changing primary key");var n=e.objectStore(t.name);t.add.forEach(function(t){U(n,t)}),t.change.forEach(function(t){n.deleteIndex(t.name),U(n,t)}),t.del.forEach(function(t){n.deleteIndex(t)})}),t._cfg.contentUpgrade)return u=!0,q.follow(function(){t._cfg.contentUpgrade(n)})}),i.push(function(n){u&&_n||M(t._cfg.dbschema,n)})}),r().then(function(){C(Jt,e)})}function j(t,n){var e={del:[],add:[],change:[]};for(var r in t)n[r]||e.del.push(r);for(r in n){var i=t[r],o=n[r];if(i){var u={name:r,def:o,recreate:!1,del:[],add:[],change:[]};if(i.primKey.src!==o.primKey.src)u.recreate=!0,e.change.push(u);else{var s=i.idxByName,c=o.idxByName;for(var a in s)c[a]||u.del.push(a);for(a in c){var f=s[a],h=c[a];f?f.src!==h.src&&u.change.push(h):u.add.push(h)}(u.del.length>0||u.add.length>0||u.change.length>0)&&e.change.push(u)}}else e.add.push([r,o])}return e}function B(t,n,e,r){var i=t.db.createObjectStore(n,e.keyPath?{keyPath:e.keyPath,autoIncrement:e.auto}:{autoIncrement:e.auto});return r.forEach(function(t){U(i,t)}),i}function C(t,n){Ot(t).forEach(function(e){n.db.objectStoreNames.contains(e)||B(n,e,t[e].primKey,t[e].indexes)})}function M(t,n){for(var e=0;e0?t:n}function pt(t,n){return zt.cmp(t,n)}function Pt(t,n){return zt.cmp(n,t)}function St(t,n){return tn?-1:t===n?0:1}function jt(t,n){return t?n?function(){return t.apply(this,arguments)&&n.apply(this,arguments)}:t:n}function Rt(){if(rn.verno=$t.version/10,rn._dbSchema=Jt={},Vt=c($t.objectStoreNames,0),0!==Vt.length){var t=$t.transaction(kt(Vt),"readonly");Vt.forEach(function(n){for(var e=t.objectStore(n),r=e.keyPath,i=r&&"string"==typeof r&&r.indexOf(".")!==-1,o=new xt(r,r||"",!1,!1,!!e.autoIncrement,r&&"string"!=typeof r,i),u=[],s=0;s0&&(sn=!1),!zt)throw new Gt.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 i=sn?zt.open(n):zt.open(n,Math.round(10*rn.verno));if(!i)throw new Gt.MissingAPI("IndexedDB API not available");i.onerror=st(gt(r)),i.onblocked=st(Dt),i.onupgradeneeded=st(function(t){if(e=i.transaction,sn&&!rn._allowEmptyDB){i.onerror=bt,e.abort(),i.result.close();var o=zt.deleteDatabase(n);o.onsuccess=o.onerror=st(function(){r(new Gt.NoSuchDatabase("Database "+n+" doesnt exist"))})}else{e.onerror=st(gt(r));m((t.oldVersion>Math.pow(2,62)?0:t.oldVersion)/10,e,r,i)}},r),i.onsuccess=st(function(){if(e=null,$t=i.result,bn.push(rn),sn)Rt();else if($t.objectStoreNames.length>0)try{Bt(Jt,$t.transaction(kt($t.objectStoreNames),nn))}catch(t){}$t.onversionchange=st(function(t){rn._vcFired=!0,rn.on("versionchange").fire(t)}),an||wt(function(t){if(t.indexOf(n)===-1)return t.push(n)}),t()},r)})]).then(function(){return lt.vip(rn.on.ready.fire)}).then(function(){return Xt=!1,rn}).catch(function(t){try{e&&e.abort()}catch(t){}return Xt=!1,rn.close(),Zt=t,ht(Zt,K)}).finally(function(){tn=!0,t()})},this.close=function(){var t=bn.indexOf(rn);if(t>=0&&bn.splice(t,1),$t){try{$t.close()}catch(t){}$t=null}qt=!1,Zt=new Gt.DatabaseClosed,Xt&&Ut(Zt),on=new q(function(t){Lt=t}),un=new q(function(t,n){Ut=n})},this.delete=function(){var t=arguments.length>0;return new q(function(e,r){function i(){rn.close();var t=zt.deleteDatabase(n);t.onsuccess=st(function(){an||wt(function(t){var e=t.indexOf(n);if(e>=0)return t.splice(e,1)}),e()}),t.onerror=st(gt(r)),t.onblocked=Dt}if(t)throw new Gt.InvalidArgument("Arguments not allowed in db.delete()");Xt?on.then(i):i()}).uncaught(K)},this.backendDB=function(){return $t},this.isOpen=function(){return null!==$t},this.hasFailed=function(){return null!==Zt},this.dynamicallyOpened=function(){return sn},this.name=n,o(this,"tables",{get:function(){return Ot(Qt).map(function(t){return Qt[t]})}}),this.on=Y(this,"error","populate","blocked","versionchange",{ready:[R,k]}),this.on.error.subscribe=L("Dexie.on.error",this.on.error.subscribe),this.on.error.unsubscribe=L("Dexie.on.error.unsubscribe",this.on.error.unsubscribe),this.on.ready.subscribe=a(this.on.ready.subscribe,function(t){return function(n,e){lt.vip(function(){tn?(Zt||q.resolve().then(n),e&&t(n)):(t(n),e||t(function t(){rn.on.ready.unsubscribe(n),rn.on.ready.unsubscribe(t)}))})}}),kn(function(){rn.on("populate").fire(rn._createTransaction(en,Vt,Jt)),rn.on("error").fire(new Error)}),this.transaction=function(t,n,e){function i(n){var i=cn;n(q.resolve().then(function(){return ct(function(){cn.transless=cn.transless||i;var n=rn._createTransaction(t,f,Jt,c);cn.trans=n,c?n.idbtrans=c.idbtrans:n.create();var o=f.map(function(t){return Qt[t]});o.push(n);var u;return q.follow(function(){if(u=e.apply(n,o))if("function"==typeof u.next&&"function"==typeof u.throw)u=_t(u);else if("function"==typeof u.then&&!r(u,"_PSD"))throw new Gt.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: "+e.toString())}).uncaught(K).then(function(){return c&&n._resolve(),n._completion}).then(function(){return u}).catch(function(t){return n._reject(t),ht(t)})})}))}var o=arguments.length;if(o<2)throw new Gt.InvalidArgument("Too few arguments");for(var u=new Array(o-1);--o;)u[o-1]=arguments[o];e=u.pop();var s=E(u),c=cn.trans;c&&c.db===rn&&t.indexOf("!")===-1||(c=null);var a=t.indexOf("?")!==-1;t=t.replace("!","").replace("?","");try{var f=s.map(function(t){var n=t instanceof H?t.name:t;if("string"!=typeof n)throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return n});if("r"==t||t==nn)t=nn;else{if("rw"!=t&&t!=en)throw new Gt.InvalidArgument("Invalid transaction mode: "+t);t=en}if(c){if(c.mode===nn&&t===en){if(!a)throw new Gt.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");c=null}c&&f.forEach(function(t){if(c&&c.storeNames.indexOf(t)===-1){if(!a)throw new Gt.SubTransaction("Table "+t+" not included in parent transaction.");c=null}})}}catch(t){return c?c._promise(null,function(n,e){e(t)}):ht(t,K)}return c?c._promise(t,i,"lock"):rn._whenReady(i)},this.table=function(t){if(An&&sn)return new G(t);if(!r(Qt,t))throw new Gt.InvalidTable("Table "+t+" does not exist");return Qt[t]},i(H.prototype,{_trans:function(t,n,e){var r=cn.trans;return r&&r.db===rn?r._promise(t,n,e):z(t,[this.name],n)},_idbstore:function(t,n,e){function r(t,e,r){n(t,e,r.idbtrans.objectStore(o),r)}if(An)return new q(n);var i=cn.trans,o=this.name;return i&&i.db===rn?i._promise(t,r,e):z(t,[this.name],r)},get:function(t,n){var e=this;return this._idbstore(nn,function(n,r,i){An&&n(e.schema.instanceTemplate);var o=i.get(t);o.onerror=gt(r),o.onsuccess=st(function(){n(e.hook.reading.fire(o.result))},r)}).then(n)},where:function(t){return new Q(this,t)},count:function(t){return this.toCollection().count(t)},offset:function(t){return this.toCollection().offset(t)},limit:function(t){return this.toCollection().limit(t)},reverse:function(){return this.toCollection().reverse()},filter:function(t){return this.toCollection().and(t)},each:function(t){return this.toCollection().each(t)},toArray:function(t){return this.toCollection().toArray(t)},orderBy:function(t){return new this._collClass(new Q(this,t))},toCollection:function(){return new this._collClass(new Q(this))},mapToClass:function(t,n){this.schema.mappedClass=t;var e=Object.create(t.prototype);n&&dt(e,n),this.schema.instanceTemplate=e;var i=function(n){if(!n)return n;var e=Object.create(t.prototype);for(var i in n)if(r(n,i))try{e[i]=n[i]}catch(t){}return e};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=i,this.hook("reading",i),t},defineClass:function(t){return this.mapToClass(lt.defineClass(t),t)}}),u(G).from(H).extend({bulkDelete:function(t){return this.hook.deleting.fire===k?this._idbstore(en,function(n,e,r,i){n(W(r,i,t,!1,k))}):this.where(":id").anyOf(t).delete().then(function(){})},bulkPut:function(t,n){var e=this;return this._idbstore(en,function(r,i,o){if(!o.keyPath&&!e.schema.primKey.auto&&!n)throw new Gt.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument");if(o.keyPath&&n)throw new Gt.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(n&&n.length!==t.length)throw new Gt.InvalidArgument("Arguments objects and keys must have the same length");if(0===t.length)return r();var u,s,c=function(t){0===a.length?r(t):i(new F(e.name+".bulkPut(): "+a.length+" of "+f+" operations failed",a))},a=[],f=t.length,h=e;if(e.hook.creating.fire===k&&e.hook.updating.fire===k){s=J(a);for(var l=0,d=t.length;l=0;--i){var o=v[i];(null==o||g[o])&&(e.push(t[i]),n&&r.push(o),null!=o&&(g[o]=null))}return e.reverse(),n&&r.reverse(),h.bulkAdd(e,r)}).then(function(t){var n=v[v.length-1];return null!=n?n:t}):h.bulkAdd(t)).then(c).catch(F,function(t){a=a.concat(t.failures),c()}).catch(i)}},"locked")},bulkAdd:function(t,n){var e=this,r=this.hook.creating.fire;return this._idbstore(en,function(i,o,u,s){function c(t){0===l.length?i(t):o(new F(e.name+".bulkAdd(): "+l.length+" of "+p+" operations failed",l))}if(!u.keyPath&&!e.schema.primKey.auto&&!n)throw new Gt.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument");if(u.keyPath&&n)throw new Gt.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(n&&n.length!==t.length)throw new Gt.InvalidArgument("Arguments objects and keys must have the same length");if(0===t.length)return i();var a,f,h,l=[],p=t.length;if(r!==k){var d,m=u.keyPath;f=J(l,null,!0),h=yt(null),v(function(){for(var e=0,i=t.length;e0&&!this._locked();){var t=this._blockedFuncs.shift();try{at(t[1],t[0])}catch(t){}}return this},_locked:function(){return this._reculock&&cn.lockOwnerFor!==this},create:function(t){var n=this;if(h(!this.idbtrans),!t&&!$t)switch(Zt&&Zt.name){case"DatabaseClosedError":throw new Gt.DatabaseClosed(Zt);case"MissingAPIError":throw new Gt.MissingAPI(Zt.message,Zt);default:throw new Gt.OpenFailed(Zt)}if(!this.active)throw new Gt.TransactionInactive;return h(null===this._completion._state),t=this.idbtrans=t||$t.transaction(kt(this.storeNames),this.mode),t.onerror=st(function(e){bt(e),n._reject(t.error)}),t.onabort=st(function(t){bt(t),n.active&&n._reject(new Gt.Abort),n.active=!1,n.on("abort").fire(t)}),t.oncomplete=st(function(){n.active=!1,n._resolve()}),this},_promise:function(t,n,e){var r=this,i=r._locked()?new q(function(i,o){r._blockedFuncs.push([function(){r._promise(t,n,e).then(i,o)},cn])}):ct(function(){var i=r.active?new q(function(i,o){if(t===en&&r.mode!==en)throw new Gt.ReadOnly("Transaction is readonly");!r.idbtrans&&t&&r.create(),e&&r._lock(),n(i,o,r)}):ht(new Gt.TransactionInactive);return r.active&&e&&i.finally(function(){r._unlock()}),i});return i._lib=!0,i.uncaught(K)},abort:function(){this.active&&this._reject(new Gt.Abort),this.active=!1},tables:{get:L("Transaction.tables",function(){return p(this.storeNames,function(t){return[t,Qt[t]]})},"Use db.tables()")},complete:L("Transaction.complete()",function(t){return this.on("complete",t)}),error:L("Transaction.error()",function(t){return this.on("error",t)}),table:L("Transaction.table()",function(t){if(this.storeNames.indexOf(t)===-1)throw new Gt.InvalidTable("Table "+t+" not in transaction");return Qt[t]})}),i(Q.prototype,function(){function t(t,n,e){var r=t instanceof Q?new t._ctx.collClass(t):t;return r._ctx.error=e?new e(n):new TypeError(n),r}function n(t){return new t._ctx.collClass(t,function(){return Ht.only("")}).limit(0)}function e(t){return"next"===t?function(t){return t.toUpperCase()}:function(t){return t.toLowerCase()}}function r(t){return"next"===t?function(t){return t.toLowerCase()}:function(t){return t.toUpperCase()}}function i(t,n,e,r,i,o){for(var u=Math.min(t.length,r.length),s=-1,c=0;c=0?t.substr(0,s)+n[s]+e.substr(s+1):null;i(t[c],a)<0&&(s=c)}return u0)&&(s=a)}return n(null!==s?function(){t.continue(s+v)}:e),!1}),g}return{between:function(e,r,i,o){i=i!==!1,o=o===!0;try{return ot(e,r)>0||0===ot(e,r)&&(i||o)&&(!i||!o)?n(this):new this._ctx.collClass(this,function(){return Ht.bound(e,r,!i,!o)})}catch(n){return t(this,gn)}},equals:function(t){return new this._ctx.collClass(this,function(){return Ht.only(t)})},above:function(t){return new this._ctx.collClass(this,function(){return Ht.lowerBound(t,!0)})},aboveOrEqual:function(t){return new this._ctx.collClass(this,function(){return Ht.lowerBound(t)})},below:function(t){return new this._ctx.collClass(this,function(){return Ht.upperBound(t,!0)})},belowOrEqual:function(t){return new this._ctx.collClass(this,function(){return Ht.upperBound(t)})},startsWith:function(n){return"string"!=typeof n?t(this,mn):this.between(n,n+vn,!0,!0)},startsWithIgnoreCase:function(t){return""===t?this.startsWith(t):o(this,function(t,n){return 0===t.indexOf(n[0])},[t],vn)},equalsIgnoreCase:function(t){return o(this,function(t,n){return t===n[0]},[t],"")},anyOfIgnoreCase:function(){var t=x.apply(Ct,arguments);return 0===t.length?n(this):o(this,function(t,n){return n.indexOf(t)!==-1},t,"")},startsWithAnyOfIgnoreCase:function(){var t=x.apply(Ct,arguments);return 0===t.length?n(this):o(this,function(t,n){return n.some(function(n){return 0===t.indexOf(n)})},t,vn)},anyOf:function(){var e=x.apply(Ct,arguments),r=pt;try{e.sort(r)}catch(n){return t(this,gn)}if(0===e.length)return n(this);var i=new this._ctx.collClass(this,function(){return Ht.bound(e[0],e[e.length-1])});i._ondirectionchange=function(t){r="next"===t?pt:Pt,e.sort(r)};var o=0;return i._addAlgorithm(function(t,n,i){for(var u=t.key;r(u,e[o])>0;)if(++o===e.length)return n(i),!1;return 0===r(u,e[o])||(n(function(){t.continue(e[o])}),!1)}),i},notEqual:function(t){return this.inAnyRange([[-(1/0),t],[t,yn]],{includeLowers:!1,includeUppers:!1})},noneOf:function(){var n=x.apply(Ct,arguments);if(0===n.length)return new this._ctx.collClass(this);try{n.sort(pt)}catch(n){return t(this,gn)}var e=n.reduce(function(t,n){return t?t.concat([[t[t.length-1][1],n]]):[[-(1/0),n]]},null);return e.push([n[n.length-1],yn]),this.inAnyRange(e,{includeLowers:!1,includeUppers:!1})},inAnyRange:function(e,r){function i(t,n){for(var e=0,r=t.length;e0){i[0]=ut(i[0],n[0]),i[1]=ft(i[1],n[1]);break}}return e===r&&t.push(n),t}function o(t,n){return h(t[0],n[0])}function u(t){return!p(t)&&!d(t)}var s=this._ctx;if(0===e.length)return n(this);if(!e.every(function(t){return void 0!==t[0]&&void 0!==t[1]&&pt(t[0],t[1])<=0}))return t(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Gt.InvalidArgument);var c,a=!r||r.includeLowers!==!1,f=r&&r.includeUppers===!0,h=pt;try{c=e.reduce(i,[]),c.sort(o)}catch(n){return t(this,gn)}var l=0,p=f?function(t){return pt(t,c[l][1])>0}:function(t){return pt(t,c[l][1])>=0},d=a?function(t){return Pt(t,c[l][0])>0}:function(t){return Pt(t,c[l][0])>=0},v=p,y=new s.collClass(this,function(){return Ht.bound(c[0][0],c[c.length-1][1],!a,!f)});return y._ondirectionchange=function(t){"next"===t?(v=p,h=pt):(v=d,h=Pt),c.sort(o)},y._addAlgorithm(function(t,n,e){for(var r=t.key;v(r);)if(++l===c.length)return n(e),!1;return!!u(r)||0!==ot(r,c[l][1])&&0!==ot(r,c[l][0])&&(n(function(){h===pt?t.continue(c[l][0]):t.continue(c[l][1])}),!1)}),y},startsWithAnyOf:function(){var e=x.apply(Ct,arguments);return e.every(function(t){return"string"==typeof t})?0===e.length?n(this):this.inAnyRange(e.map(function(t){return[t,t+vn]})):t(this,"startsWithAnyOf() only works with strings")}}}),i($.prototype,function(){function n(t,n){t.filter=jt(t.filter,n)}function e(t,n,e){var r=t.replayFilter;t.replayFilter=r?function(){return jt(r(),n())}:n,t.justLimit=e&&!r}function i(t,n){t.isMatch=jt(t.isMatch,n)}function o(t,n){if(t.isPrimKey)return n;var e=t.table.schema.idxByName[t.index];if(!e)throw new Gt.Schema("KeyPath "+t.index+" on object store "+n.name+" is not indexed");return n.index(e.name)}function u(t,n){var e=o(t,n);return t.keysOnly&&"openKeyCursor"in e?e.openKeyCursor(t.range||null,t.dir+t.unique):e.openCursor(t.range||null,t.dir+t.unique)}function s(t,n,e,i,o){var s=t.replayFilter?jt(t.filter,t.replayFilter()):t.filter;t.or?function(){function c(){2==++h&&e()}function a(t,e,o){if(!s||s(e,o,c,i)){var u=e.primaryKey.toString();r(f,u)||(f[u]=!0,n(t,e,o))}}var f={},h=0;t.or._iterate(a,c,i,o),rt(u(t,o),t.algorithm,a,c,i,!t.keysOnly&&t.valueMapper)}():rt(u(t,o),jt(t.algorithm,s),n,e,i,!t.keysOnly&&t.valueMapper)}function c(t){return t.table.schema.instanceTemplate}return{_read:function(t,n){var e=this._ctx;return e.error?e.table._trans(null,function(t,n){n(e.error)}):e.table._idbstore(nn,t).then(n)},_write:function(t){var n=this._ctx;return n.error?n.table._trans(null,function(t,e){e(n.error)}):n.table._idbstore(en,t,"locked")},_addAlgorithm:function(t){var n=this._ctx;n.algorithm=jt(n.algorithm,t)},_iterate:function(t,n,e,r){return s(this._ctx,t,n,e,r)},clone:function(n){var e=Object.create(this.constructor.prototype),r=Object.create(this._ctx);return n&&t(r,n),e._ctx=r,e},raw:function(){return this._ctx.valueMapper=null,this},each:function(t){var n=this._ctx;if(An){var e=c(n),r=n.table.schema.primKey.keyPath;t(e,{key:y(e,n.index?n.table.schema.idxByName[n.index].keyPath:r),primaryKey:y(e,r)})}return this._read(function(e,r,i){s(n,t,e,r,i)})},count:function(t){if(An)return q.resolve(0).then(t);var n=this._ctx;if(Z(n,!0))return this._read(function(t,e,r){var i=o(n,r),u=n.range?i.count(n.range):i.count();u.onerror=gt(e),u.onsuccess=function(e){t(Math.min(e.target.result,n.limit))}},t);var e=0;return this._read(function(t,r,i){s(n,function(){return++e,!1},function(){t(e)},r,i)},t)},sortBy:function(t,n){function e(t,n){return n?e(t[i[n]],n-1):t[o]}function r(t,n){var r=e(t,u),i=e(n,u);return ri?s:0}var i=t.split(".").reverse(),o=i[0],u=i.length-1,s="next"===this._ctx.dir?1:-1;return this.toArray(function(t){return t.sort(r)}).then(n)},toArray:function(t){var n=this._ctx;return this._read(function(t,e,r){if(An&&t([c(n)]),Nt&&"next"===n.dir&&Z(n,!0)&&n.limit>0){var i=n.table.hook.reading.fire,u=o(n,r),a=n.limit<1/0?u.getAll(n.range,n.limit):u.getAll(n.range);a.onerror=gt(e),a.onsuccess=i===A?vt(t):st(vt(function(n){try{t(n.map(i))}catch(t){e(t)}}))}else{var f=[];s(n,function(t){f.push(t)},function(){t(f)},e,r)}},t)},offset:function(t){var n=this._ctx;return t<=0?this:(n.offset+=t,Z(n)?e(n,function(){var n=t;return function(t,e){return 0===n||(1===n?(--n,!1):(e(function(){t.advance(n),n=0}),!1))}}):e(n,function(){var n=t;return function(){return--n<0}}),this)},limit:function(t){return this._ctx.limit=Math.min(this._ctx.limit,t),e(this._ctx,function(){var n=t;return function(t,e,r){return--n<=0&&e(r),n>=0}},!0),this},until:function(t,e){var r=this._ctx;return An&&t(c(r)),n(this._ctx,function(n,r,i){return!t(n.value)||(r(i),e)}),this},first:function(t){return this.limit(1).toArray(function(t){return t[0]}).then(t)},last:function(t){return this.reverse().first(t)},filter:function(t){return An&&t(c(this._ctx)),n(this._ctx,function(n){return t(n.value)}),i(this._ctx,t),this},and:function(t){return this.filter(t)},or:function(t){return new Q(this._ctx.table,t,this)},reverse:function(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},desc:function(){return this.reverse()},eachKey:function(t){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(n,e){t(e.key,e)})},eachUniqueKey:function(t){return this._ctx.unique="unique",this.eachKey(t)},eachPrimaryKey:function(t){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(n,e){t(e.primaryKey,e)})},keys:function(t){var n=this._ctx;n.keysOnly=!n.isMatch;var e=[];return this.each(function(t,n){e.push(n.key)}).then(function(){return e}).then(t)},primaryKeys:function(t){var n=this._ctx;if(Nt&&"next"===n.dir&&Z(n,!0)&&n.limit>0)return this._read(function(t,e,r){var i=o(n,r),u=n.limit<1/0?i.getAllKeys(n.range,n.limit):i.getAllKeys(n.range);u.onerror=gt(e),u.onsuccess=vt(t)}).then(t);n.keysOnly=!n.isMatch;var e=[];return this.each(function(t,n){e.push(n.primaryKey)}).then(function(){return e}).then(t)},uniqueKeys:function(t){return this._ctx.unique="unique",this.keys(t)},firstKey:function(t){return this.limit(1).keys(function(t){return t[0]}).then(t)},lastKey:function(t){return this.reverse().firstKey(t)},distinct:function(){var t=this._ctx,e=t.index&&t.table.schema.idxByName[t.index];if(!e||!e.multi)return this;var i={};return n(this._ctx,function(t){var n=t.primaryKey.toString(),e=r(i,n);return i[n]=!0,!e}),this}}}),u(X).from($).extend({modify:function(n){var e=this,i=this._ctx,o=i.table.hook,u=o.updating.fire,s=o.deleting.fire;return An&&"function"==typeof n&&n.call({value:i.table.schema.instanceTemplate},i.table.schema.instanceTemplate),this._write(function(i,o,c,a){function f(t,n){function e(t){return T.push(t),P.push(i.primKey),l(),!0}S=n.primaryKey;var i={primKey:n.primaryKey,value:t,onsuccess:null,onerror:null};if(p.call(i,t,i)!==!1){var o=!r(i,"value");++E,v(function(){var t=o?n.delete():n.update(i.value);t._hookCtx=i,t.onerror=mt(e),t.onsuccess=yt(function(){++A,l()})},e)}else i.onsuccess&&i.onsuccess(i.value)}function h(t){return t&&(T.push(t),P.push(S)),o(new N("Error modifying one or more objects",T,A,P))}function l(){O&&A+T.length===E&&(T.length>0?h():i(A))}var p;if("function"==typeof n)p=u===k&&s===k?n:function(t){var e=w(t);if(n.call(this,t,this)===!1)return!1;if(r(this,"value")){var i=_(e,this.value),o=u.call(this,i,this.primKey,e,a);o&&(t=this.value,Ot(o).forEach(function(n){g(t,n,o[n])}))}else s.call(this,this.primKey,t,a)};else if(u===k){var d=Ot(n),m=d.length;p=function(t){for(var e=!1,r=0;r99?t.push(n.concat(e)):t[o(t)]=n.concat(u(t).concat(e)),t}if(c)return e(c);var l=r.table;i.resolve(v(d(100,10),f(a,h,100,e)))}),i):(e(new Error("Missing key")),i)}},{key:"read",value:function(t){var n=this,e=h();return t?(this.exists(t,function(r,i){return r?e.end(r):i?void n.table.where("key").equals(t).each(function(t){return e.push(l(t.blob))}).catch(function(t){return e.end(t)}).then(function(){return e.end()}):e.end(new Error("Not found"))}),e):(e.end(new Error("Missing key")),e)}},{key:"exists",value:function(t,n){if(n=n||function(){},!t)return n(new Error("Missing key"));this.table.where("key").equals(t).count().then(function(t){return n(null,Boolean(t))}).catch(n)}},{key:"remove",value:function(t,n){if(n=n||function(){},!t)return n(new Error("Missing key"));var e=this.table.where("key").equals(t);e.count(function(t){return t>0?e.delete():null}).then(function(){return n()}).catch(n)}},{key:"table",get:function(){return this.db[this.path]}}]),t}()}).call(n,e(0).Buffer)},function(t,n){n.read=function(t,n,e,r,i){var o,u,s=8*i-r-1,c=(1<>1,f=-7,h=e?i-1:0,l=e?-1:1,p=t[n+h];for(h+=l,o=p&(1<<-f)-1,p>>=-f,f+=s;f>0;o=256*o+t[n+h],h+=l,f-=8);for(u=o&(1<<-f)-1,o>>=-f,f+=r;f>0;u=256*u+t[n+h],h+=l,f-=8);if(0===o)o=1-a;else{if(o===c)return u?NaN:1/0*(p?-1:1);u+=Math.pow(2,r),o-=a}return(p?-1:1)*u*Math.pow(2,o-r)},n.write=function(t,n,e,r,i,o){var u,s,c,a=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:o-1,d=r?1:-1,v=n<0||0===n&&1/n<0?1:0;for(n=Math.abs(n),isNaN(n)||n===1/0?(s=isNaN(n)?1:0,u=f):(u=Math.floor(Math.log(n)/Math.LN2),n*(c=Math.pow(2,-u))<1&&(u--,c*=2),n+=u+h>=1?l/c:l*Math.pow(2,1-h),n*c>=2&&(u++,c/=2),u+h>=f?(s=0,u=f):u+h>=1?(s=(n*c-1)*Math.pow(2,i),u+=h):(s=n*Math.pow(2,h-1)*Math.pow(2,i),u=0));i>=8;t[e+p]=255&s,p+=d,s/=256,i-=8);for(u=u<0;t[e+p]=255&u,p+=d,u/=256,a-=8);t[e+p-d]|=128*v}},function(t,n,e){"use strict";class r{constuctor(t){}append(t){}merge(t){}get(t){}has(t){}get values(){}get length(){}}t.exports=r},function(t,n,e){"use strict";const r=e(50),i=e(49),o=e(3);class u{static fetchParallel(t,n,e,r=[],o){const s=n=>u.fetchAll(t,n,e,r),c=(t,n)=>t.concat(n),a=t=>t.reduce(c,[]);return i(n,s,{concurrency:Math.max(o||n.length,1)}).then(a)}static fetchAll(t,n,e,i=[],u=2e3){let s=[],c={},a=Array.isArray(n)?n.slice():[n];const f=t=>a.push(t);var h=t=>c[t.hash]=t;return i.forEach(h),r(()=>{return a.length>0&&(s.length{const n=a.shift();if(c[n]){const t=c[n];return t.next.forEach(f),Promise.resolve()}return new Promise((e,r)=>{const i=setTimeout(e,u),a=t=>{clearTimeout(i),o.isEntry(t)&&(t.next.forEach(f),s.push(t),c[n]=t)};o.fromMultihash(t,n).then(a).then(e)})}).then(()=>s)}}t.exports=u},function(t,n,e){"use strict";const r=e(15),i=e(35),o=e(33),u=e(3),s=e(8),c=e(9),a=()=>new Error("Ipfs instance not defined"),f=()=>new Error("Log instance not defined"),h=()=>new Error("Given argument is not an instance of Log");class l{static create(t,n,e,o,a=-1,f=!1){if(r(n)&&!s.isSet(n)&&!Array.isArray(n))throw new Error(`'entries' argument must be an EntrySet or an array of Entry instances`);if(r(e)&&!Array.isArray(e))throw new Error(`'heads' argument must be an array`);if(s.isSet(n)||(n=new s(n)),f||(n=n.sort()),a>-1&&(n=n.slice(-a)),e=r(e)?e.map(t=>u.isEntry(t)?t:n.get(t)):n.heads,!r(t)){if(!r(n)||0===n.length)throw new Error("Log requires an id");t=o?o.id:n.get(e[0].hash).clock.id}if(!r(o)&&r(n)){const e=n.values.slice(-1)[0];o=new c(t,e?e.clock.time:null)}return new i(t,n,e,o)}static append(t,n,e){if(!r(t))throw a();if(!r(n))throw f();if(!l.isLog(n))throw h();n.clock.tick();const i=t=>n.append(t);return u.create(t,n.id,null,e,n.heads,n.clock).then(i)}static join(t,n,e,i){if(!r(t)||!r(n))throw f();if(!l.isLog(t))throw h();if(!l.isLog(n))throw h();e=e&&e>-1?e:t.length+n.length,i=i?i:[t,n].sort((t,n)=>t.id>n.id)[0].id;const o=t.entries.merge(n.entries),u=[t.clock,n.clock].sort((t,n)=>t.id===i?-1:t.id>n.id);let s=new c(i,u[0].time);return s.merge(u[1]),l.create(i,o,null,s,e)}static joinAll(t,n){return t.reduce((t,e,r)=>{return t?l.join(t,e,n):e},null)}static isLog(t){return void 0!==t.id&&void 0!==t.heads&&void 0!==t.values}static expand(t,n,e=-1){if(!r(t))throw a();if(!r(n))throw f();if(!l.isLog(n))throw h();return 0===n.tailHashes.length?Promise.resolve(l.create(n.id,n.entries,n.heads,n.clock,-1,!0)):o.fetchParallel(t,n.tailHashes,e,n.values).then(t=>new s(t)).then(t=>{const r=e>-1?n.entries.length+e:-1,i=n.entries.merge(t).last(r),o=i.difference(n.entries),u=n.entries.difference(i),s=n.entries.intersection(i),c=r-(s.length+o.length),a=u.last(c),f=s.merge(a).merge(o);return l.create(n.id,f,null,n.clock,r)})}static expandFrom(t,n,e,i=-1){if(!r(t))throw a();if(!r(n))throw f();if(!r(e))throw new Error(`'entries' must be given as argument`);if(!l.isLog(n))throw h();Array.isArray(e)||s.isSet(e)||(e=[e]),s.isSet(e)||(e=new s(e));const u=e.values.map(t=>t.next).filter(t=>t.length>0);return 0===u.length?Promise.resolve(l.create(n.id,n.entries,n.heads,n.clock,-1,!0)):o.fetchParallel(t,u,i,n.values,u.length).then(t=>new s(t)).then(t=>{const e=i>-1?n.entries.length+i:-1,r=n.entries.merge(t.slice(0,i));return l.create(n.id,r,null,n.clock,e)})}static fromEntry(t,n,e=-1,i,c){if(!r(t))throw a();if(!r(n))throw new Error("'sourceEntries' must be defined");if(!s.isSet(n)&&!Array.isArray(n)&&!u.isEntry(n))throw new Error(`'sourceEntries' argument must be an EntrySet, an array of Entry instances or a single Entry`);n&&!s.isSet(n)&&(Array.isArray(n)||(n=[n]),n=new s(n)),e=e>-1?Math.max(e,n.length):e;const f=i?i.map(t=>t.hash?t.hash:t):i;return o.fetchParallel(t,n.keys,e,f).then(t=>new s(t)).then(t=>{const r=n.merge(t).last(e),i=r.difference(n),o=r.replaceInFront(i);return l.create(null,o)})}static fromMultihash(t,n,e=-1,i,u){if(!r(t))throw a();if(!r(n))throw new Error(`Invalid hash: ${n}`);return t.object.get(n,{enc:"base58"}).then(t=>JSON.parse(t.toJSON().data)).then(n=>{if(!n.heads||!n.id)throw h();return o.fetchAll(t,n.heads,e,i).then(t=>l.create(n.id,t,n.heads))})}static toMultihash(t,n){if(!r(t))throw a();if(!r(n))throw f();if(!l.isLog(n))throw h();if(n.values.length<1)throw new Error(`Can't serialize an empty log`);if(n.heads.length<1)throw new Error(`Can't serialize a log without heads`);return t.object.put(n.toBuffer()).then(t=>t.toJSON().multihash)}}t.exports=l},function(t,n,e){"use strict";(function(n){const r=e(8),i=e(9),o=()=>(new Date).getTime();class u{constructor(t,n,e,u){this._id=t||o(),this._clock=u||new i(this.id),this._entries=n||new r,this._heads=e||this.entries.heads}get id(){return this._id}get clock(){return this._clock}get items(){return this.entries.values}get values(){return this.entries.values}get entries(){return this._entries}get heads(){return this._heads}get tails(){return this.entries.tails}get tailHashes(){return this.entries.tailHashes}get length(){return this.entries.length}get(t){return this.entries.get(t)}append(t){const n=this.entries.append(t);return new u(this.id,n,[t],this.clock)}toJSON(){return{id:this.id,heads:this.heads.map(t=>t.hash)}}toBuffer(){return new n(JSON.stringify(this.toJSON()))}toString(){return this.items.slice().reverse().map((t,n)=>{const e=r.findChildren(this.entries.values,t),i=e.length;let o=new Array(Math.max(i-1,0));return o=i>1?o.fill(" "):o,o=i>0?o.concat(["└─"]):o,o.join("")+t.payload}).join("\n")}}t.exports=u}).call(n,e(0).Buffer)},function(t,n){function e(t){return r(t)||i(t)}function r(t){return t instanceof Int8Array||t instanceof Int16Array||t instanceof Int32Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Uint16Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array}function i(t){return u[o.call(t)]}t.exports=e,e.strict=r,e.loose=i;var o=Object.prototype.toString,u={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0}},function(t,n){var e={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==e.call(t)}},function(t,n,e){(function(n){t.exports=function(){function t(t,n){return function(r){return function(){e(t,n),r&&r.apply(null,arguments)}}}function e(n,e){var r=s[n].indexOf(e);~r&&(s[n].splice(r,1),o(n)?u(function(){s[n][0](t(n,s[n][0]))}):delete s[n])}function r(t,n){return o(t)?(s[t].push(n),!1):(s[t]=[n],!0)}function i(n,i){function o(t){return function(){var n=[].slice.call(arguments);for(var r in s)e(r,s[r]);t.apply(this,n)}}if(Array.isArray(n)){var u=n.length,s={};return void n.forEach(function(t){function n(){e++||--u||i(o)}var e=0;s[t]=n,r(t,n)&&n()})}r(n,i)&&i(t(n,i))}function o(t){return!!Array.isArray(s[t])&&!!s[t].length}var u=void 0===n?setTimeout:n,s={};return i.isLocked=o,i}}).call(n,e(7).setImmediate)},function(t,n,e){"use strict";(function(n){const r=e(81),i=e(80).format,o=e(6).EventEmitter;let u=!!n.version;const s={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR",NONE:"NONE"};let c=s.DEBUG,a=null,f=new o,h={Black:0,Red:1,Green:2,Yellow:3,Blue:4,Magenta:5,Cyan:6,Grey:7,White:9,Default:9};u||(h={Black:"Black",Red:"IndianRed",Green:"LimeGreen",Yellow:"Orange",Blue:"RoyalBlue",Magenta:"Orchid",Cyan:"SkyBlue",Grey:"DimGrey",White:"White",Default:"Black"});const l=[h.Cyan,h.Green,h.Yellow,h.Red,h.Default],p={useColors:!0,color:h.Default,showTimestamp:!0,showLevel:!0,filename:a,appendFile:!0};class d{constructor(t,n){this.category=t;let e={};Object.assign(e,p),Object.assign(e,n),this.options=e}debug(){this._shouldLog(s.DEBUG)&&this._write(s.DEBUG,i.apply(null,arguments))}log(){this._shouldLog(s.DEBUG)&&this.debug.apply(this,arguments)}info(){this._shouldLog(s.INFO)&&this._write(s.INFO,i.apply(null,arguments))}warn(){this._shouldLog(s.WARN)&&this._write(s.WARN,i.apply(null,arguments))}error(){this._shouldLog(s.ERROR)&&this._write(s.ERROR,i.apply(null,arguments))}_write(t,n){(this.options.filename||a)&&!this.fileWriter&&u&&(this.fileWriter=r.openSync(this.options.filename||a,this.options.appendFile?"a+":"w+"));let e=this._format(t,n),i=this._createLogMessage(t,n),o=this._createLogMessage(t,n,e.timestamp,e.level,e.category,e.text);this.fileWriter&&u&&r.writeSync(this.fileWriter,i+"\n",null,"utf-8"),u||!this.options.useColors?(console.log(o),f.emit("data",this.category,t,n)):t===s.ERROR?this.options.showTimestamp&&this.options.showLevel?console.error(o,e.timestamp,e.level,e.category,e.text):this.options.showTimestamp&&!this.options.showLevel?console.error(o,e.timestamp,e.category,e.text):!this.options.showTimestamp&&this.options.showLevel?console.error(o,e.level,e.category,e.text):console.error(o,e.category,e.text):this.options.showTimestamp&&this.options.showLevel?console.log(o,e.timestamp,e.level,e.category,e.text):this.options.showTimestamp&&!this.options.showLevel?console.log(o,e.timestamp,e.category,e.text):!this.options.showTimestamp&&this.options.showLevel?console.log(o,e.level,e.category,e.text):console.log(o,e.category,e.text)}_format(t,n){let e="",r="",i="",o=": ";if(this.options.useColors){const n=Object.keys(s).map(t=>s[t]).indexOf(t),c=this.options.color;u?(this.options.showTimestamp&&(e="[3"+h.Grey+"m"),this.options.showLevel&&(r="[3"+l[n]+";22m"),i="[3"+c+";1m",o=": "):(this.options.showTimestamp&&(e="color:"+h.Grey),this.options.showLevel&&(r="color:"+l[n]),i="color:"+c+"; font-weight: bold")}return{timestamp:e,level:r,category:i,text:o}}_createLogMessage(t,n,e,r,i,o){e=e||"",r=r||"",i=i||"",o=o||": ",!u&&this.options.useColors&&(this.options.showTimestamp&&(e="%c"),this.options.showLevel&&(r="%c"),i="%c",o=": %c");let c="";return this.options.showTimestamp&&(c+=(new Date).toISOString()+" "),c=e+c,this.options.showLevel&&(c+=r+"["+t+"]"+(t===s.INFO||t===s.WARN?" ":"")+" "),c+=i+this.category,c+=o+n}_shouldLog(t){let e=void 0!==n&&void 0!==n.env&&void 0!==n.env.LOG?n.env.LOG.toUpperCase():null;e="undefined"!=typeof window&&window.LOG?window.LOG.toUpperCase():e;const r=e||c,i=Object.keys(s).map(t=>s[t]);return i.indexOf(t)>=i.indexOf(r)}}t.exports={Colors:h,LogLevels:s,setLogLevel:t=>{c=t},setLogfile:t=>{a=t},create:(t,n)=>{return new d(t,n)},forceBrowserMode:t=>u=!t,events:f}}).call(n,e(10))},function(t,n){t.exports=function(t){return function n(e,r,i){var o=!0,u=!1;do{u=!0,o=!1,t.call(function(t,s,c){u?(e=t,r=s,i=c,o=!0):n(t,s,c)},e,r,i),u=!1}while(o)}}},function(t,n,e){"use strict";(function(n){const r=e(16),i=e(30),o=e(38);class u{constructor(t,n=""){this.path=t||"./orbit-db",this.filename=n+"orbit.db",this._store=new i(this.path),this._cache={},this._lock=new o}get(t){return this._cache[t]}set(t,n){return new Promise((e,i)=>{if(this._cache[t]===n)return e(n);this._cache[t]=n,this._lock(this.filename,t=>{r(r.values([this._cache]),r.map(t=>JSON.stringify(t,null,2)),this._store.write(this.filename,t(t=>{if(t)return i(t);e(n)})))})})}load(){return this._cache={},new Promise((t,e)=>{this._store.exists(this.filename,(i,o)=>{if(i||!o)return t();this._lock(this.filename,i=>{r(this._store.read(this.filename),r.collect(i((r,i)=>{if(r)return e(r);try{this._cache=JSON.parse(n.concat(i).toString()||"{}")}catch(t){return e(t)}t()})))})})})}reset(){this._cache={},this._store=null}}t.exports=u}).call(n,e(0).Buffer)},function(t,n,e){"use strict";const r=e(27);class i{constructor(t){this._counter=new r(t)}get(){return this._counter}updateIndex(t){this._counter&&t.items.filter(t=>t&&"COUNTER"===t.payload.op).map(t=>r.from(t.payload.value)).forEach(t=>this._counter.merge(t))}}t.exports=i},function(t,n,e){"use strict";class r{constructor(){this._index={}}get(t){return this._index[t]}updateIndex(t){t.items.slice().reverse().reduce((t,n)=>{return t.indexOf(n.payload.key)===-1&&(t.push(n.payload.key),"PUT"===n.payload.op?this._index[n.payload.key]=n.payload.value:"DEL"===n.payload.op&&delete this._index[n.payload.key]),t},[])}}t.exports=r},function(t,n,e){"use strict";class r{constructor(){this._index=[]}get(){return this._index}updateIndex(t){this._index=t.items}}t.exports=r},function(t,n,e){"use strict";class r{constructor(){this._index={}}get(){return Object.keys(this._index).map(t=>this._index[t])}updateIndex(t){t.items.reduce((t,n)=>{return t.includes(n.hash)||(t.push(n.hash),"ADD"===n.payload.op?this._index[n.hash]=n:"DEL"===n.payload.op&&delete this._index[n.payload.value]),t},[])}}t.exports=r},function(t,n,e){"use strict";class r{constructor(){this._index={}}get(t){return this._index[t]}updateIndex(t){t.items.slice().reverse().reduce((t,n)=>{return t.includes(n.payload.key)||(t.push(n.payload.key),"PUT"===n.payload.op?this._index[n.payload.key]=n.payload.value:"DEL"===n.payload.op&&delete this._index[n.payload.key]),t},[])}}t.exports=r},function(t,n,e){"use strict";(function(n){const r=e(39),i=r.create("orbit-db.ipfs-pubsub");r.setLogLevel("ERROR");class o{constructor(t){this._ipfs=t,this._subscriptions={},null===this._ipfs.pubsub&&i.error("The provided version of ipfs doesn't have pubsub support. Messages will not be exchanged."),this._handleMessage=this._handleMessage.bind(this)}subscribe(t,n){this._subscriptions[t]||(this._subscriptions[t]={onMessage:n},this._ipfs.pubsub&&this._ipfs.pubsub.subscribe(t,{discover:!0},this._handleMessage))}unsubscribe(t){this._subscriptions[t]&&(this._ipfs.pubsub.unsubscribe(t,this._handleMessage),delete this._subscriptions[t],i.debug(`Unsubscribed from '${t}'`))}publish(t,e){this._subscriptions[t]&&this._ipfs.pubsub&&this._ipfs.pubsub.publish(t,new n(JSON.stringify(e)))}disconnect(){Object.keys(this._subscriptions).forEach(t=>this.unsubscribe(t)),this._subscriptions={}}_handleMessage(t){if(t.from!==this._ipfs.PeerId){const n=t.topicCIDs[0],e=JSON.parse(t.data.toString()),r=this._subscriptions[n];r&&r.onMessage&&e&&r.onMessage(n,e)}}}t.exports=o}).call(n,e(0).Buffer)},function(t,n,e){"use strict";class r{constructor(t){this.id=t,this._index=[]}get(){return this._index}updateIndex(t,n){this._index=t.ops}}t.exports=r},function(t,n,e){"use strict";t.exports=((t,n,e)=>new Promise((r,i)=>{const o=Array.from(t);if(0===o.length)return void r([]);e=Object.assign({concurrency:1/0},e);let u=e.concurrency;if((u===1/0||u>o.length)&&(u=o.length),!(Number.isFinite(u)&&u>=1))throw new TypeError("Expected `concurrency` to be a finite number from 1 and up");const s=new Array(o.length);let c=!1,a=0;const f=t=>{if(!c)return a===o.length?void r(s):void(t>=o.length||Promise.resolve(o[t]).then(e=>n(e,t)).then(n=>{a++,s[t]=n,f(t+u)},t=>{c=!0,i(t)}))};for(let t=0;tnew Promise(n=>{n(t())});t.exports=((t,n)=>r(function e(){if(t())return r(n).then(e)}))},function(t,n){t.exports=function(t){function n(n){if(!n)throw new Error("must be passed a readable");e=n,r&&t(e)}var e,r=!1;Math.random();return n.resolve=n.ready=n.start=function(i){return r=!0,t=i||t,e&&t(e),n},n}},function(t,n){function e(t){function n(t,n){t&&(i=t,o&&r(i)),o=n,e()}function e(){o&&(i?r(i):!s.length&&u?r(u):s.length&&r(null,s.shift()))}function r(n,e){var r=o;if(n&&t){var i=t;t=null,i(n===!0?null:n)}o=null,r(n,e)}var i,o,u,s=[];return n.end=function(t){u=u||t||!0,e()},n.push=function(t){if(!u){if(o)return void r(i,t);s.push(t),e()}},n}t.exports=e},function(t,n,e){"use strict";t.exports=function t(n){var e=arguments.length;if("function"==typeof n&&1===n.length){for(var r=new Array(e),i=0;it?r(!0):void r(null,n++)}}},function(t,n,e){"use strict";t.exports=function(){return function(t,n){n(!0)}}},function(t,n,e){"use strict";t.exports=function(t){return function(n,e){e(t)}}},function(t,n,e){"use strict";t.exports={keys:e(65),once:e(17),values:e(12),count:e(60),infinite:e(64),empty:e(61),error:e(62)}},function(t,n,e){"use strict";t.exports=function(t){return t=t||Math.random,function(n,e){return n?e&&e(n):e(null,t())}}},function(t,n,e){"use strict";var r=e(12);t.exports=function(t){return r(Object.keys(t))}},function(t,n,e){"use strict";function r(t){return t}var i=e(2);t.exports=function(t){if(!t)return r;t=i(t);var n,e,o=!1;return function(r){return function i(u,s){if(e)return s(e);u?(e=u,o?r(u,function(){o?n=s:s(u)}):r(u,s)):r(null,function(r,u){r?s(r):e?s(e):(o=!0,t(u,function(t,r){o=!1,e?(s(e),n(e)):t?i(t,s):s(null,r)}))})}}}},function(t,n,e){"use strict";var r=e(20),i=e(13);t.exports=function(t){return t=r(t),i(function(n){return!t(n)})}},function(t,n,e){"use strict";var r=e(12),i=e(17);t.exports=function(){return function(t){var n;return function(e,o){function u(){n(null,function(n,e){n===!0?s():n?t(!0,function(t){o(n)}):o(null,e)})}function s(){n=null,t(null,function(t,e){if(t)return o(t);Array.isArray(e)||e&&"object"==typeof e?e=r(e):"function"!=typeof e&&(e=i(e)),n=e,u()})}e?n?n(e,function(n){t(n||e,o)}):t(e,o):n?u():s()}}}},function(t,n,e){"use strict";t.exports={map:e(70),asyncMap:e(66),filter:e(13),filterNot:e(67),through:e(73),take:e(72),unique:e(18),nonUnique:e(71),flatten:e(68)}},function(t,n,e){"use strict";function r(t){return t}var i=e(2);t.exports=function(t){return t?(t=i(t),function(n){return function(e,r){n(e,function(e,i){try{i=e?null:t(i)}catch(t){return n(t,function(){return r(t)})}r(e,i)})}}):r}},function(t,n,e){"use strict";var r=e(18);t.exports=function(t){return r(t,!0)}},function(t,n,e){"use strict";t.exports=function(t,n){n=n||{};var e=n.last||!1,r=!1;if("number"==typeof t){e=!0;var i=t;t=function(){return--i}}return function(n){function i(t){n(!0,function(n){e=!1,t(n||!0)})}return function(o,u){r?e?i(u):u(r):(r=o)?n(r,u):n(null,function(n,o){(r=r||n)?u(r):t(o)?u(null,o):(r=!0,e?u(null,o):i(u))})}}}},function(t,n,e){"use strict";t.exports=function(t,n){function e(t){!r&&n&&(r=!0,n(t===!0?null:t))}var r=!1;return function(n){return function(r,i){return r&&e(r),n(r,function(n,r){n?e(n):t&&t(r),i(n,r)})}}}},function(t,n,e){var r=e(40),i=t.exports=function(t,n){return function(e){n=n||function(t,n){return{start:t,data:n}};var i=[],o=[],u=null,s=0;return function(c,a){if(o.length)return a(null,o.shift());if(u)return a(u);s++;e(c,r(function(r,s){function c(t,e){l||(l=!0,delete i[i.indexOf(f)],o.push(n(s,e)))}var f,h=this,l=!1;return r&&(u=r),u||(f=t(s,c)),f?i.push(f):l=!0,i.forEach(function(t,n){t(r,s)}),o.length?a(null,o.shift()):u?a(u):void e(null,h)}))}}};i.recent=function(t,n){var e=null;return i(function(r,i){function o(){var t=e;e=null,clearTimeout(u),i(null,t)}if(!e){e=[];var u;return n&&(u=setTimeout(o,n)),function(n,r){if(n)return o();e.push(r),null!=t&&e.length>=t&&o()}}},function(t,n){return n})},i.sliding=function(t,n){n=n||10;var e=0;return i(function(r,i){var o,u=0;e++;return function(e,r){e||(o=t(o,r),n<=++u&&i(null,o))}})}},function(t,n){function e(t,n){return(t=t||[]).push(n),t}t.exports=function(t,n,r,i){function o(e){function a(){v||u||(v=!0,e(null,function(t,n){v=!1,h(t,n)}))}function f(){if(!p){var n=l;l=null,p=!0,d=0,t(n,function(t){p=!1,u!==!0||d?u&&u!==!0?(i(u),s&&s()):t?e(u=t,i):d?f():a():i(t)})}}function h(t,e){u||(u=t,u?p||i(u===!0?null:u):(l=n(l,e),d=l&&l.length||0,null!=l&&f(),d=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),v(e)?r.showHidden=e:e&&n._extend(r,e),_(r.showHidden)&&(r.showHidden=!1),_(r.depth)&&(r.depth=2),_(r.colors)&&(r.colors=!1),_(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),c(r,t,r.depth)}function o(t,n){var e=i.styles[n];return e?"["+i.colors[e][0]+"m"+t+"["+i.colors[e][1]+"m":t}function u(t,n){return t}function s(t){var n={};return t.forEach(function(t,e){n[t]=!0}),n}function c(t,e,r){if(t.customInspect&&e&&O(e.inspect)&&e.inspect!==n.inspect&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(r,t);return b(i)||(i=c(t,i,r)),i}var o=a(t,e);if(o)return o;var u=Object.keys(e),v=s(u);if(t.showHidden&&(u=Object.getOwnPropertyNames(e)),A(e)&&(u.indexOf("message")>=0||u.indexOf("description")>=0))return f(e);if(0===u.length){if(O(e)){var y=e.name?": "+e.name:"";return t.stylize("[Function"+y+"]","special")}if(x(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(k(e))return t.stylize(Date.prototype.toString.call(e),"date");if(A(e))return f(e)}var g="",m=!1,w=["{","}"];if(d(e)&&(m=!0,w=["[","]"]),O(e)){g=" [Function"+(e.name?": "+e.name:"")+"]"}if(x(e)&&(g=" "+RegExp.prototype.toString.call(e)),k(e)&&(g=" "+Date.prototype.toUTCString.call(e)),A(e)&&(g=" "+f(e)),0===u.length&&(!m||0==e.length))return w[0]+g+w[1];if(r<0)return x(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);var _;return _=m?h(t,e,r,v,u):u.map(function(n){return l(t,e,r,v,n,m)}),t.seen.pop(),p(_,g,w)}function a(t,n){if(_(n))return t.stylize("undefined","undefined");if(b(n)){var e="'"+JSON.stringify(n).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(e,"string")}return m(n)?t.stylize(""+n,"number"):v(n)?t.stylize(""+n,"boolean"):y(n)?t.stylize("null","null"):void 0}function f(t){return"["+Error.prototype.toString.call(t)+"]"}function h(t,n,e,r,i){for(var o=[],u=0,s=n.length;u-1&&(s=o?s.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return" "+t}).join("\n"))):s=t.stylize("[Circular]","special")),_(u)){if(o&&i.match(/^\d+$/))return s;u=JSON.stringify(""+i),u.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(u=u.substr(1,u.length-2),u=t.stylize(u,"name")):(u=u.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),u=t.stylize(u,"string"))}return u+": "+s}function p(t,n,e){var r=0;return t.reduce(function(t,n){return r++,n.indexOf("\n")>=0&&r++,t+n.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?e[0]+(""===n?"":n+"\n ")+" "+t.join(",\n ")+" "+e[1]:e[0]+n+" "+t.join(", ")+" "+e[1]}function d(t){return Array.isArray(t)}function v(t){return"boolean"==typeof t}function y(t){return null===t}function g(t){return null==t}function m(t){return"number"==typeof t}function b(t){return"string"==typeof t}function w(t){return"symbol"==typeof t}function _(t){return void 0===t}function x(t){return E(t)&&"[object RegExp]"===P(t)}function E(t){return"object"==typeof t&&null!==t}function k(t){return E(t)&&"[object Date]"===P(t)}function A(t){return E(t)&&("[object Error]"===P(t)||t instanceof Error)}function O(t){return"function"==typeof t}function T(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function P(t){return Object.prototype.toString.call(t)}function S(t){return t<10?"0"+t.toString(10):t.toString(10)}function I(){var t=new Date,n=[S(t.getHours()),S(t.getMinutes()),S(t.getSeconds())].join(":");return[t.getDate(),C[t.getMonth()],n].join(" ")}function j(t,n){return Object.prototype.hasOwnProperty.call(t,n)}var R=/%[sdj%]/g;n.format=function(t){if(!b(t)){for(var n=[],e=0;e=o)return t;switch(t){case"%s":return String(r[e++]);case"%d":return Number(r[e++]);case"%j":try{return JSON.stringify(r[e++])}catch(t){return"[Circular]"}default:return t}}),s=r[e];ethis.close(t)),this._pubsub&&this._pubsub.disconnect(),this.stores={},this.user=null,this.network=null}_createStore(t,n,e){const r=Object.assign({replicate:!0},e),i=new t(this._ipfs,this.user.id,n,r);return i.events.on("write",this._onWrite.bind(this)),i.events.on("ready",this._onReady.bind(this)),this.stores[n]=i,r.replicate&&this._pubsub&&this._pubsub.subscribe(n,this._onMessage.bind(this)),i}_onMessage(t,n){this.stores[t].sync(n)}_onWrite(t,e,r,i){if(!i)throw new Error("'heads' not defined");this._pubsub&&n(()=>this._pubsub.publish(t,i))}_onReady(t,n){n&&this._pubsub&&setTimeout(()=>this._pubsub.publish(t,n),1e3)}}t.exports=f}).call(n,e(7).setImmediate)}]); +//# sourceMappingURL=orbitdb.min.js.map \ No newline at end of file diff --git a/examples/benchmark.js b/examples/benchmark.js index 4af0977..1ba6fc4 100644 --- a/examples/benchmark.js +++ b/examples/benchmark.js @@ -16,7 +16,7 @@ const queryLoop = (db) => { totalQueries ++ lastTenSeconds ++ queriesPerSecond ++ - process.nextTick(() => queryLoop(db)) + setImmediate(() => queryLoop(db)) }) .catch((e) => console.error(e)) } @@ -30,7 +30,7 @@ ipfs.on('error', (err) => console.error(err)) ipfs.on('ready', () => { const orbit = new OrbitDB(ipfs, 'benchmark') - const db = orbit.eventlog('orbit-db.benchmark') + const db = orbit.eventlog('orbit-db.benchmark', { maxHistory: 100 }) // Metrics output setInterval(() => { diff --git a/examples/browser/browser.html b/examples/browser/browser.html index 4a41c2d..3348eaf 100644 --- a/examples/browser/browser.html +++ b/examples/browser/browser.html @@ -3,66 +3,78 @@ -
Loading...
+ + +

+
- - + + diff --git a/examples/browser/index.html b/examples/browser/index.html index df945bd..ff3ba1a 100644 --- a/examples/browser/index.html +++ b/examples/browser/index.html @@ -3,7 +3,10 @@ -
Loading...
+ + +

+
diff --git a/examples/browser/index.js b/examples/browser/index.js index 8dc0670..63f5d62 100644 --- a/examples/browser/index.js +++ b/examples/browser/index.js @@ -3,81 +3,108 @@ const IPFS = require('ipfs-daemon/src/ipfs-browser-daemon') const OrbitDB = require('../../src/OrbitDB') -const username = new Date().getTime() -const channel = 'orbitdb-browser-examples' -const key = 'greeting' +const elm = document.getElementById("output") +const dbnameField = document.getElementById("dbname") +const openButton = document.getElementById("open") -const elm = document.getElementById("result") +const openDatabase = () => { + openButton.disabled = true + elm.innerHTML = "Starting IPFS..." -const ipfs = new IPFS({ - IpfsDataDir: '/tmp/orbit-db-examples', - // dev server: webrtc-star-signalling.cloud.ipfs.team - SignalServer: 'star-signal.cloud.ipfs.team', // IPFS dev server - Discovery: { - MDNS: { - Enabled: false, - Interval: 10 - }, - webRTCStar: { - Enabled: true - } - }, -}) + const dbname = dbnameField.value + const username = new Date().getTime() + const key = 'greeting' -function handleError(e) { - console.error(e.stack) - elm.innerHTML = e.message -} + const ipfs = new IPFS({ + IpfsDataDir: '/orbit-db-/examples/browser', + SignalServer: 'star-signal.cloud.ipfs.team', // IPFS dev server + }) -ipfs.on('error', (e) => handleError(e)) - -ipfs.on('ready', () => { - const orbit = new OrbitDB(ipfs, username, { maxHistory: 5 }) - - const db = orbit.kvstore(channel) - const log = orbit.eventlog(channel + ".log") - const counter = orbit.counter(channel + ".count") - - const creatures = ['👻', '🐙', '🐷', '🐬', '🐞', '🐈', '🙉', '🐸', '🐓'] - - let count = 1 - const query = () => { - const idx = Math.floor(Math.random() * creatures.length) - - // Set a key-value pair - db.put(key, "db.put #" + count + " - GrEEtinGs to " + creatures[idx]) - .then((res) => count ++) - .then(() => counter.inc()) // Increase the counter by one - .then(() => log.add(creatures[idx])) // Add an event to 'latest visitors' log - .then(() => { - const result = db.get(key) - const latest = log.iterator({ limit: 5 }).collect() - const count = counter.value - - const output = ` - Key-Value Store - ------------------------------------------------------- - Key | Value - ------------------------------------------------------- - ${key} | ${result} - ------------------------------------------------------- - - Eventlog - ------------------------------------------------------- - Latest Visitors - ------------------------------------------------------- - ${latest.reverse().map((e) => e.payload.value + " at " + new Date(e.payload.meta.ts).toISOString()).join('\n')} - - Counter - ------------------------------------------------------- - Visitor Count: ${count} - ------------------------------------------------------- - ` - elm.innerHTML = output.split("\n").join("
") - }) - .catch((e) => handleError(e)) + function handleError(e) { + console.error(e.stack) + elm.innerHTML = e.message } - // Start query loop when the databse has loaded its history - db.events.on('ready', () => setInterval(query, 1000)) -}) + ipfs.on('error', (e) => handleError(e)) + + ipfs.on('ready', () => { + elm.innerHTML = "Loading database..." + + const orbit = new OrbitDB(ipfs, username) + + const db = orbit.kvstore(dbname, { maxHistory: 5, syncHistory: false, cachePath: '/orbit-db' }) + const log = orbit.eventlog(dbname + ".log", { maxHistory: 5, syncHistory: false, cachePath: '/orbit-db' }) + const counter = orbit.counter(dbname + ".count", { maxHistory: 5, syncHistory: false, cachePath: '/orbit-db' }) + + const creatures = ['👻', '🐙', '🐷', '🐬', '🐞', '🐈', '🙉', '🐸', '🐓'] + const idx = Math.floor(Math.random() * creatures.length) + const creature = creatures[idx] + + const interval = Math.floor((Math.random() * 5000) + 3000) + + let count = 0 + const query = () => { + const value = "GrEEtinGs from " + username + " " + creature + ": Hello #" + count + " (" + new Date().getTime() + ")" + // Set a key-value pair + count ++ + db.put(key, value) + .then(() => counter.inc()) // Increase the counter by one + .then(() => log.add(value)) // Add an event to 'latest visitors' log + .then(() => getData()) + .catch((e) => handleError(e)) + } + + const getData = () => { + const result = db.get(key) + const latest = log.iterator({ limit: 5 }).collect() + const count = counter.value + + ipfs.pubsub.peers(dbname + ".log") + .then((peers) => { + const output = ` + You are: ${username} ${creature}
+ Peers: ${peers.length}
+ Database: ${dbname}
+
Writing to database every ${interval} milliseconds...

+ Key-Value Store + ------------------------------------------------------- + Key | Value + ------------------------------------------------------- + ${key} | ${result} + ------------------------------------------------------- + + Eventlog + ------------------------------------------------------- + Latest Updates + ------------------------------------------------------- + ${latest.reverse().map((e) => e.payload.value).join('\n')} + + Counter + ------------------------------------------------------- + Visitor Count: ${count} + ------------------------------------------------------- + ` + elm.innerHTML = output.split("\n").join("
") + }) + } + + db.events.on('synced', () => getData()) + counter.events.on('synced', () => getData()) + log.events.on('synced', () => getData()) + + db.events.on('ready', () => getData()) + counter.events.on('ready', () => getData()) + log.events.on('ready', () => getData()) + + // Start query loop when the databse has loaded its history + db.load(10) + .then(() => counter.load(10)) + .then(() => log.load(10)) + .then(() => { + count = counter.value + setInterval(query, interval) + }) + }) +} + +openButton.addEventListener('click', openDatabase) diff --git a/package.json b/package.json index 56aec26..d782f39 100644 --- a/package.json +++ b/package.json @@ -16,43 +16,36 @@ }, "main": "src/OrbitDB.js", "dependencies": { - "fs-pull-blob-store": "^0.4.1", - "idb-pull-blob-store": "^0.5.1", - "lock": "^0.1.3", + "libp2p-floodsub": "github:libp2p/js-libp2p-floodsub#orbit-floodsub", "logplease": "^1.2.12", - "orbit-db-counterstore": "^0.1.8", - "orbit-db-docstore": "^0.0.9", - "orbit-db-eventstore": "^0.1.9", - "orbit-db-feedstore": "^0.1.8", - "orbit-db-kvstore": "^0.1.7", - "orbit-db-pubsub": "^0.1.6", - "pull-stream": "^3.4.5" + "orbit-db-counterstore": "~0.2.0", + "orbit-db-docstore": "github:orbitdb/orbit-db-docstore#v0.2.0", + "orbit-db-eventstore": "~0.2.0", + "orbit-db-feedstore": "~0.2.0", + "orbit-db-kvstore": "~0.2.0", + "orbit-db-pubsub": "~0.2.1" }, "devDependencies": { - "asyncawait": "^1.0.6", - "babel-core": "^6.21.0", - "babel-loader": "^6.2.9", - "babel-plugin-transform-runtime": "^6.15.0", - "babel-polyfill": "^6.20.0", - "babel-preset-es2015": "^6.18.0", - "bluebird": "^3.4.6", - "ipfs-daemon": "^0.3.0-beta.16", + "babel-core": "^6.22.1", + "babel-loader": "^6.2.10", + "babel-plugin-transform-runtime": "^6.22.0", + "babel-polyfill": "^6.22.0", + "babel-preset-es2015": "^6.22.0", + "ipfs-daemon": "~0.3.0-beta.24", "json-loader": "^0.5.4", - "lodash": "^4.17.4", - "mocha": "^3.1.2", + "mocha": "^3.2.0", + "p-each-series": "^1.0.0", "rimraf": "^2.5.4", - "stream-http": "^2.6.2", - "webpack": "^2.1.0-beta.28" + "uglify-js": "github:mishoo/UglifyJS2#harmony", + "webpack": "^2.2.1" }, "scripts": { "examples": "npm run examples:node", "examples:node": "node examples/eventlog.js", "examples:browser": "open examples/browser/index.html && LOG=debug node examples/start-daemon.js", "test": "mocha", - "build": "npm run build:dist && npm run build:minified && npm run build:examples", - "build:dist": "webpack --config conf/webpack.config.js", - "build:minified": "webpack --config conf/webpack.config.minified.js", - "build:examples": "webpack --config conf/webpack.example.config.js", - "stats": "webpack --json > stats.json" + "build": "npm run build:examples && npm run build:dist", + "build:examples": "webpack --config conf/webpack.example.config.js --sort-modules-by size", + "build:dist": "webpack -p --config conf/webpack.config.js --sort-modules-by size" } } diff --git a/src/Cache.js b/src/Cache.js deleted file mode 100644 index 8f45127..0000000 --- a/src/Cache.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict' - -const pull = require('pull-stream') -const BlobStore = require('fs-pull-blob-store') -const Lock = require('lock') - -let filePath -let store -let cache = {} -const lock = new Lock() - -class Cache { - static set(key, value) { - return new Promise((resolve, reject) => { - if (cache[key] === value) - return resolve() - - cache[key] = value - if(filePath && store) { - lock(filePath, (release) => { - // console.log("write cache:", filePath, JSON.stringify(cache, null, 2)) - pull( - pull.values([cache]), - pull.map((v) => JSON.stringify(v, null, 2)), - store.write(filePath, release((err) => { - if (err) { - return reject(err) - } - resolve() - })) - ) - }) - } else { - resolve() - } - }) - } - - static get(key) { - return cache[key] - } - - static loadCache(cachePath, cacheFile = 'orbit-db.cache') { - cache = {} - - if (!cachePath) - return Promise.resolve() - - // console.log("cache data:", cachePath) - store = new BlobStore(cachePath) - filePath = cacheFile - - return new Promise((resolve, reject) => { - - // console.log("load cache:", cacheFile) - store.exists(cacheFile, (err, exists) => { - if (err || !exists) { - return resolve() - } - - lock(cacheFile, (release) => { - pull( - store.read(cacheFile), - pull.collect(release((err, res) => { - if (err) { - return reject(err) - } - - cache = JSON.parse(Buffer.concat(res).toString() || '{}') - - resolve() - })) - ) - }) - }) - }) - } - - static reset() { - cache = {} - store = null - } -} - -module.exports = Cache diff --git a/src/OrbitDB.js b/src/OrbitDB.js index bbb9816..dfd9175 100644 --- a/src/OrbitDB.js +++ b/src/OrbitDB.js @@ -7,7 +7,6 @@ const KeyValueStore = require('orbit-db-kvstore') const CounterStore = require('orbit-db-counterstore') const DocumentStore = require('orbit-db-docstore') const Pubsub = require('orbit-db-pubsub') -const Cache = require('./Cache') const defaultNetworkName = 'Orbit DEV Network' @@ -42,79 +41,58 @@ class OrbitDB { return this._createStore(DocumentStore, dbname, options) } + close(dbname) { + if(this._pubsub) this._pubsub.unsubscribe(dbname) + if (this.stores[dbname]) { + this.stores[dbname].events.removeAllListeners('write') + delete this.stores[dbname] + } + } + disconnect() { + Object.keys(this.stores).forEach((e) => this.close(e)) if (this._pubsub) this._pubsub.disconnect() - this.events.removeAllListeners('data') - Object.keys(this.stores).map((e) => this.stores[e]).forEach((store) => { - store.events.removeAllListeners('data') - store.events.removeAllListeners('write') - store.events.removeAllListeners('close') - }) this.stores = {} this.user = null this.network = null } /* Private methods */ - _createStore(Store, dbname, options = { subscribe: true }) { - const store = new Store(this._ipfs, this.user.id, dbname, options) - this.stores[dbname] = store - return this._subscribe(store, dbname, options.subscribe, options.cachePath) - } + _createStore(Store, dbname, options) { + const opts = Object.assign({ replicate: true }, options) - _subscribe(store, dbname, subscribe = true, cachePath = './orbit-db') { - store.events.on('data', this._onData.bind(this)) + const store = new Store(this._ipfs, this.user.id, dbname, opts) store.events.on('write', this._onWrite.bind(this)) - store.events.on('close', this._onClose.bind(this)) + store.events.on('ready', this._onReady.bind(this)) - if(subscribe && this._pubsub) - this._pubsub.subscribe(dbname, this._onMessage.bind(this), this._onConnected.bind(this), store.options.maxHistory > 0) - else - store.loadHistory().catch((e) => console.error(e.stack)) + this.stores[dbname] = store - Cache.loadCache(cachePath).then(() => { - const hash = Cache.get(dbname) - store.loadHistory(hash).catch((e) => console.error(e.stack)) - }) + if(opts.replicate && this._pubsub) + this._pubsub.subscribe(dbname, this._onMessage.bind(this)) return store } - /* Connected to the message broker */ - _onConnected(dbname, hash) { - // console.log(".CONNECTED", dbname, hash) - const store = this.stores[dbname] - store.loadHistory(hash).catch((e) => console.error(e.stack)) - } - /* Replication request from the message broker */ - _onMessage(dbname, hash) { - // console.log(".MESSAGE", dbname, hash) + _onMessage(dbname, heads) { + // console.log(".MESSAGE", dbname, heads) const store = this.stores[dbname] - store.sync(hash) - .then((res) => Cache.set(dbname, res)) - .then(() => this.events.emit('synced', dbname, hash)) - .catch((e) => console.error(e.stack)) + store.sync(heads) } /* Data events */ - _onWrite(dbname, hash) { + _onWrite(dbname, hash, entry, heads) { // 'New entry written to database...', after adding a new db entry locally // console.log(".WRITE", dbname, hash, this.user.username) - if(!hash) throw new Error("Hash can't be null!") - if(this._pubsub) this._pubsub.publish(dbname, hash) - Cache.set(dbname, hash) + if(!heads) throw new Error("'heads' not defined") + if(this._pubsub) setImmediate(() => this._pubsub.publish(dbname, heads)) } - _onData(dbname, items) { - // 'New database entry...', after a new entry was added to the database - // console.log(".SYNCED", dbname, items.length) - this.events.emit('data', dbname, items) - } - - _onClose(dbname) { - if(this._pubsub) this._pubsub.unsubscribe(dbname) - delete this.stores[dbname] + _onReady(dbname, heads) { + // if(heads && this._pubsub) setImmediate(() => this._pubsub.publish(dbname, heads)) + if(heads && this._pubsub) { + setTimeout(() => this._pubsub.publish(dbname, heads), 1000) + } } } diff --git a/test/client.test.js b/test/client.test.js deleted file mode 100644 index c41d909..0000000 --- a/test/client.test.js +++ /dev/null @@ -1,657 +0,0 @@ -'use strict' - -const _ = require('lodash') -const fs = require('fs') -const path = require('path') -const assert = require('assert') -const async = require('asyncawait/async') -const await = require('asyncawait/await') -const Promise = require('bluebird') -// const IpfsApis = require('ipfs-test-apis') -const OrbitDB = require('../src/OrbitDB') -const rmrf = require('rimraf') -const IpfsNodeDaemon = require('ipfs-daemon/src/ipfs-node-daemon') -const IpfsNativeDaemon = require('ipfs-daemon/src/ipfs-native-daemon') - -if (typeof window !== 'undefined') - window.LOG = 'ERROR' - -// Data directories -const defaultIpfsDirectory = './ipfs' -const defaultOrbitDBDirectory = './orbit-db' - -// Orbit -const username = 'testrunner' - -const hasIpfsApiWithPubsub = (ipfs) => { - return ipfs.object.get !== undefined - && ipfs.object.put !== undefined - // && ipfs.pubsub.publish !== undefined - // && ipfs.pubsub.subscribe !== undefined -} - -// [IpfsNativeDaemon, IpfsNodeDaemon].forEach((IpfsDaemon) => { -[IpfsNodeDaemon].forEach((IpfsDaemon) => { -// IpfsApis.forEach(function(ipfsApi) { - - describe('orbit-db client', function() { - this.timeout(40000) - - let ipfs, client, client2, db - let channel = 'abcdefghijklmn' - - before(function (done) { - rmrf.sync(defaultIpfsDirectory) - rmrf.sync(defaultOrbitDBDirectory) - ipfs = new IpfsDaemon() - ipfs.on('error', done) - ipfs.on('ready', () => { - assert.equal(hasIpfsApiWithPubsub(ipfs), true) - client = new OrbitDB(ipfs, username) - client2 = new OrbitDB(ipfs, username + '2') - done() - }) - }) - - after(() => { - if(db) db.delete() - if(client) client.disconnect() - if(client2) client2.disconnect() - ipfs.stop() - rmrf.sync(defaultOrbitDBDirectory) - rmrf.sync(defaultIpfsDirectory) - }) - - describe('Add events', function() { - beforeEach(() => { - db = client.eventlog(channel, { subscribe: false, maxHistory: 0 }) - db.delete() - }) - - it('adds an item to an empty channel', () => { - return db.add('hello') - .then((head) => { - assert.notEqual(head, null) - assert.equal(head.startsWith('Qm'), true) - assert.equal(head.length, 46) - }) - }) - - it('adds a new item to a channel with one item', () => { - const head = db.iterator().collect() - return db.add('hello') - .then((second) => { - assert.notEqual(second, null) - assert.notEqual(second, head) - assert.equal(second.startsWith('Qm'), true) - assert.equal(second.length, 46) - }) - }) - - it('adds five items', async(() => { - for(let i = 1; i <= 5; i ++) - await(db.add('hello' + i)) - - const items = db.iterator({ limit: -1 }).collect() - assert.equal(items.length, 5) - assert.equal(_.first(items.map((f) => f.payload.value)), 'hello1') - assert.equal(_.last(items.map((f) => f.payload.value)), 'hello5') - })) - - it('adds an item that is > 256 bytes', () => { - let msg = new Buffer(1024) - msg.fill('a') - return db.add(msg.toString()) - .then((hash) => { - assert.notEqual(hash, null) - assert.equal(hash.startsWith('Qm'), true) - assert.equal(hash.length, 46) - }) - }) - }) - - describe('Delete events (Feed)', function() { - beforeEach(() => { - db = client.feed(channel, { subscribe: false, maxHistory: 0 }) - db.delete() - }) - - it('deletes an item when only one item in the database', async(() => { - const head = await(db.add('hello1')) - const delop = await(db.remove(head)) - const items = db.iterator().collect() - assert.equal(delop.startsWith('Qm'), true) - assert.equal(items.length, 0) - })) - - it('deletes an item when two items in the database', async(() => { - await(db.add('hello1')) - const head = await(db.add('hello2')) - await(db.remove(head)) - const items = db.iterator({ limit: -1 }).collect() - assert.equal(items.length, 1) - assert.equal(items[0].payload.value, 'hello1') - })) - - it('deletes an item between adds', async(() => { - const head = await(db.add('hello1')) - await(db.add('hello2')) - db.remove(head) - await(db.add('hello3')) - const items = db.iterator().collect() - assert.equal(items.length, 1) - assert.equal(items[0].hash.startsWith('Qm'), true) - assert.equal(items[0].payload.key, null) - assert.equal(items[0].payload.value, 'hello3') - })) - }) - - describe('Iterator', function() { - let items = [] - const itemCount = 5 - - beforeEach(async(() => { - items = [] - db = client.eventlog(channel, { subscribe: false, maxHistory: 0 }) - db.delete() - for(let i = 0; i < itemCount; i ++) { - const hash = await(db.add('hello' + i)) - items.push(hash) - } - })) - - describe('Defaults', function() { - it('returns an iterator', async((done) => { - const iter = db.iterator() - const next = iter.next().value - assert.notEqual(iter, null) - assert.notEqual(next, null) - done() - })) - - it('returns an item with the correct structure', async((done) => { - const iter = db.iterator() - const next = iter.next().value - assert.notEqual(next, null) - assert.equal(next.hash.startsWith('Qm'), true) - assert.equal(next.payload.key, null) - assert.equal(next.payload.value, 'hello4') - assert.notEqual(next.payload.meta.ts, null) - done() - })) - - it('implements Iterator interface', async((done) => { - const iter = db.iterator({ limit: -1 }) - let messages = [] - - for(let i of iter) - messages.push(i.key) - - assert.equal(messages.length, items.length) - done() - })) - - it('returns 1 item as default', async((done) => { - const iter = db.iterator() - const first = iter.next().value - const second = iter.next().value - assert.equal(first.hash, items[items.length - 1]) - assert.equal(second, null) - assert.equal(first.payload.value, 'hello4') - done() - })) - - it('returns items in the correct order', async((done) => { - const amount = 3 - const iter = db.iterator({ limit: amount }) - let i = items.length - amount - for(let item of iter) { - assert.equal(item.payload.value, 'hello' + i) - i ++ - } - done() - })) - }) - - describe('Collect', function() { - it('returns all items', async((done) => { - const messages = db.iterator({ limit: -1 }).collect() - assert.equal(messages.length, items.length) - assert.equal(messages[0].payload.value, 'hello0') - assert.equal(messages[messages.length - 1].payload.value, 'hello4') - done() - })) - - it('returns 1 item', async((done) => { - const messages = db.iterator().collect() - assert.equal(messages.length, 1) - done() - })) - - it('returns 3 items', async((done) => { - const messages = db.iterator({ limit: 3 }).collect() - assert.equal(messages.length, 3) - done() - })) - }) - - describe('Options: limit', function() { - it('returns 1 item when limit is 0', async((done) => { - const iter = db.iterator({ limit: 1 }) - const first = iter.next().value - const second = iter.next().value - assert.equal(first.hash, _.last(items)) - assert.equal(second, null) - done() - })) - - it('returns 1 item when limit is 1', async((done) => { - const iter = db.iterator({ limit: 1 }) - const first = iter.next().value - const second = iter.next().value - assert.equal(first.hash, _.last(items)) - assert.equal(second, null) - done() - })) - - it('returns 3 items', async((done) => { - const iter = db.iterator({ limit: 3 }) - const first = iter.next().value - const second = iter.next().value - const third = iter.next().value - const fourth = iter.next().value - assert.equal(first.hash, items[items.length - 3]) - assert.equal(second.hash, items[items.length - 2]) - assert.equal(third.hash, items[items.length - 1]) - assert.equal(fourth, null) - done() - })) - - it('returns all items', async((done) => { - const messages = db.iterator({ limit: -1 }) - .collect() - .map((e) => e.hash) - - messages.reverse() - assert.equal(messages.length, items.length) - assert.equal(messages[0], items[items.length - 1]) - done() - })) - - it('returns all items when limit is bigger than -1', async((done) => { - const messages = db.iterator({ limit: -300 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, items.length) - assert.equal(messages[0], items[0]) - done() - })) - - it('returns all items when limit is bigger than number of items', async((done) => { - const messages = db.iterator({ limit: 300 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, items.length) - assert.equal(messages[0], items[0]) - done() - })) - }) - - describe('Option: ranges', function() { - describe('gt & gte', function() { - it('returns 1 item when gte is the head', async((done) => { - const messages = db.iterator({ gte: _.last(items), limit: -1 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, 1) - assert.equal(messages[0], _.last(items)) - done() - })) - - it('returns 0 items when gt is the head', async((done) => { - const messages = db.iterator({ gt: _.last(items) }).collect() - assert.equal(messages.length, 0) - done() - })) - - it('returns 2 item when gte is defined', async((done) => { - const gte = items[items.length - 2] - const messages = db.iterator({ gte: gte, limit: -1 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, 2) - assert.equal(messages[0], items[items.length - 2]) - assert.equal(messages[1], items[items.length - 1]) - done() - })) - - it('returns all items when gte is the root item', async((done) => { - const messages = db.iterator({ gte: items[0], limit: -1 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, items.length) - assert.equal(messages[0], items[0]) - assert.equal(messages[messages.length - 1], _.last(items)) - done() - })) - - it('returns items when gt is the root item', async((done) => { - const messages = db.iterator({ gt: items[0], limit: -1 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, itemCount - 1) - assert.equal(messages[0], items[1]) - assert.equal(messages[3], _.last(items)) - done() - })) - - it('returns items when gt is defined', async((done) => { - const messages = db.iterator({ limit: -1}) - .collect() - .map((e) => e.hash) - - const gt = messages[2] - - const messages2 = db.iterator({ gt: gt, limit: 100 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages2.length, 2) - assert.equal(messages2[0], messages[messages.length - 2]) - assert.equal(messages2[1], messages[messages.length - 1]) - done() - })) - }) - - describe('lt & lte', function() { - it('returns one item after head when lt is the head', async((done) => { - const messages = db.iterator({ lt: _.last(items) }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, 1) - assert.equal(messages[0], items[items.length - 2]) - done() - })) - - it('returns all items when lt is head and limit is -1', async((done) => { - const messages = db.iterator({ lt: _.last(items), limit: -1 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, items.length - 1) - assert.equal(messages[0], items[0]) - assert.equal(messages[messages.length - 1], items[items.length - 2]) - done() - })) - - it('returns 3 items when lt is head and limit is 3', async((done) => { - const messages = db.iterator({ lt: _.last(items), limit: 3 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, 3) - assert.equal(messages[0], items[items.length - 4]) - assert.equal(messages[2], items[items.length - 2]) - done() - })) - - it('returns null when lt is the root item', async((done) => { - const messages = db.iterator({ lt: items[0] }).collect() - assert.equal(messages.length, 0) - done() - })) - - it('returns one item when lte is the root item', async((done) => { - const messages = db.iterator({ lte: items[0] }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, 1) - assert.equal(messages[0], items[0]) - done() - })) - - it('returns all items when lte is the head', async((done) => { - const messages = db.iterator({ lte: _.last(items), limit: -1 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, itemCount) - assert.equal(messages[0], items[0]) - assert.equal(messages[4], _.last(items)) - done() - })) - - it('returns 3 items when lte is the head', async((done) => { - const messages = db.iterator({ lte: _.last(items), limit: 3 }) - .collect() - .map((e) => e.hash) - - assert.equal(messages.length, 3) - assert.equal(messages[0], items[items.length - 3]) - assert.equal(messages[1], items[items.length - 2]) - assert.equal(messages[2], _.last(items)) - done() - })) - }) - }) - }) - - describe('Delete', function() { - it('deletes a channel from the local database', () => { - const result = db.delete() - // assert.equal(result, true) - const iter = db.iterator() - assert.equal(iter.next().value, null) - }) - }) - - describe('Key-Value Store', function() { - beforeEach(() => { - db = client.kvstore(channel, { subscribe: false, maxHistory: 0 }) - db.delete() - }) - - afterEach(() => { - db.close() - }) - - it('put', async(() => { - await(db.put('key1', 'hello!')) - const value = db.get('key1') - assert.equal(value, 'hello!') - })) - - it('get', async(() => { - await(db.put('key1', 'hello!')) - const value = db.get('key1') - assert.equal(value, 'hello!') - })) - - it('put updates a value', async(() => { - await(db.put('key1', 'hello!')) - await(db.put('key1', 'hello again')) - const value = db.get('key1') - assert.equal(value, 'hello again') - })) - - it('put/get - multiple keys', async(() => { - await(db.put('key1', 'hello1')) - await(db.put('key2', 'hello2')) - await(db.put('key3', 'hello3')) - const v1 = db.get('key1') - const v2 = db.get('key2') - const v3 = db.get('key3') - assert.equal(v1, 'hello1') - assert.equal(v2, 'hello2') - assert.equal(v3, 'hello3') - })) - - it('deletes a key', async(() => { - await(db.put('key1', 'hello!')) - await(db.del('key1')) - const value = db.get('key1') - assert.equal(value, null) - })) - - it('deletes a key after multiple updates', async(() => { - await(db.put('key1', 'hello1')) - await(db.put('key1', 'hello2')) - await(db.put('key1', 'hello3')) - await(db.del('key1')) - const value = db.get('key1') - assert.equal(value, null) - })) - - it('get - integer value', async(() => { - await(db.put('key1', 123)) - const v1 = db.get('key1') - assert.equal(v1, 123) - })) - - it('get - object value', (done) => { - const val = { one: 'first', two: 2 } - db.put('key1', val).then(() => { - const v1 = db.get('key1') - assert.equal(_.isEqual(v1, val), true) - done() - }) - }) - - it('get - array value', async(() => { - const val = [1, 2, 3, 4, 5] - await(db.put('key1', val)) - const v1 = db.get('key1') - assert.equal(_.isEqual(v1, val), true) - })) - - it('syncs databases', (done) => { - const db2 = client2.kvstore(channel, { subscribe: false, maxHistory: 0 }) - db2.events.on('write', (dbname, hash) => { - assert.equal(db.get('key1', null)) - - db.sync(hash).then((hash) => { - const value = db.get('key1') - assert.equal(value, 'hello2') - done() - }) - }) - db2.put('key1', 'hello2') - }) - - it('sync returns the updated log\'s hash', (done) => { - let firstHash, secondHash - const db2 = client2.kvstore(channel, { subscribe: false, maxHistory: 0 }) - db2.events.on('write', (dbname, hash) => { - db.sync(hash).then((hash) => { - const value1 = db.get('key1') - const value2 = db.get('key2') - assert.equal(value1, 'hello1') - assert.equal(value2, 'hello2') - assert.notEqual(firstHash, hash) - done() - }) - }) - db.events.on('write', (dbname, hash) => { - firstHash = hash - db2.put('key2', 'hello2') - }) - db.put('key1', 'hello1') - }) - }) - - describe('Document Store - default index \'_id\'', function() { - beforeEach(() => { - db = client.docstore(channel, { subscribe: false, maxHistory: 0 }) - db.delete() - }) - - afterEach(() => { - db.close() - }) - - it('put', async(() => { - await(db.put({ _id: 'hello world', doc: 'all the things'})) - const value = db.get('hello world') - assert.deepEqual(value, [{ _id: 'hello world', doc: 'all the things'}]) - })) - - it('get - partial term match', async(() => { - await(db.put({ _id: 'hello world', doc: 'some things'})) - await(db.put({ _id: 'hello universe', doc: 'all the things'})) - await(db.put({ _id: 'sup world', doc: 'other things'})) - const value = db.get('hello') - assert.deepEqual(value, [{ _id: 'hello world', doc: 'some things' }, - { _id: 'hello universe', doc: 'all the things'}]) - })) - - it('get after delete', async(() => { - await(db.put({ _id: 'hello world', doc: 'some things'})) - await(db.put({ _id: 'hello universe', doc: 'all the things'})) - await(db.put({ _id: 'sup world', doc: 'other things'})) - await(db.del('hello universe')) - const value = db.get('hello') - assert.deepEqual(value, [{ _id: 'hello world', doc: 'some things'}]) - })) - - it('put updates a value', async(() => { - await(db.put({ _id: 'hello world', doc: 'all the things'})) - await(db.put({ _id: 'hello world', doc: 'some of the things'})) - const value = db.get('hello') - assert.deepEqual(value, [{ _id: 'hello world', doc: 'some of the things'}]) - })) - - it('query', async(() => { - await(db.put({ _id: 'hello world', doc: 'all the things', views: 17})) - await(db.put({ _id: 'sup world', doc: 'some of the things', views: 10})) - await(db.put({ _id: 'hello other world', doc: 'none of the things', views: 5})) - await(db.put({ _id: 'hey universe', doc: ''})) - const value = db.query((e) => e.views > 5) - assert.deepEqual(value, [{ _id: 'hello world', doc: 'all the things', views: 17}, - { _id: 'sup world', doc: 'some of the things', views: 10}]) - })) - - it('query after delete', async(() => { - await(db.put({ _id: 'hello world', doc: 'all the things', views: 17})) - await(db.put({ _id: 'sup world', doc: 'some of the things', views: 10})) - await(db.put({ _id: 'hello other world', doc: 'none of the things', views: 5})) - await(db.del('hello world')) - await(db.put({ _id: 'hey universe', doc: ''})) - const value = db.query((e) => e.views > 5) - assert.deepEqual(value, [{ _id: 'sup world', doc: 'some of the things', views: 10}]) - })) - }) - - describe('Document Store - specified index', function() { - beforeEach(() => { - db = client.docstore(channel, { subscribe: false, indexBy: 'doc', maxHistory: 0 }) - db.delete() - }) - - afterEach(() => { - db.close() - }) - - it('put', async(() => { - await(db.put({ _id: 'hello world', doc: 'all the things'})) - const value = db.get('all') - assert.deepEqual(value, [{ _id: 'hello world', doc: 'all the things'}]) - })) - - it('get - matches specified index', async(() => { - await(db.put({ _id: 'hello universe', doc: 'all the things'})) - await(db.put({ _id: 'hello world', doc: 'some things'})) - const value = db.get('all') - assert.deepEqual(value, [{ _id: 'hello universe', doc: 'all the things'}]) - })) - }) - }) - -}) diff --git a/test/counterdb.test.js b/test/counterdb.test.js index af2fc1a..0d74e7a 100644 --- a/test/counterdb.test.js +++ b/test/counterdb.test.js @@ -1,13 +1,12 @@ // 'use strict' -// const assert = require('assert') -// const path = require('path') -// const fs = require('fs') -// const Promise = require('bluebird') -// const rimraf = require('rimraf') -// const IpfsApis = require('ipfs-test-apis') -// const IpfsDaemon = require('ipfs-daemon') -// const OrbitDB = require('../src/OrbitDB') +// const path = require('path') +// const assert = require('assert') +// const Promise = require('bluebird') +// const rmrf = require('rimraf') +// const IpfsNodeDaemon = require('ipfs-daemon/src/ipfs-node-daemon') +// const IpfsNativeDaemon = require('ipfs-daemon/src/ipfs-native-daemon') +// const OrbitDB = require('../src/OrbitDB') // const username = 'testrunner' // const username2 = 'rennurtset' @@ -31,16 +30,16 @@ // }, 1000) // } -// IpfsApis.forEach(function(ipfsApi) { +// [IpfsNodeDaemon].forEach((IpfsDaemon) => { // let ipfs, ipfsDaemon -// describe('CounterStore with ' + ipfsApi.name, function() { +// describe('CounterStore', function() { // this.timeout(20000) // let client1, client2 // let daemon1, daemon2 // before((done) => { -// // rimraf.sync('./orbit-db-cache.json') +// rmrf.sync(cacheFile) // daemon1 = new IpfsDaemon(daemonConfs.daemon1) // daemon1.on('ready', () => { // daemon2 = new IpfsDaemon(daemonConfs.daemon2) @@ -54,17 +53,18 @@ // after((done) => { // daemon1.stop() // daemon2.stop() +// rmrf.sync(cacheFile) // done() // }) // beforeEach(() => { -// client1 = new OrbitDB(ipfs[0], username, { cacheFile: cacheFile }) -// client2 = new OrbitDB(ipfs[1], username2, { cacheFile: cacheFile }) +// client1 = new OrbitDB(ipfs[0]) +// client2 = new OrbitDB(ipfs[1]) // }) // afterEach(() => { -// if(client1) client1.disconnect() -// if(client2) client2.disconnect() +// if (client1) client1.disconnect() +// if (client2) client2.disconnect() // }) // describe('counters', function() { @@ -72,9 +72,9 @@ // const timeout = setTimeout(() => done(new Error('event was not fired')), 2000) // const counter = client1.counter('counter test', { subscribe: false, cacheFile: cacheFile }) // counter.events.on('ready', () => { -// Promise.map([13, 1], (f) => counter.inc(f), { concurrency: 1 }) +// Promise.map([13, 1], (f) => counter.inc(f), { concurrency: 1, cacheFile: cacheFile }) // .then(() => { -// assert.equal(counter.value(), 14) +// assert.equal(counter.value, 14) // clearTimeout(timeout) // client1.disconnect() // done() @@ -83,11 +83,11 @@ // }) // }) -// it('creates a new counter from cached data', function(done) { +// it.skip('creates a new counter from cached data', function(done) { // const timeout = setTimeout(() => done(new Error('event was not fired')), 2000) // const counter = client1.counter('counter test', { subscribe: false, cacheFile: cacheFile }) // counter.events.on('ready', () => { -// assert.equal(counter.value(), 14) +// assert.equal(counter.value, 14) // clearTimeout(timeout) // client1.disconnect() // done() @@ -104,9 +104,11 @@ // waitForPeers(daemon1, [daemon2.PeerId], name, (err, res) => { // waitForPeers(daemon2, [daemon1.PeerId], name, (err, res) => { +// console.log("load!!!") // const increaseCounter = (counter, i) => numbers[i].map((e) => counter.inc(e)) // Promise.map([counter1, counter2], increaseCounter, { concurrency: 1 }) // .then((res) => { +// console.log("..", res) // // wait for a while to make sure db's have been synced // setTimeout(() => { // assert.equal(counter2.value, 30) diff --git a/test/docstore.test.js b/test/docstore.test.js new file mode 100644 index 0000000..61451b1 --- /dev/null +++ b/test/docstore.test.js @@ -0,0 +1,191 @@ +'use strict' + +const assert = require('assert') +const rmrf = require('rimraf') +const IpfsNodeDaemon = require('ipfs-daemon/src/ipfs-node-daemon') +const IpfsNativeDaemon = require('ipfs-daemon/src/ipfs-native-daemon') +const OrbitDB = require('../src/OrbitDB') +const hasIpfsApiWithPubsub = require('./test-utils').hasIpfsApiWithPubsub +const config = require('./test-config') + +config.daemons.forEach((IpfsDaemon) => { + + describe('orbit-db - Document Store', function() { + this.timeout(config.timeout) + + let ipfs, client1, client2, db + + before(function (done) { + rmrf.sync(config.defaultIpfsDirectory) + rmrf.sync(config.defaultOrbitDBDirectory) + ipfs = new IpfsDaemon() + ipfs.on('error', done) + ipfs.on('ready', () => { + assert.equal(hasIpfsApiWithPubsub(ipfs), true) + client1 = new OrbitDB(ipfs, 'A') + client2 = new OrbitDB(ipfs, 'B') + done() + }) + }) + + after(() => { + if(client1) client1.disconnect() + if(client2) client2.disconnect() + ipfs.stop() + rmrf.sync(config.defaultOrbitDBDirectory) + rmrf.sync(config.defaultIpfsDirectory) + }) + + describe('Default index \'_id\'', function() { + beforeEach(() => { + db = client1.docstore(config.dbname, { replicate: false, maxHistory: 0 }) + }) + + it('put', () => { + const doc = { _id: 'hello world', doc: 'all the things'} + return db.put(doc) + .then(() => { + const value = db.get('hello world') + assert.deepEqual(value, [doc]) + }) + }) + + it('get - partial term match', () => { + const doc1 = { _id: 'hello world', doc: 'some things'} + const doc2 = { _id: 'hello universe', doc: 'all the things'} + const doc3 = { _id: 'sup world', doc: 'other things'} + return db.put(doc1) + .then(() => db.put(doc2)) + .then(() => db.put(doc3)) + .then(() => { + const value = db.get('hello') + assert.deepEqual(value, [doc1, doc2]) + }) + }) + + it('get after delete', () => { + const doc1 = { _id: 'hello world', doc: 'some things'} + const doc2 = { _id: 'hello universe', doc: 'all the things'} + const doc3 = { _id: 'sup world', doc: 'other things'} + return db.put(doc1) + .then(() => db.put(doc2)) + .then(() => db.put(doc3)) + .then(() => db.del('hello universe')) + .then(() => { + const value1 = db.get('hello') + const value2 = db.get('sup') + assert.deepEqual(value1, [doc1]) + assert.deepEqual(value2, [doc3]) + }) + }) + + it('put updates a value', () => { + const doc1 = { _id: 'hello world', doc: 'all the things'} + const doc2 = { _id: 'hello world', doc: 'some of the things'} + return db.put(doc1) + .then(() => db.put(doc2)) + .then(() => { + const value = db.get('hello') + assert.deepEqual(value, [doc2]) + }) + }) + + it('query', () => { + const doc1 = { _id: 'hello world', doc: 'all the things', views: 17} + const doc2 = { _id: 'sup world', doc: 'some of the things', views: 10} + const doc3 = { _id: 'hello other world', doc: 'none of the things', views: 5} + const doc4 = { _id: 'hey universe', doc: ''} + + return db.put(doc1) + .then(() => db.put(doc2)) + .then(() => db.put(doc3)) + .then(() => db.put(doc4)) + .then(() => { + const value1 = db.query((e) => e.views > 5) + const value2 = db.query((e) => e.views > 10) + const value3 = db.query((e) => e.views > 17) + assert.deepEqual(value1, [doc1, doc2]) + assert.deepEqual(value2, [doc1]) + assert.deepEqual(value3, []) + }) + }) + + it('query after delete', () => { + const doc1 = { _id: 'hello world', doc: 'all the things', views: 17} + const doc2 = { _id: 'sup world', doc: 'some of the things', views: 10} + const doc3 = { _id: 'hello other world', doc: 'none of the things', views: 5} + const doc4 = { _id: 'hey universe', doc: ''} + + return db.put(doc1) + .then(() => db.put(doc2)) + .then(() => db.put(doc3)) + .then(() => db.del('hello world')) + .then(() => db.put(doc4)) + .then(() => { + const value1 = db.query((e) => e.views >= 5) + const value2 = db.query((e) => e.views >= 10) + assert.deepEqual(value1, [doc2, doc3]) + assert.deepEqual(value2, [doc2]) + }) + }) + }) + + describe('Specified index', function() { + beforeEach(() => { + db = client1.docstore(config.dbname, { indexBy: 'doc', replicate: false, maxHistory: 0 }) + }) + + it('put', () => { + const doc = { _id: 'hello world', doc: 'all the things'} + return db.put(doc) + .then(() => { + const value = db.get('all') + assert.deepEqual(value, [doc]) + }) + }) + + it('get - matches specified index', () => { + const doc1 = { _id: 'hello world', doc: 'all the things'} + const doc2 = { _id: 'hello world', doc: 'some things'} + + return db.put(doc1) + .then(() => db.put(doc2)) + .then(() => { + const value1 = db.get('all') + const value2 = db.get('some') + assert.deepEqual(value1, [doc1]) + assert.deepEqual(value2, [doc2]) + }) + }) + }) + + describe('Sync', function() { + const doc1 = { _id: 'hello world', doc: 'all the things'} + const doc2 = { _id: 'moi moi', doc: 'everything'} + + const options = { + replicate: false, + maxHistory: 0, + } + + it('syncs databases', (done) => { + const db1 = client1.docstore(config.dbname, options) + const db2 = client2.docstore(config.dbname, options) + + db2.events.on('write', (dbname, hash, entry, heads) => { + assert.deepEqual(db1.get('hello world'), []) + db1.sync(heads) + }) + + db1.events.on('synced', () => { + const value = db1.get(doc1._id) + assert.deepEqual(value, [doc1]) + done() + }) + + db2.put(doc1) + .catch(done) + }) + }) + }) +}) diff --git a/test/eventlog.test.js b/test/eventlog.test.js new file mode 100644 index 0000000..15ce041 --- /dev/null +++ b/test/eventlog.test.js @@ -0,0 +1,387 @@ +'use strict' + +const assert = require('assert') +const rmrf = require('rimraf') +const mapSeries = require('./promise-map-series') +const OrbitDB = require('../src/OrbitDB') +const hasIpfsApiWithPubsub = require('./test-utils').hasIpfsApiWithPubsub +const first = require('./test-utils').first +const last = require('./test-utils').last +const config = require('./test-config') + +config.daemons.forEach((IpfsDaemon) => { + + describe('orbit-db - Eventlog', function() { + this.timeout(config.timeout) + + let ipfs, client1, client2, db + + before(function (done) { + rmrf.sync(config.defaultIpfsDirectory) + rmrf.sync(config.defaultOrbitDBDirectory) + ipfs = new IpfsDaemon() + ipfs.on('error', done) + ipfs.on('ready', () => { + assert.equal(hasIpfsApiWithPubsub(ipfs), true) + client1 = new OrbitDB(ipfs, 'A') + client2 = new OrbitDB(ipfs, 'B') + done() + }) + }) + + after(() => { + if(client1) client1.disconnect() + if(client2) client2.disconnect() + ipfs.stop() + rmrf.sync(config.defaultOrbitDBDirectory) + rmrf.sync(config.defaultIpfsDirectory) + }) + + describe('Eventlog', function() { + it('returns the added entry\'s hash, 1 entry', () => { + db = client1.eventlog(config.dbname, { replicate: false, maxHistory: 0 }) + return db.add('hello1') + .then((hash) => { + const items = db.iterator({ limit: -1 }).collect() + assert.notEqual(hash, null) + assert.equal(hash, last(items).hash) + assert.equal(items.length, 1) + }) + }) + + it('returns the added entry\'s hash, 2 entries', () => { + const prevHash = db.iterator().collect()[0].hash + return db.add('hello2') + .then((hash) => { + const items = db.iterator({ limit: -1 }).collect() + assert.equal(items.length, 2) + assert.notEqual(hash, null) + assert.notEqual(hash, prevHash) + assert.equal(hash, last(items).hash) + }) + }) + + it('adds five items', () => { + db = client1.eventlog(config.dbname, { replicate: false, maxHistory: 0 }) + return mapSeries([1, 2, 3, 4, 5], (i) => db.add('hello' + i)) + .then(() => { + const items = db.iterator({ limit: -1 }).collect() + assert.equal(items.length, 5) + assert.equal(first(items.map((f) => f.payload.value)), 'hello1') + assert.equal(last(items.map((f) => f.payload.value)), 'hello5') + }) + }) + + it('adds an item that is > 256 bytes', () => { + db = client1.eventlog(config.dbname, { replicate: false, maxHistory: 0 }) + + let msg = new Buffer(1024) + msg.fill('a') + return db.add(msg.toString()) + .then((hash) => { + assert.notEqual(hash, null) + assert.equal(hash.startsWith('Qm'), true) + assert.equal(hash.length, 46) + }) + }) + }) + + describe('Iterator', function() { + let items = [] + const itemCount = 5 + + beforeEach(() => { + items = [] + db = client1.eventlog(config.dbname, { replicate: false, maxHistory: 0 }) + return mapSeries([0, 1, 2, 3, 4], (i) => db.add('hello' + i)) + .then((res) => items = res) + }) + + describe('Defaults', function() { + it('returns an iterator', () => { + const iter = db.iterator() + const next = iter.next().value + assert.notEqual(iter, null) + assert.notEqual(next, null) + }) + + it('returns an item with the correct structure', () => { + const iter = db.iterator() + const next = iter.next().value + assert.notEqual(next, null) + assert.equal(next.hash.startsWith('Qm'), true) + assert.equal(next.payload.key, null) + assert.equal(next.payload.value, 'hello4') + }) + + it('implements Iterator interface', () => { + const iter = db.iterator({ limit: -1 }) + let messages = [] + + for(let i of iter) + messages.push(i.key) + + assert.equal(messages.length, items.length) + }) + + it('returns 1 item as default', () => { + const iter = db.iterator() + const first = iter.next().value + const second = iter.next().value + assert.equal(first.hash, items[items.length - 1]) + assert.equal(second, null) + assert.equal(first.payload.value, 'hello4') + }) + + it('returns items in the correct order', () => { + const amount = 3 + const iter = db.iterator({ limit: amount }) + let i = items.length - amount + for(let item of iter) { + assert.equal(item.payload.value, 'hello' + i) + i ++ + } + }) + }) + + describe('Collect', function() { + it('returns all items', () => { + const messages = db.iterator({ limit: -1 }).collect() + assert.equal(messages.length, items.length) + assert.equal(messages[0].payload.value, 'hello0') + assert.equal(messages[messages.length - 1].payload.value, 'hello4') + }) + + it('returns 1 item', () => { + const messages = db.iterator().collect() + assert.equal(messages.length, 1) + }) + + it('returns 3 items', () => { + const messages = db.iterator({ limit: 3 }).collect() + assert.equal(messages.length, 3) + }) + }) + + describe('Options: limit', function() { + it('returns 1 item when limit is 0', () => { + const iter = db.iterator({ limit: 1 }) + const first = iter.next().value + const second = iter.next().value + assert.equal(first.hash, last(items)) + assert.equal(second, null) + }) + + it('returns 1 item when limit is 1', () => { + const iter = db.iterator({ limit: 1 }) + const first = iter.next().value + const second = iter.next().value + assert.equal(first.hash, last(items)) + assert.equal(second, null) + }) + + it('returns 3 items', () => { + const iter = db.iterator({ limit: 3 }) + const first = iter.next().value + const second = iter.next().value + const third = iter.next().value + const fourth = iter.next().value + assert.equal(first.hash, items[items.length - 3]) + assert.equal(second.hash, items[items.length - 2]) + assert.equal(third.hash, items[items.length - 1]) + assert.equal(fourth, null) + }) + + it('returns all items', () => { + const messages = db.iterator({ limit: -1 }) + .collect() + .map((e) => e.hash) + + messages.reverse() + assert.equal(messages.length, items.length) + assert.equal(messages[0], items[items.length - 1]) + }) + + it('returns all items when limit is bigger than -1', () => { + const messages = db.iterator({ limit: -300 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, items.length) + assert.equal(messages[0], items[0]) + }) + + it('returns all items when limit is bigger than number of items', () => { + const messages = db.iterator({ limit: 300 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, items.length) + assert.equal(messages[0], items[0]) + }) + }) + + describe('Option: ranges', function() { + describe('gt & gte', function() { + it('returns 1 item when gte is the head', () => { + const messages = db.iterator({ gte: last(items), limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 1) + assert.equal(messages[0], last(items)) + }) + + it('returns 0 items when gt is the head', () => { + const messages = db.iterator({ gt: last(items) }).collect() + assert.equal(messages.length, 0) + }) + + it('returns 2 item when gte is defined', () => { + const gte = items[items.length - 2] + const messages = db.iterator({ gte: gte, limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 2) + assert.equal(messages[0], items[items.length - 2]) + assert.equal(messages[1], items[items.length - 1]) + }) + + it('returns all items when gte is the root item', () => { + const messages = db.iterator({ gte: items[0], limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, items.length) + assert.equal(messages[0], items[0]) + assert.equal(messages[messages.length - 1], last(items)) + }) + + it('returns items when gt is the root item', () => { + const messages = db.iterator({ gt: items[0], limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, itemCount - 1) + assert.equal(messages[0], items[1]) + assert.equal(messages[3], last(items)) + }) + + it('returns items when gt is defined', () => { + const messages = db.iterator({ limit: -1}) + .collect() + .map((e) => e.hash) + + const gt = messages[2] + + const messages2 = db.iterator({ gt: gt, limit: 100 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages2.length, 2) + assert.equal(messages2[0], messages[messages.length - 2]) + assert.equal(messages2[1], messages[messages.length - 1]) + }) + }) + + describe('lt & lte', function() { + it('returns one item after head when lt is the head', () => { + const messages = db.iterator({ lt: last(items) }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 1) + assert.equal(messages[0], items[items.length - 2]) + }) + + it('returns all items when lt is head and limit is -1', () => { + const messages = db.iterator({ lt: last(items), limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, items.length - 1) + assert.equal(messages[0], items[0]) + assert.equal(messages[messages.length - 1], items[items.length - 2]) + }) + + it('returns 3 items when lt is head and limit is 3', () => { + const messages = db.iterator({ lt: last(items), limit: 3 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 3) + assert.equal(messages[0], items[items.length - 4]) + assert.equal(messages[2], items[items.length - 2]) + }) + + it('returns null when lt is the root item', () => { + const messages = db.iterator({ lt: items[0] }).collect() + assert.equal(messages.length, 0) + }) + + it('returns one item when lte is the root item', () => { + const messages = db.iterator({ lte: items[0] }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 1) + assert.equal(messages[0], items[0]) + }) + + it('returns all items when lte is the head', () => { + const messages = db.iterator({ lte: last(items), limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, itemCount) + assert.equal(messages[0], items[0]) + assert.equal(messages[4], last(items)) + }) + + it('returns 3 items when lte is the head', () => { + const messages = db.iterator({ lte: last(items), limit: 3 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 3) + assert.equal(messages[0], items[items.length - 3]) + assert.equal(messages[1], items[items.length - 2]) + assert.equal(messages[2], last(items)) + }) + }) + }) + }) + + describe('sync', () => { + const options = { + replicate: false, + } + + it('syncs databases', (done) => { + const db1 = client1.eventlog(config.dbname, options) + const db2 = client2.eventlog(config.dbname, options) + + db1.events.on('error', (e) => { + console.log(e.stack()) + done(e) + }) + + db2.events.on('write', (dbname, hash, entry, heads) => { + assert.equal(db1.iterator({ limit: -1 }).collect().length, 0) + db1.sync(heads) + }) + + db1.events.on('synced', () => { + const items = db1.iterator({ limit: -1 }).collect() + assert.equal(items.length, 1) + assert.equal(items[0].payload.value, 'hello2') + done() + }) + + db2.add('hello2') + .catch(done) + }) + }) + }) +}) diff --git a/test/feed.test.js b/test/feed.test.js new file mode 100644 index 0000000..f2e20d4 --- /dev/null +++ b/test/feed.test.js @@ -0,0 +1,428 @@ +'use strict' + +const assert = require('assert') +const rmrf = require('rimraf') +const mapSeries = require('./promise-map-series') +const OrbitDB = require('../src/OrbitDB') +const hasIpfsApiWithPubsub = require('./test-utils').hasIpfsApiWithPubsub +const first = require('./test-utils').first +const last = require('./test-utils').last +const config = require('./test-config') + +config.daemons.forEach((IpfsDaemon) => { + + describe('orbit-db - Feed', function() { + this.timeout(config.timeout) + + let ipfs, client1, client2, db + + before(function (done) { + rmrf.sync(config.defaultIpfsDirectory) + rmrf.sync(config.defaultOrbitDBDirectory) + ipfs = new IpfsDaemon() + ipfs.on('error', done) + ipfs.on('ready', () => { + assert.equal(hasIpfsApiWithPubsub(ipfs), true) + client1 = new OrbitDB(ipfs, 'A') + client2 = new OrbitDB(ipfs, 'B') + done() + }) + }) + + after(() => { + if(client1) client1.disconnect() + if(client2) client2.disconnect() + ipfs.stop() + rmrf.sync(config.defaultOrbitDBDirectory) + rmrf.sync(config.defaultIpfsDirectory) + }) + + describe('Feed', function() { + it('returns the added entry\'s hash, 1 entry', () => { + db = client1.feed(config.dbname, { replicate: false, maxHistory: 0 }) + return db.add('hello1') + .then((hash) => { + const items = db.iterator({ limit: -1 }).collect() + assert.notEqual(hash, null) + assert.equal(hash, last(items).hash) + assert.equal(items.length, 1) + }) + }) + + it('returns the added entry\'s hash, 2 entries', () => { + const prevHash = db.iterator().collect()[0].hash + return db.add('hello2') + .then((hash) => { + const items = db.iterator({ limit: -1 }).collect() + assert.equal(items.length, 2) + assert.notEqual(hash, null) + assert.notEqual(hash, prevHash) + assert.equal(hash, last(items).hash) + }) + }) + + it('adds five items', () => { + db = client1.feed(config.dbname, { replicate: false, maxHistory: 0 }) + return mapSeries([1, 2, 3, 4, 5], (i) => db.add('hello' + i)) + .then(() => { + const items = db.iterator({ limit: -1 }).collect() + assert.equal(items.length, 5) + assert.equal(first(items.map((f) => f.payload.value)), 'hello1') + assert.equal(last(items.map((f) => f.payload.value)), 'hello5') + }) + }) + + it('adds an item that is > 256 bytes', () => { + db = client1.feed(config.dbname, { replicate: false, maxHistory: 0 }) + + let msg = new Buffer(1024) + msg.fill('a') + return db.add(msg.toString()) + .then((hash) => { + assert.notEqual(hash, null) + assert.equal(hash.startsWith('Qm'), true) + assert.equal(hash.length, 46) + }) + }) + + it('deletes an item when only one item in the database', () => { + db = client1.feed(config.dbname, { replicate: false, maxHistory: 0 }) + + return db.add('hello3') + .then((hash) => db.remove(hash)) + .then((delopHash) => { + const items = db.iterator().collect() + assert.equal(delopHash.startsWith('Qm'), true) + assert.equal(items.length, 0) + }) + }) + + it('deletes an item when two items in the database', () => { + db = client1.feed(config.dbname, { replicate: false, maxHistory: 0 }) + + return db.add('hello1') + .then(() => db.add('hello2')) + .then((hash) => db.remove(hash)) + .then(() => { + const items = db.iterator({ limit: -1 }).collect() + assert.equal(items.length, 1) + assert.equal(first(items).payload.value, 'hello1') + }) + }) + + it('deletes an item between adds', () => { + db = client1.feed(config.dbname, { replicate: false, maxHistory: 0 }) + + let hash + return db.add('hello1') + .then((res) => hash = res) + .then(() => db.add('hello2')) + .then(() => db.remove(hash)) + .then(() => db.add('hello3')) + .then(() => { + const items = db.iterator({ limit: -1 }).collect() + assert.equal(items.length, 2) + + const firstItem = first(items) + const secondItem = items[1] + assert.equal(firstItem.hash.startsWith('Qm'), true) + assert.equal(firstItem.payload.key, null) + assert.equal(firstItem.payload.value, 'hello2') + assert.equal(secondItem.payload.value, 'hello3') + }) + }) + }) + + describe('Iterator', function() { + let items = [] + const itemCount = 5 + + beforeEach(() => { + items = [] + db = client1.feed(config.dbname, { replicate: false, maxHistory: 0 }) + return mapSeries([0, 1, 2, 3, 4], (i) => db.add('hello' + i)) + .then((res) => items = res) + }) + + describe('Defaults', function() { + it('returns an iterator', () => { + const iter = db.iterator() + const next = iter.next().value + assert.notEqual(iter, null) + assert.notEqual(next, null) + }) + + it('returns an item with the correct structure', () => { + const iter = db.iterator() + const next = iter.next().value + assert.notEqual(next, null) + assert.equal(next.hash.startsWith('Qm'), true) + assert.equal(next.payload.key, null) + assert.equal(next.payload.value, 'hello4') + }) + + it('implements Iterator interface', () => { + const iter = db.iterator({ limit: -1 }) + let messages = [] + + for(let i of iter) + messages.push(i.key) + + assert.equal(messages.length, items.length) + }) + + it('returns 1 item as default', () => { + const iter = db.iterator() + const first = iter.next().value + const second = iter.next().value + assert.equal(first.hash, items[items.length - 1]) + assert.equal(second, null) + assert.equal(first.payload.value, 'hello4') + }) + + it('returns items in the correct order', () => { + const amount = 3 + const iter = db.iterator({ limit: amount }) + let i = items.length - amount + for(let item of iter) { + assert.equal(item.payload.value, 'hello' + i) + i ++ + } + }) + }) + + describe('Collect', function() { + it('returns all items', () => { + const messages = db.iterator({ limit: -1 }).collect() + assert.equal(messages.length, items.length) + assert.equal(messages[0].payload.value, 'hello0') + assert.equal(messages[messages.length - 1].payload.value, 'hello4') + }) + + it('returns 1 item', () => { + const messages = db.iterator().collect() + assert.equal(messages.length, 1) + }) + + it('returns 3 items', () => { + const messages = db.iterator({ limit: 3 }).collect() + assert.equal(messages.length, 3) + }) + }) + + describe('Options: limit', function() { + it('returns 1 item when limit is 0', () => { + const iter = db.iterator({ limit: 1 }) + const first = iter.next().value + const second = iter.next().value + assert.equal(first.hash, last(items)) + assert.equal(second, null) + }) + + it('returns 1 item when limit is 1', () => { + const iter = db.iterator({ limit: 1 }) + const first = iter.next().value + const second = iter.next().value + assert.equal(first.hash, last(items)) + assert.equal(second, null) + }) + + it('returns 3 items', () => { + const iter = db.iterator({ limit: 3 }) + const first = iter.next().value + const second = iter.next().value + const third = iter.next().value + const fourth = iter.next().value + assert.equal(first.hash, items[items.length - 3]) + assert.equal(second.hash, items[items.length - 2]) + assert.equal(third.hash, items[items.length - 1]) + assert.equal(fourth, null) + }) + + it('returns all items', () => { + const messages = db.iterator({ limit: -1 }) + .collect() + .map((e) => e.hash) + + messages.reverse() + assert.equal(messages.length, items.length) + assert.equal(messages[0], items[items.length - 1]) + }) + + it('returns all items when limit is bigger than -1', () => { + const messages = db.iterator({ limit: -300 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, items.length) + assert.equal(messages[0], items[0]) + }) + + it('returns all items when limit is bigger than number of items', () => { + const messages = db.iterator({ limit: 300 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, items.length) + assert.equal(messages[0], items[0]) + }) + }) + + describe('Option: ranges', function() { + describe('gt & gte', function() { + it('returns 1 item when gte is the head', () => { + const messages = db.iterator({ gte: last(items), limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 1) + assert.equal(messages[0], last(items)) + }) + + it('returns 0 items when gt is the head', () => { + const messages = db.iterator({ gt: last(items) }).collect() + assert.equal(messages.length, 0) + }) + + it('returns 2 item when gte is defined', () => { + const gte = items[items.length - 2] + const messages = db.iterator({ gte: gte, limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 2) + assert.equal(messages[0], items[items.length - 2]) + assert.equal(messages[1], items[items.length - 1]) + }) + + it('returns all items when gte is the root item', () => { + const messages = db.iterator({ gte: items[0], limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, items.length) + assert.equal(messages[0], items[0]) + assert.equal(messages[messages.length - 1], last(items)) + }) + + it('returns items when gt is the root item', () => { + const messages = db.iterator({ gt: items[0], limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, itemCount - 1) + assert.equal(messages[0], items[1]) + assert.equal(messages[3], last(items)) + }) + + it('returns items when gt is defined', () => { + const messages = db.iterator({ limit: -1}) + .collect() + .map((e) => e.hash) + + const gt = messages[2] + + const messages2 = db.iterator({ gt: gt, limit: 100 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages2.length, 2) + assert.equal(messages2[0], messages[messages.length - 2]) + assert.equal(messages2[1], messages[messages.length - 1]) + }) + }) + + describe('lt & lte', function() { + it('returns one item after head when lt is the head', () => { + const messages = db.iterator({ lt: last(items) }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 1) + assert.equal(messages[0], items[items.length - 2]) + }) + + it('returns all items when lt is head and limit is -1', () => { + const messages = db.iterator({ lt: last(items), limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, items.length - 1) + assert.equal(messages[0], items[0]) + assert.equal(messages[messages.length - 1], items[items.length - 2]) + }) + + it('returns 3 items when lt is head and limit is 3', () => { + const messages = db.iterator({ lt: last(items), limit: 3 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 3) + assert.equal(messages[0], items[items.length - 4]) + assert.equal(messages[2], items[items.length - 2]) + }) + + it('returns null when lt is the root item', () => { + const messages = db.iterator({ lt: items[0] }).collect() + assert.equal(messages.length, 0) + }) + + it('returns one item when lte is the root item', () => { + const messages = db.iterator({ lte: items[0] }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 1) + assert.equal(messages[0], items[0]) + }) + + it('returns all items when lte is the head', () => { + const messages = db.iterator({ lte: last(items), limit: -1 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, itemCount) + assert.equal(messages[0], items[0]) + assert.equal(messages[4], last(items)) + }) + + it('returns 3 items when lte is the head', () => { + const messages = db.iterator({ lte: last(items), limit: 3 }) + .collect() + .map((e) => e.hash) + + assert.equal(messages.length, 3) + assert.equal(messages[0], items[items.length - 3]) + assert.equal(messages[1], items[items.length - 2]) + assert.equal(messages[2], last(items)) + }) + }) + }) + }) + + describe('sync', () => { + const options = { + replicate: false, + } + + it('syncs databases', (done) => { + const db1 = client1.feed(config.dbname, options) + const db2 = client2.feed(config.dbname, options) + db2.events.on('write', (dbname, hash, entry, heads) => { + assert.equal(db1.iterator({ limit: -1 }).collect().length, 0) + db1.sync(heads) + }) + + db1.events.on('synced', () => { + const items = db1.iterator({ limit: -1 }).collect() + assert.equal(items.length, 1) + assert.equal(items[0].payload.value, 'hello2') + done() + }) + + db2.add('hello2') + .catch(done) + }) + }) + }) +}) diff --git a/test/ipfs-daemons.conf.js b/test/ipfs-daemons.conf.js index 9e53847..580476a 100644 --- a/test/ipfs-daemons.conf.js +++ b/test/ipfs-daemons.conf.js @@ -6,16 +6,16 @@ module.exports = { Swarm: ['/ip4/0.0.0.0/tcp/0'], Gateway: '/ip4/0.0.0.0/tcp/0' }, + Bootstrap: [], Discovery: { MDNS: { Enabled: true, Interval: 10 }, webRTCStar: { - Enabled: true + Enabled: false } - }, - Bootstrap: [] + } }, daemon2: { IpfsDataDir: '/tmp/orbit-db-tests-2', @@ -24,15 +24,15 @@ module.exports = { Swarm: ['/ip4/0.0.0.0/tcp/0'], Gateway: '/ip4/0.0.0.0/tcp/0' }, + Bootstrap: [], Discovery: { MDNS: { Enabled: true, Interval: 10 }, webRTCStar: { - Enabled: true + Enabled: false } - }, - Bootstrap: [] - }, + } + } } diff --git a/test/kvstore.test.js b/test/kvstore.test.js new file mode 100644 index 0000000..9f207fe --- /dev/null +++ b/test/kvstore.test.js @@ -0,0 +1,163 @@ +'use strict' + +const assert = require('assert') +const rmrf = require('rimraf') +const OrbitDB = require('../src/OrbitDB') +const hasIpfsApiWithPubsub = require('./test-utils').hasIpfsApiWithPubsub +const config = require('./test-config') + +config.daemons.forEach((IpfsDaemon) => { + + describe('orbit-db - Key-Value Store', function() { + this.timeout(config.timeout) + + let ipfs, client1, client2, db + + before(function (done) { + rmrf.sync(config.defaultIpfsDirectory) + rmrf.sync(config.defaultOrbitDBDirectory) + ipfs = new IpfsDaemon() + ipfs.on('error', done) + ipfs.on('ready', () => { + assert.equal(hasIpfsApiWithPubsub(ipfs), true) + client1 = new OrbitDB(ipfs, 'A') + client2 = new OrbitDB(ipfs, 'B') + done() + }) + }) + + after(() => { + if(client1) client1.disconnect() + if(client2) client2.disconnect() + ipfs.stop() + rmrf.sync(config.defaultOrbitDBDirectory) + rmrf.sync(config.defaultIpfsDirectory) + }) + + beforeEach(() => { + db = client1.kvstore(config.dbname, { replicate: false, maxHistory: 0 }) + }) + + it('put', () => { + return db.put('key1', 'hello1') + .then(() => { + const value = db.get('key1') + assert.equal(value, 'hello1') + }) + }) + + it('get', () => { + return db.put('key1', 'hello2') + .then(() => { + const value = db.get('key1') + assert.equal(value, 'hello2') + }) + }) + + it('put updates a value', () => { + return db.put('key1', 'hello3') + .then(() => db.put('key1', 'hello4')) + .then(() => { + const value = db.get('key1') + assert.equal(value, 'hello4') + }) + }) + + it('set is an alias for put', () => { + return db.set('key1', 'hello5') + .then(() => { + const value = db.get('key1') + assert.equal(value, 'hello5') + }) + }) + + it('put/get - multiple keys', () => { + return db.put('key1', 'hello1') + .then(() => db.put('key2', 'hello2')) + .then(() => db.put('key3', 'hello3')) + .then(() => { + const v1 = db.get('key1') + const v2 = db.get('key2') + const v3 = db.get('key3') + assert.equal(v1, 'hello1') + assert.equal(v2, 'hello2') + assert.equal(v3, 'hello3') + }) + }) + + it('deletes a key', () => { + return db.put('key1', 'hello!') + .then(() => db.del('key1')) + .then(() => { + const value = db.get('key1') + assert.equal(value, null) + }) + }) + + it('deletes a key after multiple updates', () => { + return db.put('key1', 'hello1') + .then(() => db.put('key1', 'hello2')) + .then(() => db.put('key1', 'hello3')) + .then(() => db.del('key1')) + .then(() => { + const value = db.get('key1') + assert.equal(value, null) + }) + }) + + it('get - integer value', () => { + const val = 123 + return db.put('key1', val) + .then(() => { + const v1 = db.get('key1') + assert.equal(v1, val) + }) + }) + + it('get - object value', () => { + const val = { one: 'first', two: 2 } + return db.put('key1', val) + .then(() => { + const v1 = db.get('key1') + assert.deepEqual(v1, val) + }) + }) + + it('get - array value', () => { + const val = [1, 2, 3, 4, 5] + return db.put('key1', val) + .then(() => { + const v1 = db.get('key1') + assert.deepEqual(v1, val) + }) + }) + + describe('sync', () => { + const options = { + replicate: false, + } + + it('syncs databases', (done) => { + const db1 = client1.kvstore(config.dbname, options) + const db2 = client2.kvstore(config.dbname, options) + + db1.events.on('error', done) + + db2.events.on('write', (dbname, hash, entry, heads) => { + assert.equal(db1.get('key1'), null) + assert.equal(db2.get('key1'), 'hello1') + db1.sync(heads) + }) + + db1.events.on('synced', () => { + const value = db1.get('key1') + assert.equal(value, 'hello1') + done() + }) + + db2.put('key1', 'hello1') + .catch(done) + }) + }) + }) +}) diff --git a/test/persistency.js b/test/persistency.js new file mode 100644 index 0000000..38744f6 --- /dev/null +++ b/test/persistency.js @@ -0,0 +1,96 @@ +'use strict' + +const assert = require('assert') +const mapSeries = require('./promise-map-series') +const rmrf = require('rimraf') +const hasIpfsApiWithPubsub = require('./test-utils').hasIpfsApiWithPubsub +const OrbitDB = require('../src/OrbitDB') +const config = require('./test-config') + +// Daemon settings +const daemonsConf = require('./ipfs-daemons.conf.js') + +// orbit-db path +const testDataDir = './orbit-db' + +config.daemons.forEach((IpfsDaemon) => { + + describe('orbit-db - Persistency', function() { + this.timeout(config.timeout) + + let ipfs1, ipfs2, client1, client2, db1, db2 + + const removeDirectories = () => { + rmrf.sync(daemonsConf.daemon1.IpfsDataDir) + rmrf.sync(daemonsConf.daemon2.IpfsDataDir) + rmrf.sync(config.defaultIpfsDirectory) + rmrf.sync(config.defaultOrbitDBDirectory) + rmrf.sync(testDataDir) + } + + before(function (done) { + removeDirectories() + ipfs1 = new IpfsDaemon(daemonsConf.daemon1) + ipfs1.on('error', done) + ipfs1.on('ready', () => { + assert.equal(hasIpfsApiWithPubsub(ipfs1), true) + ipfs2 = new IpfsDaemon(daemonsConf.daemon2) + ipfs2.on('error', done) + ipfs2.on('ready', () => { + assert.equal(hasIpfsApiWithPubsub(ipfs2), true) + client1 = new OrbitDB(ipfs1, "one") + client2 = new OrbitDB(ipfs2, "two") + done() + }) + }) + }) + + after(() => { + ipfs1.stop() + ipfs2.stop() + removeDirectories() + }) + + describe('load', function() { + it('loads database from local cache', function(done) { + const entryCount = 100 + const entryArr = [] + + for (let i = 0; i < entryCount; i ++) + entryArr.push(i) + + const options = { + replicate: false, + maxHistory: -1, + cachePath: testDataDir, + } + + let db = client1.eventlog(config.dbname, options) + + db.events.on('error', done) + db.load().then(function () { + mapSeries(entryArr, (i) => db.add('hello' + i)) + .then(function() { + db = null + db = client1.eventlog(config.dbname, options) + db.events.on('error', done) + db.events.on('ready', () => { + try { + const items = db.iterator({ limit: -1 }).collect() + assert.equal(items.length, entryCount) + assert.equal(items[0].payload.value, 'hello0') + assert.equal(items[entryCount - 1].payload.value, 'hello99') + done() + } catch(e) { + done(e) + } + }) + db.load() + .catch(done) + }) + .catch(done) + }).catch(done) + }) + }) + }) +}) diff --git a/test/promise-map-series.js b/test/promise-map-series.js new file mode 100644 index 0000000..a2b0221 --- /dev/null +++ b/test/promise-map-series.js @@ -0,0 +1,16 @@ +'use strict' + +// https://gist.github.com/dignifiedquire/dd08d2f3806a7b87f45b00c41fe109b7 + +module.exports = function mapSeries (list, func) { + const res = [] + return list.reduce((acc, next) => { + return acc.then((val) => { + res.push(val) + return func(next) + }) + }, Promise.resolve(null)).then((val) => { + res.push(val) + return res.slice(1) + }) +} diff --git a/test/replicate.test.js b/test/replicate.test.js index 7df34de..21a6703 100644 --- a/test/replicate.test.js +++ b/test/replicate.test.js @@ -1,66 +1,50 @@ 'use strict' -const _ = require('lodash') -const fs = require('fs') -const path = require('path') const assert = require('assert') -const async = require('asyncawait/async') -const await = require('asyncawait/await') -const OrbitDB = require('../src/OrbitDB') +const mapSeries = require('p-each-series') const rmrf = require('rimraf') -const IpfsNodeDaemon = require('ipfs-daemon/src/ipfs-node-daemon') -const IpfsNativeDaemon = require('ipfs-daemon/src/ipfs-native-daemon') - -if (typeof window !== 'undefined') - window.LOG = 'ERROR' - -// Data directories -const defaultIpfsDirectory = './ipfs' -const defaultOrbitDBDirectory = './orbit-db' +const hasIpfsApiWithPubsub = require('./test-utils').hasIpfsApiWithPubsub +const OrbitDB = require('../src/OrbitDB') +const config = require('./test-config') // Daemon settings const daemonsConf = require('./ipfs-daemons.conf.js') -const databaseName = 'oribt-db-tests' - -const hasIpfsApiWithPubsub = (ipfs) => { - return ipfs.object.get !== undefined - && ipfs.object.put !== undefined - // && ipfs.pubsub.publish !== undefined - // && ipfs.pubsub.subscribe !== undefined -} - +// Shared database name const waitForPeers = (ipfs, channel) => { - return new Promise((resolve) => { - console.log("Waiting for peers for '" + channel + "'...") + return new Promise((resolve, reject) => { + console.log("Waiting for peers...") const interval = setInterval(() => { ipfs.pubsub.peers(channel) - // The tests pass if used with swarm.peers (peers find each other) - // ipfs.swarm.peers() .then((peers) => { - // console.log(peers) if (peers.length > 0) { + console.log("Found peers, running tests...") clearInterval(interval) resolve() } }) + .catch((e) => { + clearInterval(interval) + reject(e) + }) }, 1000) }) } -// [IpfsNativeDaemon, IpfsNodeDaemon].forEach((IpfsDaemon) => { -[IpfsNodeDaemon].forEach((IpfsDaemon) => { +config.daemons.forEach((IpfsDaemon) => { - describe('orbit-db replication', function() { - this.timeout(40000) + describe('orbit-db - Replication', function() { + this.timeout(config.timeout) let ipfs1, ipfs2, client1, client2, db1, db2 - const removeDirectories= () => { + const removeDirectories = () => { rmrf.sync(daemonsConf.daemon1.IpfsDataDir) rmrf.sync(daemonsConf.daemon2.IpfsDataDir) - rmrf.sync(defaultIpfsDirectory) - rmrf.sync(defaultOrbitDBDirectory) + rmrf.sync(config.defaultIpfsDirectory) + rmrf.sync(config.defaultOrbitDBDirectory) + rmrf.sync('/tmp/daemon1') + rmrf.sync('/tmp/daemon2') } before(function (done) { @@ -73,57 +57,77 @@ const waitForPeers = (ipfs, channel) => { ipfs2.on('error', done) ipfs2.on('ready', () => { assert.equal(hasIpfsApiWithPubsub(ipfs2), true) - client1 = new OrbitDB(ipfs1, databaseName) - client2 = new OrbitDB(ipfs2, databaseName + '2') + client1 = new OrbitDB(ipfs1, "one") + client2 = new OrbitDB(ipfs2, "two") done() }) }) }) - after(() => { - ipfs1.stop() - ipfs2.stop() + after((done) => { + if (client1) client1.disconnect() + if (client2) client2.disconnect() + if (ipfs1) ipfs1.stop() + if (ipfs2) ipfs2.stop() removeDirectories() + setTimeout(() => done(), 10000) }) describe('two peers', function() { beforeEach(() => { - db1 = client1.eventlog(databaseName, { maxHistory: 0 }) - db2 = client2.eventlog(databaseName, { maxHistory: 0 }) + db1 = client1.eventlog(config.dbname, { maxHistory: 1, cachePath: '/tmp/daemon1' }) + db2 = client2.eventlog(config.dbname, { maxHistory: 1, cachePath: '/tmp/daemon2' }) }) - it.only('replicates database of 1 entry', (done) => { - waitForPeers(ipfs1, databaseName + '2') - .then(async(() => { - db2.events.on('history', (db, data) => { + it('replicates database of 1 entry', (done) => { + waitForPeers(ipfs1, config.dbname) + .then(() => { + db2.events.once('error', done) + db2.events.once('synced', (db) => { const items = db2.iterator().collect() assert.equal(items.length, 1) assert.equal(items[0].payload.value, 'hello') done() }) db1.add('hello') - })) + .catch(done) + }) + .catch(done) }) it('replicates database of 100 entries', (done) => { const entryCount = 100 - waitForPeers(ipfs1, databaseName + '2') - .then(async(() => { + const entryArr = [] + let timer + + for (let i = 0; i < entryCount; i ++) + entryArr.push(i) + + waitForPeers(ipfs1, config.dbname) + .then(() => { let count = 0 - db2.events.on('history', (db, data) => { - count ++ - if (count === entryCount) { - const items = db2.iterator({ limit: 100 }).collect() - assert.equal(items.length, entryCount) - assert.equal(items[0].payload.value, 'hello0') - assert.equal(_.last(items).payload.value, 'hello99') - done() + db2.events.once('error', done) + db2.events.on('synced', (d) => { + if (count === entryCount && !timer) { + timer = setInterval(() => { + const items = db2.iterator({ limit: -1 }).collect() + if (items.length === count) { + clearInterval(timer) + assert.equal(items.length, entryCount) + assert.equal(items[0].payload.value, 'hello0') + assert.equal(items[items.length - 1].payload.value, 'hello99') + setTimeout(done, 5000) + } + }, 1000) } }) - for(let i = 0; i < entryCount; i ++) - await(db1.add('hello' + i)) - })) + db1.events.on('write', () => count++) + + mapSeries(entryArr, (i) => db1.add('hello' + i)) + .catch(done) + }) + .catch(done) }) }) }) diff --git a/test/test-config.js b/test/test-config.js new file mode 100644 index 0000000..68a14d4 --- /dev/null +++ b/test/test-config.js @@ -0,0 +1,18 @@ +'use strict' + +const IpfsNodeDaemon = require('ipfs-daemon/src/ipfs-node-daemon') +const IpfsNativeDaemon = require('ipfs-daemon/src/ipfs-native-daemon') +const testDaemons = require('./test-daemons') + +// Set logplease logging level if in the browser +if (typeof window !== 'undefined') + window.LOG = 'ERROR' + +// Config +module.exports = { + daemons: testDaemons, + timeout: 60000, + defaultIpfsDirectory: './ipfs', + defaultOrbitDBDirectory: './orbit-db', + dbname: 'abcdefghijklmn', +} diff --git a/test/test-daemons.js b/test/test-daemons.js new file mode 100644 index 0000000..865374d --- /dev/null +++ b/test/test-daemons.js @@ -0,0 +1,9 @@ +'use strict' + +const IpfsNodeDaemon = require('ipfs-daemon/src/ipfs-node-daemon') +const IpfsNativeDaemon = require('ipfs-daemon/src/ipfs-native-daemon') + +// module.exports = [IpfsNodeDaemon] +// module.exports = [IpfsNativeDaemon] +// module.exports = [IpfsNativeDaemon, IpfsNodeDaemon] +module.exports = [IpfsNodeDaemon, IpfsNativeDaemon] diff --git a/test/test-utils.js b/test/test-utils.js new file mode 100644 index 0000000..187d461 --- /dev/null +++ b/test/test-utils.js @@ -0,0 +1,18 @@ +'use strict' + +// Helper functions + +exports.hasIpfsApiWithPubsub = (ipfs) => { + return ipfs.object.get !== undefined + && ipfs.object.put !== undefined + && ipfs.pubsub.publish !== undefined + && ipfs.pubsub.subscribe !== undefined +} + +exports.first = (arr) => { + return arr[0] +} + +exports.last = (arr) => { + return arr[arr.length - 1] +}