From 9a171da4129114af93ee90ce12b7f8b87dc172c1 Mon Sep 17 00:00:00 2001 From: Fergie McDowall Date: Fri, 23 Jun 2017 14:35:25 +0200 Subject: [PATCH] feat(add): add is now a writable stream add is no a writable stream and not a transform stream. This makes it more difficult to track progress, but makes the API much more robust --- dist/search-index.js | 2707 +++++++++++-------- dist/search-index.min.js | 30 +- docs/demo/search-index.min.js | 30 +- package.json | 4 +- test/node/mocha-tests/328-test.js | 2 +- test/node/mocha-tests/boost-test.js | 5 +- test/node/mocha-tests/bucket-test.js | 3 +- test/node/mocha-tests/delete-test.js | 7 +- test/node/mocha-tests/facet-test.js | 3 +- test/node/mocha-tests/fieldsToStore-test.js | 7 +- test/node/mocha-tests/flush-test.js | 5 +- test/node/mocha-tests/get-test.js | 3 +- test/node/mocha-tests/indexing-test-2.js | 3 +- test/node/mocha-tests/indexing-test.js | 28 +- test/node/mocha-tests/instantiation-test.js | 6 +- test/node/mocha-tests/matching-test.js | 5 +- test/node/mocha-tests/or-test.js | 5 +- test/node/mocha-tests/phrase-search-test.js | 20 +- test/node/mocha-tests/preserve-case-test.js | 4 +- test/node/mocha-tests/relevancy-test.js | 5 +- test/node/mocha-tests/scan-test.js | 5 +- test/node/mocha-tests/search-test.js | 4 +- test/node/mocha-tests/sorting-test.js | 5 +- test/node/mocha-tests/sqlite-test.js | 4 +- test/node/mocha-tests/stopword-test.js | 6 +- test/node/mocha-tests/stream-test.js | 2 +- test/node/tape-tests/classifier-test.js | 2 +- test/node/tape-tests/stream-test.js | 10 +- 28 files changed, 1588 insertions(+), 1332 deletions(-) diff --git a/dist/search-index.js b/dist/search-index.js index acde4ff4..dd9daa2d 100644 --- a/dist/search-index.js +++ b/dist/search-index.js @@ -32,6 +32,7 @@ const getAdder = function (SearchIndex, done) { SearchIndex.add = searchIndexAdder.add SearchIndex.callbackyAdd = searchIndexAdder.concurrentAdd // deprecated SearchIndex.concurrentAdd = searchIndexAdder.concurrentAdd + SearchIndex.concurrentDel = searchIndexAdder.concurrentDel SearchIndex.createWriteStream = searchIndexAdder.createWriteStream SearchIndex.dbWriteStream = searchIndexAdder.dbWriteStream SearchIndex.defaultPipeline = searchIndexAdder.defaultPipeline @@ -47,6 +48,7 @@ const getSearcher = function (SearchIndex, done) { SearchIndex.availableFields = searchIndexSearcher.availableFields SearchIndex.buckets = searchIndexSearcher.bucketStream SearchIndex.categorize = searchIndexSearcher.categoryStream + SearchIndex.classify = searchIndexSearcher.classify SearchIndex.dbReadStream = searchIndexSearcher.dbReadStream SearchIndex.get = searchIndexSearcher.get SearchIndex.match = searchIndexSearcher.match @@ -81,7 +83,7 @@ const getOptions = function (options, done) { } } -},{"./siUtil.js":2,"bunyan":10,"leveldown":58,"levelup":71,"search-index-adder":101,"search-index-searcher":105}],2:[function(require,module,exports){ +},{"./siUtil.js":2,"bunyan":9,"leveldown":57,"levelup":70,"search-index-adder":103,"search-index-searcher":107}],2:[function(require,module,exports){ module.exports = function(siOptions) { var siUtil = {} @@ -611,98 +613,30 @@ var objectKeys = Object.keys || function (obj) { }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"util/":131}],4:[function(require,module,exports){ +},{"util/":134}],4:[function(require,module,exports){ (function (process,global){ (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.async = global.async || {}))); + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.async = global.async || {}))); }(this, (function (exports) { 'use strict'; -/** - * 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); -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ -function overRest$1(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; +function slice(arrayLike, start) { + start = start|0; + var newLen = Math.max(arrayLike.length - start, 0); + var newArr = Array(newLen); + for(var idx = 0; idx < newLen; idx++) { + newArr[idx] = arrayLike[start + idx]; } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; -} - -/** - * 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; -} - -// Lodash rest function without function.toString() -// remappings -function rest(func, start) { - return overRest$1(func, start, identity); + return newArr; } var initialParams = function (fn) { - return rest(function (args /*..., callback*/) { + return function (/*...args, callback*/) { + var args = slice(arguments); var callback = args.pop(); fn.call(this, args, callback); - }); + }; }; /** @@ -735,6 +669,34 @@ function isObject(value) { return value != null && (type == 'object' || type == 'function'); } +var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return function (fn/*, ...args*/) { + var args = slice(arguments, 1); + defer(function () { + fn.apply(null, args); + }); + }; +} + +var _defer; + +if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +var setImmediate$1 = wrap(_defer); + /** * Take a sync function and make it async, passing its return value to a * callback. This is useful for plugging sync functions into a waterfall, @@ -754,7 +716,7 @@ function isObject(value) { * @method * @alias wrapSync * @category Util - * @param {Function} func - The synchronous funuction, or Promise-returning + * @param {Function} func - The synchronous function, or Promise-returning * function to convert to an {@link AsyncFunction}. * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be * invoked with `(args..., callback)`. @@ -801,10 +763,10 @@ function asyncify(func) { } // if result is Promise object if (isObject(result) && typeof result.then === 'function') { - result.then(function (value) { - callback(null, value); - }, function (err) { - callback(err.message ? err : new Error(err)); + result.then(function(value) { + invokeCallback(callback, null, value); + }, function(err) { + invokeCallback(callback, err.message ? err : new Error(err)); }); } else { callback(null, result); @@ -812,19 +774,20 @@ function asyncify(func) { }); } -var supportsSymbol = typeof Symbol === 'function'; - -function supportsAsync() { - var supported; +function invokeCallback(callback, error, value) { try { - /* eslint no-eval: 0 */ - supported = isAsync(eval('(async function () {})')); + callback(error, value); } catch (e) { - supported = false; + setImmediate$1(rethrow, e); } - return supported; } +function rethrow(error) { + throw error; +} + +var supportsSymbol = typeof Symbol === 'function'; + function isAsync(fn) { return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; } @@ -833,22 +796,22 @@ function wrapAsync(asyncFn) { return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; } -var wrapAsync$1 = supportsAsync() ? wrapAsync : identity; - function applyEach$1(eachfn) { - return rest(function (fns, args) { - var go = initialParams(function (args, callback) { + return function(fns/*, ...args*/) { + var args = slice(arguments, 1); + var go = initialParams(function(args, callback) { var that = this; return eachfn(fns, function (fn, cb) { - wrapAsync$1(fn).apply(that, args.concat(cb)); + wrapAsync(fn).apply(that, args.concat(cb)); }, callback); }); if (args.length) { return go.apply(this, args); - } else { + } + else { return go; } - }); + }; } /** Detect free variable `global` from Node.js. */ @@ -1518,18 +1481,19 @@ function createArrayIterator(coll) { var i = -1; var len = coll.length; return function next() { - return ++i < len ? { value: coll[i], key: i } : null; - }; + return ++i < len ? {value: coll[i], key: i} : null; + } } function createES2015Iterator(iterator) { var i = -1; return function next() { var item = iterator.next(); - if (item.done) return null; + if (item.done) + return null; i++; - return { value: item.value, key: i }; - }; + return {value: item.value, key: i}; + } } function createObjectIterator(obj) { @@ -1538,7 +1502,7 @@ function createObjectIterator(obj) { var len = okeys.length; return function next() { var key = okeys[++i]; - return i < len ? { value: obj[key], key: key } : null; + return i < len ? {value: obj[key], key: key} : null; }; } @@ -1552,7 +1516,7 @@ function iterator(coll) { } function onlyOnce(fn) { - return function () { + return function() { if (fn === null) throw new Error("Callback was already called."); var callFn = fn; fn = null; @@ -1575,15 +1539,17 @@ function _eachOfLimit(limit) { if (err) { done = true; callback(err); - } else if (value === breakLoop || done && running <= 0) { + } + else if (value === breakLoop || (done && running <= 0)) { done = true; return callback(null); - } else { + } + else { replenish(); } } - function replenish() { + function replenish () { while (running < limit && !done) { var elem = nextElem(); if (elem === null) { @@ -1623,7 +1589,7 @@ function _eachOfLimit(limit) { * `iteratee` functions have finished, or an error occurs. Invoked with (err). */ function eachOfLimit(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, wrapAsync$1(iteratee), callback); + _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); } function doLimit(fn, limit) { @@ -1645,7 +1611,7 @@ function eachOfArrayLike(coll, iteratee, callback) { function iteratorCallback(err, value) { if (err) { callback(err); - } else if (++completed === length || value === breakLoop) { + } else if ((++completed === length) || value === breakLoop) { callback(null); } } @@ -1697,14 +1663,14 @@ var eachOfGeneric = doLimit(eachOfLimit, Infinity); * doSomethingWith(configs); * }); */ -var eachOf = function (coll, iteratee, callback) { +var eachOf = function(coll, iteratee, callback) { var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, wrapAsync$1(iteratee), callback); + eachOfImplementation(coll, wrapAsync(iteratee), callback); }; function doParallel(fn) { return function (obj, iteratee, callback) { - return fn(eachOf, obj, wrapAsync$1(iteratee), callback); + return fn(eachOf, obj, wrapAsync(iteratee), callback); }; } @@ -1713,7 +1679,7 @@ function _asyncMap(eachfn, arr, iteratee, callback) { arr = arr || []; var results = []; var counter = 0; - var _iteratee = wrapAsync$1(iteratee); + var _iteratee = wrapAsync(iteratee); eachfn(arr, function (value, _, callback) { var index = counter++; @@ -1801,7 +1767,7 @@ var applyEach = applyEach$1(map); function doParallelLimit(fn) { return function (obj, limit, iteratee, callback) { - return fn(_eachOfLimit(limit), obj, wrapAsync$1(iteratee), callback); + return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); }; } @@ -1879,10 +1845,11 @@ var applyEachSeries = applyEach$1(mapSeries); * @memberOf module:Utils * @method * @category Util - * @param {Function} function - The function you want to eventually apply all + * @param {Function} fn - The function you want to eventually apply all * arguments to. Invokes with (arguments...). * @param {...*} arguments... - Any number of arguments to automatically apply * when the continuation is called. + * @returns {Function} the partially-applied function * @example * * // using apply @@ -1911,11 +1878,13 @@ var applyEachSeries = applyEach$1(mapSeries); * two * three */ -var apply$2 = rest(function (fn, args) { - return rest(function (callArgs) { +var apply = function(fn/*, ...args*/) { + var args = slice(arguments, 1); + return function(/*callArgs*/) { + var callArgs = slice(arguments); return fn.apply(null, args.concat(callArgs)); - }); -}); + }; +}; /** * A specialized version of `_.forEach` for arrays without support for @@ -2185,7 +2154,10 @@ var auto = function (tasks, concurrency, callback) { arrayEach(dependencies, function (dependencyName) { if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); } addListener(dependencyName, function () { remainingDependencies--; @@ -2209,10 +2181,11 @@ var auto = function (tasks, concurrency, callback) { if (readyTasks.length === 0 && runningTasks === 0) { return callback(null, results); } - while (readyTasks.length && runningTasks < concurrency) { + while(readyTasks.length && runningTasks < concurrency) { var run = readyTasks.shift(); run(); } + } function addListener(taskName, fn) { @@ -2232,32 +2205,33 @@ var auto = function (tasks, concurrency, callback) { processQueue(); } + function runTask(key, task) { if (hasError) return; - var taskCallback = onlyOnce(rest(function (err, args) { + var taskCallback = onlyOnce(function(err, result) { runningTasks--; - if (args.length <= 1) { - args = args[0]; + if (arguments.length > 2) { + result = slice(arguments, 1); } if (err) { var safeResults = {}; - baseForOwn(results, function (val, rkey) { + baseForOwn(results, function(val, rkey) { safeResults[rkey] = val; }); - safeResults[key] = args; + safeResults[key] = result; hasError = true; listeners = Object.create(null); callback(err, safeResults); } else { - results[key] = args; + results[key] = result; taskComplete(key); } - })); + }); runningTasks++; - var taskFn = wrapAsync$1(task[task.length - 1]); + var taskFn = wrapAsync(task[task.length - 1]); if (task.length > 1) { taskFn(results, taskCallback); } else { @@ -2282,7 +2256,9 @@ var auto = function (tasks, concurrency, callback) { } if (counter !== numTasks) { - throw new Error('async.auto cannot execute tasks due to a recursive dependency'); + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); } } @@ -2610,7 +2586,7 @@ function parseParams(func) { func = func.toString().replace(STRIP_COMMENTS, ''); func = func.match(FN_ARGS)[2].replace(' ', ''); func = func ? func.split(FN_ARG_SPLIT) : []; - func = func.map(function (arg) { + func = func.map(function (arg){ return trim(arg.replace(FN_ARG, '')); }); return func; @@ -2704,7 +2680,9 @@ function autoInject(tasks, callback) { baseForOwn(tasks, function (taskFn, key) { var params; var fnIsAsync = isAsync(taskFn); - var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0; + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); if (isArray(taskFn)) { params = taskFn.slice(0, -1); @@ -2731,40 +2709,13 @@ function autoInject(tasks, callback) { return results[name]; }); newArgs.push(taskCb); - wrapAsync$1(taskFn).apply(null, newArgs); + wrapAsync(taskFn).apply(null, newArgs); } }); auto(newTasks, callback); } -var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - -function fallback(fn) { - setTimeout(fn, 0); -} - -function wrap(defer) { - return rest(function (fn, args) { - defer(function () { - fn.apply(null, args); - }); - }); -} - -var _defer; - -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} - -var setImmediate$1 = wrap(_defer); - // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation // used for queues. This implementation assumes that the node provided by the user can be modified // to adjust the next and last properties. We implement only the minimal functionality @@ -2779,57 +2730,89 @@ function setInitial(dll, node) { dll.head = dll.tail = node; } -DLL.prototype.removeLink = function (node) { - if (node.prev) node.prev.next = node.next;else this.head = node.next; - if (node.next) node.next.prev = node.prev;else this.tail = node.prev; +DLL.prototype.removeLink = function(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; node.prev = node.next = null; this.length -= 1; return node; }; -DLL.prototype.empty = DLL; +DLL.prototype.empty = function () { + while(this.head) this.shift(); + return this; +}; -DLL.prototype.insertAfter = function (node, newNode) { +DLL.prototype.insertAfter = function(node, newNode) { newNode.prev = node; newNode.next = node.next; - if (node.next) node.next.prev = newNode;else this.tail = newNode; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; node.next = newNode; this.length += 1; }; -DLL.prototype.insertBefore = function (node, newNode) { +DLL.prototype.insertBefore = function(node, newNode) { newNode.prev = node.prev; newNode.next = node; - if (node.prev) node.prev.next = newNode;else this.head = newNode; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; node.prev = newNode; this.length += 1; }; -DLL.prototype.unshift = function (node) { - if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); +DLL.prototype.unshift = function(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); }; -DLL.prototype.push = function (node) { - if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); +DLL.prototype.push = function(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); }; -DLL.prototype.shift = function () { +DLL.prototype.shift = function() { return this.head && this.removeLink(this.head); }; -DLL.prototype.pop = function () { +DLL.prototype.pop = function() { return this.tail && this.removeLink(this.tail); }; +DLL.prototype.toArray = function () { + var arr = Array(this.length); + var curr = this.head; + for(var idx = 0; idx < this.length; idx++) { + arr[idx] = curr.data; + curr = curr.next; + } + return arr; +}; + +DLL.prototype.remove = function (testFn) { + var curr = this.head; + while(!!curr) { + var next = curr.next; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; +}; + function queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; - } else if (concurrency === 0) { + } + else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } - var _worker = wrapAsync$1(worker); + var _worker = wrapAsync(worker); var numRunning = 0; var workersList = []; @@ -2843,7 +2826,7 @@ function queue(worker, concurrency, payload) { } if (data.length === 0 && q.idle()) { // call drain immediately if there are no tasks - return setImmediate$1(function () { + return setImmediate$1(function() { q.drain(); }); } @@ -2864,7 +2847,7 @@ function queue(worker, concurrency, payload) { } function _next(tasks) { - return rest(function (args) { + return function(err){ numRunning -= 1; for (var i = 0, l = tasks.length; i < l; i++) { @@ -2874,14 +2857,14 @@ function queue(worker, concurrency, payload) { workersList.splice(index); } - task.callback.apply(task, args); + task.callback.apply(task, arguments); - if (args[0] != null) { - q.error(args[0], task.data); + if (err != null) { + q.error(err, task.data); } } - if (numRunning <= q.concurrency - q.buffer) { + if (numRunning <= (q.concurrency - q.buffer) ) { q.unsaturated(); } @@ -2889,7 +2872,7 @@ function queue(worker, concurrency, payload) { q.drain(); } q.process(); - }); + }; } var isProcessing = false; @@ -2898,7 +2881,7 @@ function queue(worker, concurrency, payload) { concurrency: concurrency, payload: payload, saturated: noop, - unsaturated: noop, + unsaturated:noop, buffer: concurrency / 4, empty: noop, drain: noop, @@ -2915,6 +2898,9 @@ function queue(worker, concurrency, payload) { unshift: function (data, callback) { _insert(data, true, callback); }, + remove: function (testFn) { + q._tasks.remove(testFn); + }, process: function () { // Avoid trying to start too many processing operations. This can occur // when callbacks resolve synchronously (#1267). @@ -2922,9 +2908,8 @@ function queue(worker, concurrency, payload) { return; } isProcessing = true; - while (!q.paused && numRunning < q.concurrency && q._tasks.length) { - var tasks = [], - data = []; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; var l = q._tasks.length; if (q.payload) l = Math.min(l, q.payload); for (var i = 0; i < l; i++) { @@ -2933,11 +2918,12 @@ function queue(worker, concurrency, payload) { data.push(node.data); } + numRunning += 1; + workersList.push(tasks[0]); + if (q._tasks.length === 0) { q.empty(); } - numRunning += 1; - workersList.push(tasks[0]); if (numRunning === q.concurrency) { q.saturated(); @@ -2957,16 +2943,14 @@ function queue(worker, concurrency, payload) { workersList: function () { return workersList; }, - idle: function () { + idle: function() { return q._tasks.length + numRunning === 0; }, pause: function () { q.paused = true; }, resume: function () { - if (q.paused === false) { - return; - } + if (q.paused === false) { return; } q.paused = false; setImmediate$1(q.process); } @@ -3052,7 +3036,7 @@ function queue(worker, concurrency, payload) { * }); */ function cargo(worker, payload) { - return queue(worker, 1, payload); + return queue(worker, 1, payload); } /** @@ -3116,13 +3100,13 @@ var eachOfSeries = doLimit(eachOfLimit, 1); */ function reduce(coll, memo, iteratee, callback) { callback = once(callback || noop); - var _iteratee = wrapAsync$1(iteratee); - eachOfSeries(coll, function (x, i, callback) { - _iteratee(memo, x, function (err, v) { + var _iteratee = wrapAsync(iteratee); + eachOfSeries(coll, function(x, i, callback) { + _iteratee(memo, x, function(err, v) { memo = v; callback(err); }); - }, function (err) { + }, function(err) { callback(err, memo); }); } @@ -3165,9 +3149,10 @@ function reduce(coll, memo, iteratee, callback) { * }); * }); */ -var seq$1 = rest(function seq(functions) { - var _functions = arrayMap(functions, wrapAsync$1); - return rest(function (args) { +function seq(/*...functions*/) { + var _functions = arrayMap(arguments, wrapAsync); + return function(/*...args*/) { + var args = slice(arguments); var that = this; var cb = args[args.length - 1]; @@ -3177,15 +3162,17 @@ var seq$1 = rest(function seq(functions) { cb = noop; } - reduce(_functions, args, function (newargs, fn, cb) { - fn.apply(that, newargs.concat(rest(function (err, nextargs) { + reduce(_functions, args, function(newargs, fn, cb) { + fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) { + var nextargs = slice(arguments, 1); cb(err, nextargs); - }))); - }, function (err, results) { + })); + }, + function(err, results) { cb.apply(that, [err].concat(results)); }); - }); -}); + }; +} /** * Creates a function which is a composition of the passed asynchronous @@ -3222,9 +3209,9 @@ var seq$1 = rest(function seq(functions) { * // result now equals 15 * }); */ -var compose = rest(function (args) { - return seq$1.apply(null, args.reverse()); -}); +var compose = function(/*...args*/) { + return seq.apply(null, slice(arguments).reverse()); +}; function concat$1(eachfn, arr, fn, callback) { var result = []; @@ -3267,7 +3254,7 @@ var concat = doParallel(concat$1); function doSeries(fn) { return function (obj, iteratee, callback) { - return fn(eachOfSeries, obj, wrapAsync$1(iteratee), callback); + return fn(eachOfSeries, obj, wrapAsync(iteratee), callback); }; } @@ -3333,20 +3320,42 @@ var concatSeries = doSeries(concat$1); * //... * }, callback); */ -var constant = rest(function (values) { +var constant = function(/*...values*/) { + var values = slice(arguments); var args = [null].concat(values); - return initialParams(function (ignoredArgs, callback) { + return function (/*...ignoredArgs, callback*/) { + var callback = arguments[arguments.length - 1]; return callback.apply(this, args); - }); -}); + }; +}; + +/** + * 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; +} function _createTester(check, getResult) { - return function (eachfn, arr, iteratee, cb) { + return function(eachfn, arr, iteratee, cb) { cb = cb || noop; var testPassed = false; var testResult; - eachfn(arr, function (value, _, callback) { - iteratee(value, function (err, result) { + eachfn(arr, function(value, _, callback) { + iteratee(value, function(err, result) { if (err) { callback(err); } else if (check(result) && !testResult) { @@ -3357,7 +3366,7 @@ function _createTester(check, getResult) { callback(); } }); - }, function (err) { + }, function(err) { if (err) { cb(err); } else { @@ -3455,8 +3464,10 @@ var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); var detectSeries = doLimit(detectLimit, 1); function consoleFunc(name) { - return rest(function (fn, args) { - wrapAsync$1(fn).apply(null, args.concat(rest(function (err, args) { + return function (fn/*, ...args*/) { + var args = slice(arguments, 1); + args.push(function (err/*, ...args*/) { + var args = slice(arguments, 1); if (typeof console === 'object') { if (err) { if (console.error) { @@ -3468,8 +3479,9 @@ function consoleFunc(name) { }); } } - }))); - }); + }); + wrapAsync(fn).apply(null, args); + }; } /** @@ -3525,14 +3537,15 @@ var dir = consoleFunc('dir'); */ function doDuring(fn, test, callback) { callback = onlyOnce(callback || noop); - var _fn = wrapAsync$1(fn); - var _test = wrapAsync$1(test); + var _fn = wrapAsync(fn); + var _test = wrapAsync(test); - var next = rest(function (err, args) { + function next(err/*, ...args*/) { if (err) return callback(err); + var args = slice(arguments, 1); args.push(check); _test.apply(this, args); - }); + } function check(err, truth) { if (err) return callback(err); @@ -3541,6 +3554,7 @@ function doDuring(fn, test, callback) { } check(null, true); + } /** @@ -3567,12 +3581,13 @@ function doDuring(fn, test, callback) { */ function doWhilst(iteratee, test, callback) { callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync$1(iteratee); - var next = rest(function (err, args) { + var _iteratee = wrapAsync(iteratee); + var next = function(err/*, ...args*/) { if (err) return callback(err); + var args = slice(arguments, 1); if (test.apply(this, args)) return _iteratee(next); callback.apply(null, [null].concat(args)); - }); + }; _iteratee(next); } @@ -3597,7 +3612,7 @@ function doWhilst(iteratee, test, callback) { * callback. Invoked with (err, [results]); */ function doUntil(iteratee, test, callback) { - doWhilst(iteratee, function () { + doWhilst(iteratee, function() { return !test.apply(this, arguments); }, callback); } @@ -3640,8 +3655,8 @@ function doUntil(iteratee, test, callback) { */ function during(test, fn, callback) { callback = onlyOnce(callback || noop); - var _fn = wrapAsync$1(fn); - var _test = wrapAsync$1(test); + var _fn = wrapAsync(fn); + var _test = wrapAsync(test); function next(err) { if (err) return callback(err); @@ -3721,7 +3736,7 @@ function _withoutIndex(iteratee) { * }); */ function eachLimit(coll, iteratee, callback) { - eachOf(coll, _withoutIndex(wrapAsync$1(iteratee)), callback); + eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); } /** @@ -3745,7 +3760,7 @@ function eachLimit(coll, iteratee, callback) { * `iteratee` functions have finished, or an error occurs. Invoked with (err). */ function eachLimit$1(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync$1(iteratee)), callback); + _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); } /** @@ -3938,7 +3953,7 @@ function filterGeneric(eachfn, coll, iteratee, callback) { callback(err); } else { if (v) { - results.push({ index: index, value: x }); + results.push({index: index, value: x}); } callback(); } @@ -3956,7 +3971,7 @@ function filterGeneric(eachfn, coll, iteratee, callback) { function _filter(eachfn, coll, iteratee, callback) { var filter = isArrayLike(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, wrapAsync$1(iteratee), callback || noop); + filter(eachfn, coll, wrapAsync(iteratee), callback || noop); } /** @@ -4059,7 +4074,7 @@ var filterSeries = doLimit(filterLimit, 1); */ function forever(fn, errback) { var done = onlyOnce(errback || noop); - var task = wrapAsync$1(ensureAsync(fn)); + var task = wrapAsync(ensureAsync(fn)); function next(err) { if (err) return done(err); @@ -4087,15 +4102,15 @@ function forever(fn, errback) { * functions have finished, or an error occurs. Result is an `Object` whoses * properties are arrays of values which returned the corresponding key. */ -var groupByLimit = function (coll, limit, iteratee, callback) { +var groupByLimit = function(coll, limit, iteratee, callback) { callback = callback || noop; - var _iteratee = wrapAsync$1(iteratee); - mapLimit(coll, limit, function (val, callback) { - _iteratee(val, function (err, key) { + var _iteratee = wrapAsync(iteratee); + mapLimit(coll, limit, function(val, callback) { + _iteratee(val, function(err, key) { if (err) return callback(err); - return callback(null, { key: key, val: val }); + return callback(null, {key: key, val: val}); }); - }, function (err, mapResults) { + }, function(err, mapResults) { var result = {}; // from MDN, handle object having an `hasOwnProperty` prop var hasOwnProperty = Object.prototype.hasOwnProperty; @@ -4229,8 +4244,8 @@ var log = consoleFunc('log'); function mapValuesLimit(obj, limit, iteratee, callback) { callback = once(callback || noop); var newObj = {}; - var _iteratee = wrapAsync$1(iteratee); - eachOfLimit(obj, limit, function (val, key, next) { + var _iteratee = wrapAsync(iteratee); + eachOfLimit(obj, limit, function(val, key, next) { _iteratee(val, key, function (err, result) { if (err) return next(err); newObj[key] = result; @@ -4354,25 +4369,26 @@ function memoize(fn, hasher) { var memo = Object.create(null); var queues = Object.create(null); hasher = hasher || identity; - var _fn = wrapAsync$1(fn); + var _fn = wrapAsync(fn); var memoized = initialParams(function memoized(args, callback) { var key = hasher.apply(null, args); if (has(memo, key)) { - setImmediate$1(function () { + setImmediate$1(function() { callback.apply(null, memo[key]); }); } else if (has(queues, key)) { queues[key].push(callback); } else { queues[key] = [callback]; - _fn.apply(null, args.concat(rest(function (args) { + _fn.apply(null, args.concat(function(/*args*/) { + var args = slice(arguments); memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } - }))); + })); } }); memoized.memo = memo; @@ -4428,13 +4444,13 @@ function _parallel(eachfn, tasks, callback) { var results = isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { - wrapAsync$1(task)(rest(function (err, args) { - if (args.length <= 1) { - args = args[0]; + wrapAsync(task)(function (err, result) { + if (arguments.length > 2) { + result = slice(arguments, 1); } - results[key] = args; + results[key] = result; callback(err); - })); + }); }, function (err) { callback(err, results); }); @@ -4510,7 +4526,7 @@ function _parallel(eachfn, tasks, callback) { * }); */ function parallelLimit(tasks, callback) { - _parallel(eachOf, tasks, callback); + _parallel(eachOf, tasks, callback); } /** @@ -4533,7 +4549,7 @@ function parallelLimit(tasks, callback) { * Invoked with (err, results). */ function parallelLimit$1(tasks, limit, callback) { - _parallel(_eachOfLimit(limit), tasks, callback); + _parallel(_eachOfLimit(limit), tasks, callback); } /** @@ -4559,6 +4575,12 @@ function parallelLimit$1(tasks, limit, callback) { * task in the list. Invoke with `queue.push(task, [callback])`, * @property {Function} unshift - add a new task to the front of the `queue`. * Invoke with `queue.unshift(task, [callback])`. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. * @property {Function} saturated - a callback that is called when the number of * running workers hits the `concurrency` limit, and further tasks will be * queued. @@ -4635,10 +4657,10 @@ function parallelLimit$1(tasks, limit, callback) { * }); */ var queue$1 = function (worker, concurrency) { - var _worker = wrapAsync$1(worker); - return queue(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); + var _worker = wrapAsync(worker); + return queue(function (items, cb) { + _worker(items[0], cb); + }, concurrency, 1); }; /** @@ -4664,12 +4686,12 @@ var queue$1 = function (worker, concurrency) { * array of `tasks` is given, all tasks will be assigned the same priority. * * The `unshift` method was removed. */ -var priorityQueue = function (worker, concurrency) { +var priorityQueue = function(worker, concurrency) { // Start with a normal queue var q = queue$1(worker, concurrency); // Override push to accept second parameter representing priority - q.push = function (data, priority, callback) { + q.push = function(data, priority, callback) { if (callback == null) callback = noop; if (typeof callback !== 'function') { throw new Error('task callback must be a function'); @@ -4680,7 +4702,7 @@ var priorityQueue = function (worker, concurrency) { } if (data.length === 0) { // call drain immediately if there are no tasks - return setImmediate$1(function () { + return setImmediate$1(function() { q.drain(); }); } @@ -4754,12 +4776,10 @@ function race(tasks, callback) { if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); if (!tasks.length) return callback(); for (var i = 0, l = tasks.length; i < l; i++) { - wrapAsync$1(tasks[i])(callback); + wrapAsync(tasks[i])(callback); } } -var slice = Array.prototype.slice; - /** * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. * @@ -4782,9 +4802,9 @@ var slice = Array.prototype.slice; * `iteratee` functions have finished. Result is the reduced value. Invoked with * (err, result). */ -function reduceRight(array, memo, iteratee, callback) { - var reversed = slice.call(array).reverse(); - reduce(reversed, memo, iteratee, callback); +function reduceRight (array, memo, iteratee, callback) { + var reversed = slice(array).reverse(); + reduce(reversed, memo, iteratee, callback); } /** @@ -4827,33 +4847,29 @@ function reduceRight(array, memo, iteratee, callback) { * }); */ function reflect(fn) { - var _fn = wrapAsync$1(fn); + var _fn = wrapAsync(fn); return initialParams(function reflectOn(args, reflectCallback) { - args.push(rest(function callback(err, cbArgs) { - if (err) { - reflectCallback(null, { - error: err - }); + args.push(function callback(error, cbArg) { + if (error) { + reflectCallback(null, { error: error }); } else { - var value = null; - if (cbArgs.length === 1) { - value = cbArgs[0]; - } else if (cbArgs.length > 1) { - value = cbArgs; + var value; + if (arguments.length <= 2) { + value = cbArg; + } else { + value = slice(arguments, 1); } - reflectCallback(null, { - value: value - }); + reflectCallback(null, { value: value }); } - })); + }); return _fn.apply(this, args); }); } function reject$1(eachfn, arr, iteratee, callback) { - _filter(eachfn, arr, function (value, cb) { - iteratee(value, function (err, v) { + _filter(eachfn, arr, function(value, cb) { + iteratee(value, function(err, v) { cb(err, !v); }); }, callback); @@ -4961,7 +4977,7 @@ function reflectAll(tasks) { results = arrayMap(tasks, reflect); } else { results = {}; - baseForOwn(tasks, function (task, key) { + baseForOwn(tasks, function(task, key) { results[key] = reflect.call(this, task); }); } @@ -5130,7 +5146,9 @@ function retry(opts, task, callback) { if (typeof t === 'object') { acc.times = +t.times || DEFAULT_TIMES; - acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant$1(+t.interval || DEFAULT_INTERVAL); + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant$1(+t.interval || DEFAULT_INTERVAL); acc.errorFilter = t.errorFilter; } else if (typeof t === 'number' || typeof t === 'string') { @@ -5152,12 +5170,14 @@ function retry(opts, task, callback) { throw new Error("Invalid arguments for async.retry"); } - var _task = wrapAsync$1(task); + var _task = wrapAsync(task); var attempt = 1; function retryAttempt() { - _task(function (err) { - if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { + _task(function(err) { + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { setTimeout(retryAttempt, options.intervalFunc(attempt)); } else { callback.apply(null, arguments); @@ -5201,13 +5221,15 @@ var retryable = function (opts, task) { task = opts; opts = null; } - var _task = wrapAsync$1(task); + var _task = wrapAsync(task); return initialParams(function (args, callback) { function taskFn(cb) { _task.apply(null, args.concat(cb)); } - if (opts) retry(opts, taskFn, callback);else retry(taskFn, callback); + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + }); }; @@ -5276,7 +5298,7 @@ var retryable = function (opts, task) { * }); */ function series(tasks, callback) { - _parallel(eachOfSeries, tasks, callback); + _parallel(eachOfSeries, tasks, callback); } /** @@ -5403,12 +5425,12 @@ var someSeries = doLimit(someLimit, 1); * // result callback * }); */ -function sortBy(coll, iteratee, callback) { - var _iteratee = wrapAsync$1(iteratee); +function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); map(coll, function (x, callback) { _iteratee(x, function (err, criteria) { if (err) return callback(err); - callback(null, { value: x, criteria: criteria }); + callback(null, {value: x, criteria: criteria}); }); }, function (err, results) { if (err) return callback(err); @@ -5416,8 +5438,7 @@ function sortBy(coll, iteratee, callback) { }); function comparator(left, right) { - var a = left.criteria, - b = right.criteria; + var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } } @@ -5464,40 +5485,39 @@ function sortBy(coll, iteratee, callback) { * }); */ function timeout(asyncFn, milliseconds, info) { - var originalCallback, timer; - var timedOut = false; - - function injectedCallback() { - if (!timedOut) { - originalCallback.apply(null, arguments); - clearTimeout(timer); - } - } + var fn = wrapAsync(asyncFn); - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; + return initialParams(function (args, callback) { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); } - timedOut = true; - originalCallback(error); - } - var fn = wrapAsync$1(asyncFn); + args.push(function () { + if (!timedOut) { + callback.apply(null, arguments); + clearTimeout(timer); + } + }); - return initialParams(function (args, origCallback) { - originalCallback = origCallback; // setup timer and call original function timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args.concat(injectedCallback)); + fn.apply(null, args); }); } /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil; -var nativeMax$1 = Math.max; +var nativeMax = Math.max; /** * The base implementation of `_.range` and `_.rangeRight` which doesn't @@ -5512,7 +5532,7 @@ var nativeMax$1 = Math.max; */ function baseRange(start, end, step, fromRight) { var index = -1, - length = nativeMax$1(nativeCeil((end - start) / (step || 1)), 0), + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { @@ -5539,8 +5559,8 @@ function baseRange(start, end, step, fromRight) { * @param {Function} callback - see [async.map]{@link module:Collections.map}. */ function timeLimit(count, limit, iteratee, callback) { - var _iteratee = wrapAsync$1(iteratee); - mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); + var _iteratee = wrapAsync(iteratee); + mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); } /** @@ -5635,22 +5655,78 @@ var timesSeries = doLimit(timeLimit, 1); * // result is equal to {a: 2, b: 4, c: 6} * }) */ -function transform(coll, accumulator, iteratee, callback) { +function transform (coll, accumulator, iteratee, callback) { if (arguments.length <= 3) { callback = iteratee; iteratee = accumulator; accumulator = isArray(coll) ? [] : {}; } callback = once(callback || noop); - var _iteratee = wrapAsync$1(iteratee); + var _iteratee = wrapAsync(iteratee); - eachOf(coll, function (v, k, cb) { + eachOf(coll, function(v, k, cb) { _iteratee(accumulator, v, k, cb); - }, function (err) { + }, function(err) { callback(err, accumulator); }); } +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @example + * async.try([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + callback = callback || noop; + eachSeries(tasks, function(task, callback) { + wrapAsync(task)(function (err, res/*, ...args*/) { + if (arguments.length > 2) { + result = slice(arguments, 1); + } else { + result = res; + } + error = err; + callback(!err); + }); + }, function () { + callback(error, result); + }); +} + /** * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, * unmemoized form. Handy for testing. @@ -5706,13 +5782,14 @@ function unmemoize(fn) { */ function whilst(test, iteratee, callback) { callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync$1(iteratee); + var _iteratee = wrapAsync(iteratee); if (!test()) return callback(null); - var next = rest(function (err, args) { + var next = function(err/*, ...args*/) { if (err) return callback(err); if (test()) return _iteratee(next); + var args = slice(arguments, 1); callback.apply(null, [null].concat(args)); - }); + }; _iteratee(next); } @@ -5739,7 +5816,7 @@ function whilst(test, iteratee, callback) { * callback. Invoked with (err, [results]); */ function until(test, iteratee, callback) { - whilst(function () { + whilst(function() { return !test.apply(this, arguments); }, iteratee, callback); } @@ -5801,30 +5878,25 @@ function until(test, iteratee, callback) { * callback(null, 'done'); * } */ -var waterfall = function (tasks, callback) { +var waterfall = function(tasks, callback) { callback = once(callback || noop); if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); if (!tasks.length) return callback(); var taskIndex = 0; function nextTask(args) { - if (taskIndex === tasks.length) { - return callback.apply(null, [null].concat(args)); - } - - var taskCallback = onlyOnce(rest(function (err, args) { - if (err) { - return callback.apply(null, [err].concat(args)); - } - nextTask(args); - })); - - args.push(taskCallback); - - var task = wrapAsync$1(tasks[taskIndex++]); + var task = wrapAsync(tasks[taskIndex++]); + args.push(onlyOnce(next)); task.apply(null, args); } + function next(err/*, ...args*/) { + if (err || taskIndex === tasks.length) { + return callback.apply(null, arguments); + } + nextTask(slice(arguments, 1)); + } + nextTask([]); }; @@ -5876,6 +5948,7 @@ var waterfall = function (tasks, callback) { * @see AsyncFunction */ + /** * A collection of `async` functions for manipulating collections, such as * arrays and objects. @@ -5893,104 +5966,105 @@ var waterfall = function (tasks, callback) { */ var index = { - applyEach: applyEach, - applyEachSeries: applyEachSeries, - apply: apply$2, - asyncify: asyncify, - auto: auto, - autoInject: autoInject, - cargo: cargo, - compose: compose, - concat: concat, - concatSeries: concatSeries, - constant: constant, - detect: detect, - detectLimit: detectLimit, - detectSeries: detectSeries, - dir: dir, - doDuring: doDuring, - doUntil: doUntil, - doWhilst: doWhilst, - during: during, - each: eachLimit, - eachLimit: eachLimit$1, - eachOf: eachOf, - eachOfLimit: eachOfLimit, - eachOfSeries: eachOfSeries, - eachSeries: eachSeries, - ensureAsync: ensureAsync, - every: every, - everyLimit: everyLimit, - everySeries: everySeries, - filter: filter, - filterLimit: filterLimit, - filterSeries: filterSeries, - forever: forever, - groupBy: groupBy, - groupByLimit: groupByLimit, - groupBySeries: groupBySeries, - log: log, - map: map, - mapLimit: mapLimit, - mapSeries: mapSeries, - mapValues: mapValues, - mapValuesLimit: mapValuesLimit, - mapValuesSeries: mapValuesSeries, - memoize: memoize, - nextTick: nextTick, - parallel: parallelLimit, - parallelLimit: parallelLimit$1, - priorityQueue: priorityQueue, - queue: queue$1, - race: race, - reduce: reduce, - reduceRight: reduceRight, - reflect: reflect, - reflectAll: reflectAll, - reject: reject, - rejectLimit: rejectLimit, - rejectSeries: rejectSeries, - retry: retry, - retryable: retryable, - seq: seq$1, - series: series, - setImmediate: setImmediate$1, - some: some, - someLimit: someLimit, - someSeries: someSeries, - sortBy: sortBy, - timeout: timeout, - times: times, - timesLimit: timeLimit, - timesSeries: timesSeries, - transform: transform, - unmemoize: unmemoize, - until: until, - waterfall: waterfall, - whilst: whilst, - - // aliases - all: every, - any: some, - forEach: eachLimit, - forEachSeries: eachSeries, - forEachLimit: eachLimit$1, - forEachOf: eachOf, - forEachOfSeries: eachOfSeries, - forEachOfLimit: eachOfLimit, - inject: reduce, - foldl: reduce, - foldr: reduceRight, - select: filter, - selectLimit: filterLimit, - selectSeries: filterSeries, - wrapSync: asyncify + applyEach: applyEach, + applyEachSeries: applyEachSeries, + apply: apply, + asyncify: asyncify, + auto: auto, + autoInject: autoInject, + cargo: cargo, + compose: compose, + concat: concat, + concatSeries: concatSeries, + constant: constant, + detect: detect, + detectLimit: detectLimit, + detectSeries: detectSeries, + dir: dir, + doDuring: doDuring, + doUntil: doUntil, + doWhilst: doWhilst, + during: during, + each: eachLimit, + eachLimit: eachLimit$1, + eachOf: eachOf, + eachOfLimit: eachOfLimit, + eachOfSeries: eachOfSeries, + eachSeries: eachSeries, + ensureAsync: ensureAsync, + every: every, + everyLimit: everyLimit, + everySeries: everySeries, + filter: filter, + filterLimit: filterLimit, + filterSeries: filterSeries, + forever: forever, + groupBy: groupBy, + groupByLimit: groupByLimit, + groupBySeries: groupBySeries, + log: log, + map: map, + mapLimit: mapLimit, + mapSeries: mapSeries, + mapValues: mapValues, + mapValuesLimit: mapValuesLimit, + mapValuesSeries: mapValuesSeries, + memoize: memoize, + nextTick: nextTick, + parallel: parallelLimit, + parallelLimit: parallelLimit$1, + priorityQueue: priorityQueue, + queue: queue$1, + race: race, + reduce: reduce, + reduceRight: reduceRight, + reflect: reflect, + reflectAll: reflectAll, + reject: reject, + rejectLimit: rejectLimit, + rejectSeries: rejectSeries, + retry: retry, + retryable: retryable, + seq: seq, + series: series, + setImmediate: setImmediate$1, + some: some, + someLimit: someLimit, + someSeries: someSeries, + sortBy: sortBy, + timeout: timeout, + times: times, + timesLimit: timeLimit, + timesSeries: timesSeries, + transform: transform, + tryEach: tryEach, + unmemoize: unmemoize, + until: until, + waterfall: waterfall, + whilst: whilst, + + // aliases + all: every, + any: some, + forEach: eachLimit, + forEachSeries: eachSeries, + forEachLimit: eachLimit$1, + forEachOf: eachOf, + forEachOfSeries: eachOfSeries, + forEachOfLimit: eachOfLimit, + inject: reduce, + foldl: reduce, + foldr: reduceRight, + select: filter, + selectLimit: filterLimit, + selectSeries: filterSeries, + wrapSync: asyncify }; exports['default'] = index; exports.applyEach = applyEach; exports.applyEachSeries = applyEachSeries; -exports.apply = apply$2; +exports.apply = apply; exports.asyncify = asyncify; exports.auto = auto; exports.autoInject = autoInject; @@ -6047,7 +6121,7 @@ exports.rejectLimit = rejectLimit; exports.rejectSeries = rejectSeries; exports.retry = retry; exports.retryable = retryable; -exports.seq = seq$1; +exports.seq = seq; exports.series = series; exports.setImmediate = setImmediate$1; exports.some = some; @@ -6059,6 +6133,7 @@ exports.times = times; exports.timesLimit = timeLimit; exports.timesSeries = timesSeries; exports.transform = transform; +exports.tryEach = tryEach; exports.unmemoize = unmemoize; exports.until = until; exports.waterfall = waterfall; @@ -6091,7 +6166,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":85}],5:[function(require,module,exports){ +},{"_process":84}],5:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -6127,22 +6202,22 @@ function placeHoldersCount (b64) { function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data - return b64.length * 3 / 4 - placeHoldersCount(b64) + return (b64.length * 3 / 4) - placeHoldersCount(b64) } function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr + var i, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) - arr = new Arr(len * 3 / 4 - placeHolders) + arr = new Arr((len * 3 / 4) - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 - for (i = 0, j = 0; i < l; i += 4, j += 3) { + for (i = 0; i < l; i += 4) { 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 @@ -6213,118 +6288,6 @@ function fromByteArray (uint8) { arguments[4][6][0].apply(exports,arguments) },{"dup":6}],8:[function(require,module,exports){ (function (global){ -'use strict'; - -var buffer = require('buffer'); -var Buffer = buffer.Buffer; -var SlowBuffer = buffer.SlowBuffer; -var MAX_LEN = buffer.kMaxLength || 2147483647; -exports.alloc = function alloc(size, fill, encoding) { - if (typeof Buffer.alloc === 'function') { - return Buffer.alloc(size, fill, encoding); - } - if (typeof encoding === 'number') { - throw new TypeError('encoding must not be number'); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - var enc = encoding; - var _fill = fill; - if (_fill === undefined) { - enc = undefined; - _fill = 0; - } - var buf = new Buffer(size); - if (typeof _fill === 'string') { - var fillBuf = new Buffer(_fill, enc); - var flen = fillBuf.length; - var i = -1; - while (++i < size) { - buf[i] = fillBuf[i % flen]; - } - } else { - buf.fill(_fill); - } - return buf; -} -exports.allocUnsafe = function allocUnsafe(size) { - if (typeof Buffer.allocUnsafe === 'function') { - return Buffer.allocUnsafe(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - return new Buffer(size); -} -exports.from = function from(value, encodingOrOffset, length) { - if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { - return Buffer.from(value, encodingOrOffset, length); - } - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number'); - } - if (typeof value === 'string') { - return new Buffer(value, encodingOrOffset); - } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - var offset = encodingOrOffset; - if (arguments.length === 1) { - return new Buffer(value); - } - if (typeof offset === 'undefined') { - offset = 0; - } - var len = length; - if (typeof len === 'undefined') { - len = value.byteLength - offset; - } - if (offset >= value.byteLength) { - throw new RangeError('\'offset\' is out of bounds'); - } - if (len > value.byteLength - offset) { - throw new RangeError('\'length\' is out of bounds'); - } - return new Buffer(value.slice(offset, offset + len)); - } - if (Buffer.isBuffer(value)) { - var out = new Buffer(value.length); - value.copy(out, 0, 0, value.length); - return out; - } - if (value) { - if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { - return new Buffer(value); - } - if (value.type === 'Buffer' && Array.isArray(value.data)) { - return new Buffer(value.data); - } - } - - throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); -} -exports.allocUnsafeSlow = function allocUnsafeSlow(size) { - if (typeof Buffer.allocUnsafeSlow === 'function') { - return Buffer.allocUnsafeSlow(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size >= MAX_LEN) { - throw new RangeError('size is too large'); - } - return new SlowBuffer(size); -} - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"buffer":9}],9:[function(require,module,exports){ -(function (global){ /*! * The buffer module from node.js, for the browser. * @@ -8116,7 +8079,7 @@ function isnan (val) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":5,"ieee754":40,"isarray":44}],10:[function(require,module,exports){ +},{"base64-js":5,"ieee754":39,"isarray":43}],9:[function(require,module,exports){ (function (Buffer,process){ /** * Copyright (c) 2017 Trent Mick. @@ -9747,7 +9710,7 @@ module.exports.RotatingFileStream = RotatingFileStream; module.exports.safeCycles = safeCycles; }).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process')) -},{"../../is-buffer/index.js":43,"_process":85,"assert":3,"events":38,"fs":7,"os":83,"safe-json-stringify":100,"stream":122,"util":131}],11:[function(require,module,exports){ +},{"../../is-buffer/index.js":42,"_process":84,"assert":3,"events":37,"fs":7,"os":82,"safe-json-stringify":102,"stream":125,"util":134}],10:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // @@ -9858,7 +9821,7 @@ function objectToString(o) { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":43}],12:[function(require,module,exports){ +},{"../../is-buffer/index.js":42}],11:[function(require,module,exports){ var util = require('util') , AbstractIterator = require('abstract-leveldown').AbstractIterator @@ -9894,7 +9857,7 @@ DeferredIterator.prototype._operation = function (method, args) { module.exports = DeferredIterator; -},{"abstract-leveldown":17,"util":131}],13:[function(require,module,exports){ +},{"abstract-leveldown":16,"util":134}],12:[function(require,module,exports){ (function (Buffer,process){ var util = require('util') , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN @@ -9954,7 +9917,7 @@ module.exports = DeferredLevelDOWN module.exports.DeferredIterator = DeferredIterator }).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process')) -},{"../is-buffer/index.js":43,"./deferred-iterator":12,"_process":85,"abstract-leveldown":17,"util":131}],14:[function(require,module,exports){ +},{"../is-buffer/index.js":42,"./deferred-iterator":11,"_process":84,"abstract-leveldown":16,"util":134}],13:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -10037,7 +10000,7 @@ AbstractChainedBatch.prototype.write = function (options, callback) { module.exports = AbstractChainedBatch }).call(this,require('_process')) -},{"_process":85}],15:[function(require,module,exports){ +},{"_process":84}],14:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -10090,7 +10053,7 @@ AbstractIterator.prototype.end = function (callback) { module.exports = AbstractIterator }).call(this,require('_process')) -},{"_process":85}],16:[function(require,module,exports){ +},{"_process":84}],15:[function(require,module,exports){ (function (Buffer,process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -10366,13 +10329,13 @@ AbstractLevelDOWN.prototype._checkKey = function (obj, type) { module.exports = AbstractLevelDOWN }).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) -},{"../../../is-buffer/index.js":43,"./abstract-chained-batch":14,"./abstract-iterator":15,"_process":85,"xtend":133}],17:[function(require,module,exports){ +},{"../../../is-buffer/index.js":42,"./abstract-chained-batch":13,"./abstract-iterator":14,"_process":84,"xtend":136}],16:[function(require,module,exports){ exports.AbstractLevelDOWN = require('./abstract-leveldown') exports.AbstractIterator = require('./abstract-iterator') exports.AbstractChainedBatch = require('./abstract-chained-batch') exports.isLevelDOWN = require('./is-leveldown') -},{"./abstract-chained-batch":14,"./abstract-iterator":15,"./abstract-leveldown":16,"./is-leveldown":18}],18:[function(require,module,exports){ +},{"./abstract-chained-batch":13,"./abstract-iterator":14,"./abstract-leveldown":15,"./is-leveldown":17}],17:[function(require,module,exports){ var AbstractLevelDOWN = require('./abstract-leveldown') function isLevelDOWN (db) { @@ -10388,7 +10351,7 @@ function isLevelDOWN (db) { module.exports = isLevelDOWN -},{"./abstract-leveldown":16}],19:[function(require,module,exports){ +},{"./abstract-leveldown":15}],18:[function(require,module,exports){ const pumpify = require('pumpify') const stopwords = [] @@ -10454,7 +10417,7 @@ exports.customPipeline = function (pl) { return pumpify.obj.apply(this, pl) } -},{"./pipeline/CalculateTermFrequency.js":20,"./pipeline/CreateCompositeVector.js":21,"./pipeline/CreateSortVectors.js":22,"./pipeline/CreateStoredDocument.js":23,"./pipeline/FieldedSearch.js":24,"./pipeline/IngestDoc.js":25,"./pipeline/LowCase.js":26,"./pipeline/NormaliseFields.js":27,"./pipeline/RemoveStopWords.js":28,"./pipeline/Spy.js":29,"./pipeline/Tokeniser.js":30,"pumpify":88}],20:[function(require,module,exports){ +},{"./pipeline/CalculateTermFrequency.js":19,"./pipeline/CreateCompositeVector.js":20,"./pipeline/CreateSortVectors.js":21,"./pipeline/CreateStoredDocument.js":22,"./pipeline/FieldedSearch.js":23,"./pipeline/IngestDoc.js":24,"./pipeline/LowCase.js":25,"./pipeline/NormaliseFields.js":26,"./pipeline/RemoveStopWords.js":27,"./pipeline/Spy.js":28,"./pipeline/Tokeniser.js":29,"pumpify":87}],19:[function(require,module,exports){ const tv = require('term-vector') const tf = require('term-frequency') const Transform = require('stream').Transform @@ -10499,7 +10462,7 @@ CalculateTermFrequency.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"term-frequency":125,"term-vector":126,"util":131}],21:[function(require,module,exports){ +},{"stream":125,"term-frequency":128,"term-vector":129,"util":134}],20:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -10530,7 +10493,7 @@ CreateCompositeVector.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"util":131}],22:[function(require,module,exports){ +},{"stream":125,"util":134}],21:[function(require,module,exports){ const tf = require('term-frequency') const tv = require('term-vector') const Transform = require('stream').Transform @@ -10567,7 +10530,7 @@ CreateSortVectors.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"term-frequency":125,"term-vector":126,"util":131}],23:[function(require,module,exports){ +},{"stream":125,"term-frequency":128,"term-vector":129,"util":134}],22:[function(require,module,exports){ // Creates the document that will be returned in the search // results. There may be cases where the document that is searchable // is not the same as the document that is returned @@ -10598,7 +10561,7 @@ CreateStoredDocument.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"util":131}],24:[function(require,module,exports){ +},{"stream":125,"util":134}],23:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -10623,7 +10586,7 @@ FieldedSearch.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"util":131}],25:[function(require,module,exports){ +},{"stream":125,"util":134}],24:[function(require,module,exports){ const util = require('util') const Transform = require('stream').Transform @@ -10660,7 +10623,7 @@ IngestDoc.prototype._transform = function (doc, encoding, end) { } -},{"stream":122,"util":131}],26:[function(require,module,exports){ +},{"stream":125,"util":134}],25:[function(require,module,exports){ // insert all search tokens in lower case const Transform = require('stream').Transform const util = require('util') @@ -10694,7 +10657,7 @@ LowCase.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"util":131}],27:[function(require,module,exports){ +},{"stream":125,"util":134}],26:[function(require,module,exports){ const util = require('util') const Transform = require('stream').Transform @@ -10722,7 +10685,7 @@ NormaliseFields.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"util":131}],28:[function(require,module,exports){ +},{"stream":125,"util":134}],27:[function(require,module,exports){ // removes stopwords from indexed docs const Transform = require('stream').Transform const util = require('util') @@ -10753,7 +10716,7 @@ RemoveStopWords.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"util":131}],29:[function(require,module,exports){ +},{"stream":125,"util":134}],28:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -10768,7 +10731,7 @@ Spy.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"util":131}],30:[function(require,module,exports){ +},{"stream":125,"util":134}],29:[function(require,module,exports){ // split up fields in to arrays of tokens const Transform = require('stream').Transform const util = require('util') @@ -10800,7 +10763,7 @@ Tokeniser.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":122,"util":131}],31:[function(require,module,exports){ +},{"stream":125,"util":134}],30:[function(require,module,exports){ (function (process,Buffer){ var stream = require('readable-stream') var eos = require('end-of-stream') @@ -11032,7 +10995,7 @@ Duplexify.prototype.end = function(data, enc, cb) { module.exports = Duplexify }).call(this,require('_process'),require("buffer").Buffer) -},{"_process":85,"buffer":9,"end-of-stream":32,"inherits":41,"readable-stream":97,"stream-shift":123}],32:[function(require,module,exports){ +},{"_process":84,"buffer":8,"end-of-stream":31,"inherits":40,"readable-stream":98,"stream-shift":126}],31:[function(require,module,exports){ var once = require('once'); var noop = function() {}; @@ -11105,7 +11068,7 @@ var eos = function(stream, opts, callback) { }; module.exports = eos; -},{"once":33}],33:[function(require,module,exports){ +},{"once":32}],32:[function(require,module,exports){ var wrappy = require('wrappy') module.exports = wrappy(once) @@ -11128,7 +11091,7 @@ function once (fn) { return f } -},{"wrappy":132}],34:[function(require,module,exports){ +},{"wrappy":135}],33:[function(require,module,exports){ var once = require('once'); var noop = function() {}; @@ -11213,7 +11176,7 @@ var eos = function(stream, opts, callback) { module.exports = eos; -},{"once":82}],35:[function(require,module,exports){ +},{"once":81}],34:[function(require,module,exports){ var prr = require('prr') function init (type, message, cause) { @@ -11270,7 +11233,7 @@ module.exports = function (errno) { } } -},{"prr":37}],36:[function(require,module,exports){ +},{"prr":36}],35:[function(require,module,exports){ var all = module.exports.all = [ { errno: -2, @@ -11585,7 +11548,7 @@ all.forEach(function (error) { module.exports.custom = require('./custom')(module.exports) module.exports.create = module.exports.custom.createError -},{"./custom":35}],37:[function(require,module,exports){ +},{"./custom":34}],36:[function(require,module,exports){ /*! * prr * (c) 2013 Rod Vagg @@ -11649,7 +11612,7 @@ module.exports.create = module.exports.custom.createError return prr }) -},{}],38:[function(require,module,exports){ +},{}],37:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -11953,7 +11916,7 @@ function isUndefined(arg) { return arg === void 0; } -},{}],39:[function(require,module,exports){ +},{}],38:[function(require,module,exports){ /*global window:false, self:false, define:false, module:false */ /** @@ -13360,7 +13323,7 @@ function isUndefined(arg) { }, this); -},{}],40:[function(require,module,exports){ +},{}],39:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -13446,7 +13409,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],41:[function(require,module,exports){ +},{}],40:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -13471,7 +13434,7 @@ if (typeof Object.create === 'function') { } } -},{}],42:[function(require,module,exports){ +},{}],41:[function(require,module,exports){ // This module takes an arbitrary number of sorted arrays, and returns // the intersection as a stream. Arrays need to be sorted in order for @@ -13537,7 +13500,7 @@ exports.getIntersectionStream = function(sortedSets) { return s } -},{"stream":122}],43:[function(require,module,exports){ +},{"stream":125}],42:[function(require,module,exports){ /*! * Determine if an object is a Buffer * @@ -13560,14 +13523,14 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } -},{}],44:[function(require,module,exports){ +},{}],43:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],45:[function(require,module,exports){ +},{}],44:[function(require,module,exports){ var Buffer = require('buffer').Buffer; module.exports = isBuffer; @@ -13577,7 +13540,7 @@ function isBuffer (o) { || /\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o)); } -},{"buffer":9}],46:[function(require,module,exports){ +},{"buffer":8}],45:[function(require,module,exports){ var encodings = require('./lib/encodings'); module.exports = Codec; @@ -13685,7 +13648,7 @@ Codec.prototype.valueAsBuffer = function(opts){ }; -},{"./lib/encodings":47}],47:[function(require,module,exports){ +},{"./lib/encodings":46}],46:[function(require,module,exports){ (function (Buffer){ exports.utf8 = exports['utf-8'] = { @@ -13765,7 +13728,7 @@ function isBinary(data){ }).call(this,require("buffer").Buffer) -},{"buffer":9}],48:[function(require,module,exports){ +},{"buffer":8}],47:[function(require,module,exports){ /* Copyright (c) 2012-2015 LevelUP contributors * See list at * MIT License @@ -13789,7 +13752,7 @@ module.exports = { , EncodingError : createError('EncodingError', LevelUPError) } -},{"errno":36}],49:[function(require,module,exports){ +},{"errno":35}],48:[function(require,module,exports){ var inherits = require('inherits'); var Readable = require('readable-stream').Readable; var extend = require('xtend'); @@ -13847,12 +13810,12 @@ ReadStream.prototype._cleanup = function(){ }; -},{"inherits":41,"level-errors":48,"readable-stream":56,"xtend":133}],50:[function(require,module,exports){ +},{"inherits":40,"level-errors":47,"readable-stream":55,"xtend":136}],49:[function(require,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; -},{}],51:[function(require,module,exports){ +},{}],50:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -13945,7 +13908,7 @@ function forEach (xs, f) { } }).call(this,require('_process')) -},{"./_stream_readable":53,"./_stream_writable":55,"_process":85,"core-util-is":11,"inherits":41}],52:[function(require,module,exports){ +},{"./_stream_readable":52,"./_stream_writable":54,"_process":84,"core-util-is":10,"inherits":40}],51:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -13993,7 +13956,7 @@ PassThrough.prototype._transform = function(chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":54,"core-util-is":11,"inherits":41}],53:[function(require,module,exports){ +},{"./_stream_transform":53,"core-util-is":10,"inherits":40}],52:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -14948,7 +14911,7 @@ function indexOf (xs, x) { } }).call(this,require('_process')) -},{"./_stream_duplex":51,"_process":85,"buffer":9,"core-util-is":11,"events":38,"inherits":41,"isarray":50,"stream":122,"string_decoder/":57,"util":6}],54:[function(require,module,exports){ +},{"./_stream_duplex":50,"_process":84,"buffer":8,"core-util-is":10,"events":37,"inherits":40,"isarray":49,"stream":125,"string_decoder/":56,"util":6}],53:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -15159,7 +15122,7 @@ function done(stream, er) { return stream.push(null); } -},{"./_stream_duplex":51,"core-util-is":11,"inherits":41}],55:[function(require,module,exports){ +},{"./_stream_duplex":50,"core-util-is":10,"inherits":40}],54:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -15640,7 +15603,7 @@ function endWritable(stream, state, cb) { } }).call(this,require('_process')) -},{"./_stream_duplex":51,"_process":85,"buffer":9,"core-util-is":11,"inherits":41,"stream":122}],56:[function(require,module,exports){ +},{"./_stream_duplex":50,"_process":84,"buffer":8,"core-util-is":10,"inherits":40,"stream":125}],55:[function(require,module,exports){ (function (process){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = require('stream'); @@ -15654,7 +15617,7 @@ if (!process.browser && process.env.READABLE_STREAM === 'disable') { } }).call(this,require('_process')) -},{"./lib/_stream_duplex.js":51,"./lib/_stream_passthrough.js":52,"./lib/_stream_readable.js":53,"./lib/_stream_transform.js":54,"./lib/_stream_writable.js":55,"_process":85,"stream":122}],57:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":50,"./lib/_stream_passthrough.js":51,"./lib/_stream_readable.js":52,"./lib/_stream_transform.js":53,"./lib/_stream_writable.js":54,"_process":84,"stream":125}],56:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -15877,7 +15840,7 @@ function base64DetectIncompleteChar(buffer) { this.charLength = this.charReceived ? 3 : 0; } -},{"buffer":9}],58:[function(require,module,exports){ +},{"buffer":8}],57:[function(require,module,exports){ (function (Buffer){ module.exports = Level @@ -16055,7 +16018,7 @@ var checkKeyValue = Level.prototype._checkKeyValue = function (obj, type) { } }).call(this,require("buffer").Buffer) -},{"./iterator":59,"abstract-leveldown":62,"buffer":9,"idb-wrapper":39,"isbuffer":45,"typedarray-to-buffer":127,"util":131,"xtend":69}],59:[function(require,module,exports){ +},{"./iterator":58,"abstract-leveldown":61,"buffer":8,"idb-wrapper":38,"isbuffer":44,"typedarray-to-buffer":130,"util":134,"xtend":68}],58:[function(require,module,exports){ var util = require('util') var AbstractIterator = require('abstract-leveldown').AbstractIterator var ltgt = require('ltgt') @@ -16129,7 +16092,7 @@ Iterator.prototype._next = function (callback) { this.callback = callback } -},{"abstract-leveldown":62,"ltgt":81,"util":131}],60:[function(require,module,exports){ +},{"abstract-leveldown":61,"ltgt":79,"util":134}],59:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -16213,9 +16176,9 @@ AbstractChainedBatch.prototype.write = function (options, callback) { module.exports = AbstractChainedBatch }).call(this,require('_process')) -},{"_process":85}],61:[function(require,module,exports){ -arguments[4][15][0].apply(exports,arguments) -},{"_process":85,"dup":15}],62:[function(require,module,exports){ +},{"_process":84}],60:[function(require,module,exports){ +arguments[4][14][0].apply(exports,arguments) +},{"_process":84,"dup":14}],61:[function(require,module,exports){ (function (Buffer,process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -16475,7 +16438,7 @@ module.exports.AbstractIterator = AbstractIterator module.exports.AbstractChainedBatch = AbstractChainedBatch }).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) -},{"../../../is-buffer/index.js":43,"./abstract-chained-batch":60,"./abstract-iterator":61,"_process":85,"xtend":63}],63:[function(require,module,exports){ +},{"../../../is-buffer/index.js":42,"./abstract-chained-batch":59,"./abstract-iterator":60,"_process":84,"xtend":62}],62:[function(require,module,exports){ module.exports = extend function extend() { @@ -16494,7 +16457,7 @@ function extend() { return target } -},{}],64:[function(require,module,exports){ +},{}],63:[function(require,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; @@ -16536,11 +16499,11 @@ module.exports = function forEach(obj, fn) { }; -},{}],65:[function(require,module,exports){ +},{}],64:[function(require,module,exports){ module.exports = Object.keys || require('./shim'); -},{"./shim":67}],66:[function(require,module,exports){ +},{"./shim":66}],65:[function(require,module,exports){ var toString = Object.prototype.toString; module.exports = function isArguments(value) { @@ -16558,7 +16521,7 @@ module.exports = function isArguments(value) { }; -},{}],67:[function(require,module,exports){ +},{}],66:[function(require,module,exports){ (function () { "use strict"; @@ -16622,7 +16585,7 @@ module.exports = function isArguments(value) { }()); -},{"./foreach":64,"./isArguments":66}],68:[function(require,module,exports){ +},{"./foreach":63,"./isArguments":65}],67:[function(require,module,exports){ module.exports = hasKeys function hasKeys(source) { @@ -16631,7 +16594,7 @@ function hasKeys(source) { typeof source === "function") } -},{}],69:[function(require,module,exports){ +},{}],68:[function(require,module,exports){ var Keys = require("object-keys") var hasKeys = require("./has-keys") @@ -16658,7 +16621,7 @@ function extend() { return target } -},{"./has-keys":68,"object-keys":65}],70:[function(require,module,exports){ +},{"./has-keys":67,"object-keys":64}],69:[function(require,module,exports){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at * MIT License @@ -16743,7 +16706,7 @@ Batch.prototype.write = function (callback) { module.exports = Batch -},{"./util":72,"level-errors":48}],71:[function(require,module,exports){ +},{"./util":71,"level-errors":47}],70:[function(require,module,exports){ (function (process){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at @@ -16766,6 +16729,7 @@ var EventEmitter = require('events').EventEmitter , OpenError = errors.OpenError , EncodingError = errors.EncodingError , InitializationError = errors.InitializationError + , LevelUPError = errors.LevelUPError , util = require('./util') , Batch = require('./batch') @@ -16773,7 +16737,7 @@ var EventEmitter = require('events').EventEmitter , getOptions = util.getOptions , defaultOptions = util.defaultOptions - , getLevelDOWN = util.getLevelDOWN + , getLevelDOWN = require('./leveldown') , dispatchError = util.dispatchError , isDefined = util.isDefined @@ -16855,11 +16819,16 @@ LevelUP.prototype.open = function (callback) { } this.emit('opening') - this._status = 'opening' this.db = new DeferredLevelDOWN(this.location) - dbFactory = this.options.db || getLevelDOWN() - db = dbFactory(this.location) + + if (typeof this.options.db !== 'function' && + typeof getLevelDOWN !== 'function') { + throw new LevelUPError('missing db factory, you need to set options.db') + } + + dbFactory = this.options.db || getLevelDOWN() + db = dbFactory(this.location) db.open(this.options, function (err) { if (err) { @@ -17146,7 +17115,7 @@ module.exports.repair = deprecate( }).call(this,require('_process')) -},{"./batch":70,"./util":72,"_process":85,"deferred-leveldown":13,"events":38,"level-codec":46,"level-errors":48,"level-iterator-stream":49,"prr":86,"util":131,"xtend":133}],72:[function(require,module,exports){ +},{"./batch":69,"./leveldown":6,"./util":71,"_process":84,"deferred-leveldown":12,"events":37,"level-codec":45,"level-errors":47,"level-iterator-stream":48,"prr":85,"util":134,"xtend":136}],71:[function(require,module,exports){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at * MIT License @@ -17154,8 +17123,6 @@ module.exports.repair = deprecate( */ var extend = require('xtend') - , LevelUPError = require('level-errors').LevelUPError - , format = require('util').format , defaultOptions = { createIfMissing : true , errorIfExists : false @@ -17164,8 +17131,6 @@ var extend = require('xtend') , compression : true } - , leveldown - function getOptions (options) { if (typeof options == 'string') options = { valueEncoding: options } @@ -17174,41 +17139,6 @@ function getOptions (options) { return options } -function getLevelDOWN () { - if (leveldown) - return leveldown - - var requiredVersion = require('../package.json').devDependencies.leveldown - , leveldownVersion - - try { - leveldownVersion = require('leveldown/package.json').version - } catch (e) { - throw requireError(e) - } - - if (!require('semver').satisfies(leveldownVersion, requiredVersion)) { - throw new LevelUPError( - 'Installed version of LevelDOWN (' - + leveldownVersion - + ') does not match required version (' - + requiredVersion - + ')' - ) - } - - try { - return leveldown = require('leveldown') - } catch (e) { - throw requireError(e) - } -} - -function requireError (e) { - var template = 'Failed to require LevelDOWN (%s). Try `npm install leveldown` if it\'s missing' - return new LevelUPError(format(template, e.message)) -} - function dispatchError (db, error, callback) { typeof callback == 'function' ? callback(error) : db.emit('error', error) } @@ -17220,212 +17150,11 @@ function isDefined (v) { module.exports = { defaultOptions : defaultOptions , getOptions : getOptions - , getLevelDOWN : getLevelDOWN , dispatchError : dispatchError , isDefined : isDefined } -},{"../package.json":73,"level-errors":48,"leveldown":6,"leveldown/package.json":6,"semver":6,"util":131,"xtend":133}],73:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - { - "raw": "levelup@^1.3.5", - "scope": null, - "escapedName": "levelup", - "name": "levelup", - "rawSpec": "^1.3.5", - "spec": ">=1.3.5 <2.0.0", - "type": "range" - }, - "/Users/fergusmcdowall/node/search-index" - ] - ], - "_from": "levelup@>=1.3.5 <2.0.0", - "_id": "levelup@1.3.5", - "_inCache": true, - "_installable": true, - "_location": "/levelup", - "_nodeVersion": "7.4.0", - "_npmOperationalInternal": { - "host": "packages-18-east.internal.npmjs.com", - "tmp": "tmp/levelup-1.3.5.tgz_1488477248468_0.036320413229987025" - }, - "_npmUser": { - "name": "ralphtheninja", - "email": "ralphtheninja@riseup.net" - }, - "_npmVersion": "4.0.5", - "_phantomChildren": {}, - "_requested": { - "raw": "levelup@^1.3.5", - "scope": null, - "escapedName": "levelup", - "name": "levelup", - "rawSpec": "^1.3.5", - "spec": ">=1.3.5 <2.0.0", - "type": "range" - }, - "_requiredBy": [ - "/", - "/search-index-adder", - "/search-index-searcher" - ], - "_resolved": "https://registry.npmjs.org/levelup/-/levelup-1.3.5.tgz", - "_shasum": "fa80a972b74011f2537c8b65678bd8b5188e4e66", - "_shrinkwrap": null, - "_spec": "levelup@^1.3.5", - "_where": "/Users/fergusmcdowall/node/search-index", - "browser": { - "leveldown": false, - "leveldown/package": false, - "semver": false - }, - "bugs": { - "url": "https://github.com/level/levelup/issues" - }, - "contributors": [ - { - "name": "Rod Vagg", - "email": "r@va.gg", - "url": "https://github.com/rvagg" - }, - { - "name": "John Chesley", - "email": "john@chesl.es", - "url": "https://github.com/chesles/" - }, - { - "name": "Jake Verbaten", - "email": "raynos2@gmail.com", - "url": "https://github.com/raynos" - }, - { - "name": "Dominic Tarr", - "email": "dominic.tarr@gmail.com", - "url": "https://github.com/dominictarr" - }, - { - "name": "Max Ogden", - "email": "max@maxogden.com", - "url": "https://github.com/maxogden" - }, - { - "name": "Lars-Magnus Skog", - "email": "ralphtheninja@riseup.net", - "url": "https://github.com/ralphtheninja" - }, - { - "name": "David Björklund", - "email": "david.bjorklund@gmail.com", - "url": "https://github.com/kesla" - }, - { - "name": "Julian Gruber", - "email": "julian@juliangruber.com", - "url": "https://github.com/juliangruber" - }, - { - "name": "Paolo Fragomeni", - "email": "paolo@async.ly", - "url": "https://github.com/0x00a" - }, - { - "name": "Anton Whalley", - "email": "anton.whalley@nearform.com", - "url": "https://github.com/No9" - }, - { - "name": "Matteo Collina", - "email": "matteo.collina@gmail.com", - "url": "https://github.com/mcollina" - }, - { - "name": "Pedro Teixeira", - "email": "pedro.teixeira@gmail.com", - "url": "https://github.com/pgte" - }, - { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "https://github.com/substack" - }, - { - "name": "Jarrett Cruger", - "email": "jcrugzz@gmail.com", - "url": "https://github.com/jcrugzz" - } - ], - "dependencies": { - "deferred-leveldown": "~1.2.1", - "level-codec": "~6.1.0", - "level-errors": "~1.0.3", - "level-iterator-stream": "~1.3.0", - "prr": "~1.0.1", - "semver": "~5.1.0", - "xtend": "~4.0.0" - }, - "description": "Fast & simple storage - a Node.js-style LevelDB wrapper", - "devDependencies": { - "async": "~1.5.0", - "bustermove": "~1.0.0", - "delayed": "~1.0.1", - "faucet": "~0.0.1", - "leveldown": "^1.1.0", - "memdown": "~1.1.0", - "msgpack-js": "~0.3.0", - "referee": "~1.2.0", - "rimraf": "~2.4.3", - "slow-stream": "0.0.4", - "tap": "~2.3.1", - "tape": "~4.2.1" - }, - "directories": {}, - "dist": { - "shasum": "fa80a972b74011f2537c8b65678bd8b5188e4e66", - "tarball": "https://registry.npmjs.org/levelup/-/levelup-1.3.5.tgz" - }, - "gitHead": "ed5a54202085839784f1189f1266e9c379d64081", - "homepage": "https://github.com/level/levelup", - "keywords": [ - "leveldb", - "stream", - "database", - "db", - "store", - "storage", - "json" - ], - "license": "MIT", - "main": "lib/levelup.js", - "maintainers": [ - { - "name": "rvagg", - "email": "rod@vagg.org" - }, - { - "name": "ralphtheninja", - "email": "ralphtheninja@riseup.net" - }, - { - "name": "juliangruber", - "email": "julian@juliangruber.com" - } - ], - "name": "levelup", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/level/levelup.git" - }, - "scripts": { - "test": "tape test/*-test.js | faucet" - }, - "version": "1.3.5" -} - -},{}],74:[function(require,module,exports){ +},{"xtend":136}],72:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -18599,7 +18328,7 @@ function isObjectLike(value) { module.exports = difference; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],75:[function(require,module,exports){ +},{}],73:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -19668,7 +19397,7 @@ function isObjectLike(value) { module.exports = intersection; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],76:[function(require,module,exports){ +},{}],74:[function(require,module,exports){ (function (global){ /** * Lodash (Custom Build) @@ -21520,7 +21249,7 @@ function stubFalse() { module.exports = isEqual; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],77:[function(require,module,exports){ +},{}],75:[function(require,module,exports){ /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` @@ -21773,7 +21502,7 @@ function identity(value) { module.exports = sortedIndexOf; -},{}],78:[function(require,module,exports){ +},{}],76:[function(require,module,exports){ /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` @@ -22179,7 +21908,7 @@ function toNumber(value) { module.exports = spread; -},{}],79:[function(require,module,exports){ +},{}],77:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -23364,7 +23093,7 @@ function noop() { module.exports = union; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],80:[function(require,module,exports){ +},{}],78:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -24264,7 +23993,7 @@ function noop() { module.exports = uniq; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],81:[function(require,module,exports){ +},{}],79:[function(require,module,exports){ (function (Buffer){ exports.compare = function (a, b) { @@ -24312,9 +24041,9 @@ var lowerBoundKey = exports.lowerBoundKey = function (range) { ) } -var lowerBound = exports.lowerBound = function (range) { +var lowerBound = exports.lowerBound = function (range, def) { var k = lowerBoundKey(range) - return k && range[k] + return k ? range[k] : def } var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) { @@ -24346,9 +24075,30 @@ var upperBoundKey = exports.upperBoundKey = function (range) { ) } -var upperBound = exports.upperBound = function (range) { +var upperBound = exports.upperBound = function (range, def) { var k = upperBoundKey(range) - return k && range[k] + return k ? range[k] : def +} + +exports.start = function (range, def) { + return range.reverse ? upperBound(range, def) : lowerBound(range, def) +} +exports.end = function (range, def) { + return range.reverse ? lowerBound(range, def) : upperBound(range, def) +} +exports.startInclusive = function (range) { + return ( + range.reverse + ? upperBoundInclusive(range) + : lowerBoundInclusive(range) + ) +} +exports.endInclusive = function (range) { + return ( + range.reverse + ? lowerBoundInclusive(range) + : upperBoundInclusive(range) + ) } function id (e) { return e } @@ -24415,11 +24165,43 @@ exports.filter = function (range, compare) { +}).call(this,{"isBuffer":require("../is-buffer/index.js")}) +},{"../is-buffer/index.js":42}],80:[function(require,module,exports){ +// nGramLengths is of the form [ 9, 10 ] +const getNGramsOfMultipleLengths = function (inputArray, nGramLengths) { + var outputArray = [] + nGramLengths.forEach(function (len) { + outputArray = outputArray.concat(getNGramsOfSingleLength(inputArray, len)) + }) + return outputArray +} +// nGramLengths is of the form { gte: 9, lte: 10 } +const getNGramsOfRangeOfLengths = function (inputArray, nGramLengths) { + var outputArray = [] + for (var i = nGramLengths.gte; i <= nGramLengths.lte; i++) { + outputArray = outputArray.concat(getNGramsOfSingleLength(inputArray, i)) + } + return outputArray +} -}).call(this,{"isBuffer":require("../is-buffer/index.js")}) -},{"../is-buffer/index.js":43}],82:[function(require,module,exports){ +// nGramLength is a single integer +const getNGramsOfSingleLength = function (inputArray, nGramLength) { + return inputArray.slice(nGramLength - 1).map(function (item, i) { + return inputArray.slice(i, i + nGramLength) + }) +} + +exports.ngram = function (inputArray, nGramLength) { + switch (nGramLength.constructor) { + case Array: return getNGramsOfMultipleLengths(inputArray, nGramLength) + case Number: return getNGramsOfSingleLength(inputArray, nGramLength) + case Object: return getNGramsOfRangeOfLengths(inputArray, nGramLength) + } +} + +},{}],81:[function(require,module,exports){ var wrappy = require('wrappy') module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) @@ -24463,7 +24245,7 @@ function onceStrict (fn) { return f } -},{"wrappy":132}],83:[function(require,module,exports){ +},{"wrappy":135}],82:[function(require,module,exports){ exports.endianness = function () { return 'LE' }; exports.hostname = function () { @@ -24510,7 +24292,7 @@ exports.tmpdir = exports.tmpDir = function () { exports.EOL = '\n'; -},{}],84:[function(require,module,exports){ +},{}],83:[function(require,module,exports){ (function (process){ 'use strict'; @@ -24557,7 +24339,7 @@ function nextTick(fn, arg1, arg2, arg3) { } }).call(this,require('_process')) -},{"_process":85}],85:[function(require,module,exports){ +},{"_process":84}],84:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -24728,6 +24510,10 @@ process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); @@ -24739,9 +24525,9 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],86:[function(require,module,exports){ -arguments[4][37][0].apply(exports,arguments) -},{"dup":37}],87:[function(require,module,exports){ +},{}],85:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],86:[function(require,module,exports){ var once = require('once') var eos = require('end-of-stream') var fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes @@ -24823,7 +24609,7 @@ var pump = function () { module.exports = pump -},{"end-of-stream":34,"fs":6,"once":82}],88:[function(require,module,exports){ +},{"end-of-stream":33,"fs":6,"once":81}],87:[function(require,module,exports){ var pump = require('pump') var inherits = require('inherits') var Duplexify = require('duplexify') @@ -24880,10 +24666,31 @@ var define = function(opts) { module.exports = define({destroy:false}) module.exports.obj = define({destroy:false, objectMode:true, highWaterMark:16}) -},{"duplexify":31,"inherits":41,"pump":87}],89:[function(require,module,exports){ +},{"duplexify":30,"inherits":40,"pump":86}],88:[function(require,module,exports){ module.exports = require('./lib/_stream_duplex.js'); -},{"./lib/_stream_duplex.js":90}],90:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":89}],89:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from @@ -24893,6 +24700,10 @@ module.exports = require('./lib/_stream_duplex.js'); /**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { @@ -24903,10 +24714,6 @@ var objectKeys = Object.keys || function (obj) { module.exports = Duplex; -/**/ -var processNextTick = require('process-nextick-args'); -/**/ - /**/ var util = require('core-util-is'); util.inherits = require('inherits'); @@ -24954,12 +24761,61 @@ function onEndNT(self) { self.end(); } +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + processNextTick(cb, err); +}; + function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } -},{"./_stream_readable":92,"./_stream_writable":94,"core-util-is":11,"inherits":41,"process-nextick-args":84}],91:[function(require,module,exports){ +},{"./_stream_readable":91,"./_stream_writable":93,"core-util-is":10,"inherits":40,"process-nextick-args":83}],90:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. @@ -24986,16 +24842,38 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":93,"core-util-is":11,"inherits":41}],92:[function(require,module,exports){ +},{"./_stream_transform":92,"core-util-is":10,"inherits":40}],91:[function(require,module,exports){ (function (process){ -'use strict'; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -module.exports = Readable; +'use strict'; /**/ + var processNextTick = require('process-nextick-args'); /**/ +module.exports = Readable; + /**/ var isArray = require('isarray'); /**/ @@ -25015,19 +24893,19 @@ var EElistenerCount = function (emitter, type) { /**/ /**/ -var Stream; -(function () { - try { - Stream = require('st' + 'ream'); - } catch (_) {} finally { - if (!Stream) Stream = require('events').EventEmitter; - } -})(); +var Stream = require('./internal/streams/stream'); /**/ -var Buffer = require('buffer').Buffer; +// TODO(bmeurer): Change this back to const once hole checks are +// properly optimized away early in Ignition+TurboFan. /**/ -var bufferShim = require('buffer-shims'); +var Buffer = require('safe-buffer').Buffer; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]' || Buffer.isBuffer(obj); +} /**/ /**/ @@ -25046,10 +24924,13 @@ if (debugUtil && debugUtil.debuglog) { /**/ var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); var StringDecoder; util.inherits(Readable, Stream); +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. @@ -25082,7 +24963,7 @@ function ReadableState(options, stream) { this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than @@ -25096,10 +24977,10 @@ function ReadableState(options, stream) { this.endEmitted = false; this.reading = false; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say @@ -25109,15 +24990,14 @@ function ReadableState(options, stream) { this.readableListening = false; this.resumeScheduled = false; + // has it been destroyed + this.destroyed = false; + // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; @@ -25143,87 +25023,129 @@ function Readable(options) { // legacy this.readable = true; - if (options && typeof options.read === 'function') this._read = options.read; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } Stream.call(this); } +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; - - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = bufferShim.from(chunk, encoding); - encoding = ''; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; } + } else { + skipChunkCheck = true; } - return readableAddChunk(this, state, chunk, encoding, false); + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); + return readableAddChunk(this, chunk, null, true, false); }; -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { state.reading = false; onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && Object.getPrototypeOf(chunk) !== Buffer.prototype && !state.objectMode) { + chunk = _uint8ArrayToBuffer(chunk); } - if (!addToFront) state.reading = false; - - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); + addChunk(stream, state, chunk, false); } } - - maybeReadMore(stream, state); + } else if (!addToFront) { + state.reading = false; } - } else if (!addToFront) { - state.reading = false; } return needMoreData(state); } +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, @@ -25235,6 +25157,10 @@ function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; @@ -25383,14 +25309,6 @@ Readable.prototype.read = function (n) { return ret; }; -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { @@ -25478,14 +25396,17 @@ Readable.prototype.pipe = function (dest, pipeOpts) { var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : cleanup; + var endFn = doEnd ? onend : unpipe; if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); - function onunpipe(readable) { + function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { - cleanup(); + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } } @@ -25511,7 +25432,7 @@ Readable.prototype.pipe = function (dest, pipeOpts) { dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); - src.removeListener('end', cleanup); + src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; @@ -25604,6 +25525,7 @@ function pipeOnDrain(src) { Readable.prototype.unpipe = function (dest) { var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; @@ -25619,7 +25541,7 @@ Readable.prototype.unpipe = function (dest) { state.pipes = null; state.pipesCount = 0; state.flowing = false; - if (dest) dest.emit('unpipe', this); + if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } @@ -25634,7 +25556,7 @@ Readable.prototype.unpipe = function (dest) { state.flowing = false; for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this); + dests[i].emit('unpipe', this, unpipeInfo); }return this; } @@ -25646,7 +25568,7 @@ Readable.prototype.unpipe = function (dest) { state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this); + dest.emit('unpipe', this, unpipeInfo); return this; }; @@ -25667,7 +25589,7 @@ Readable.prototype.on = function (ev, fn) { if (!state.reading) { processNextTick(nReadingNextTick, this); } else if (state.length) { - emitReadable(this, state); + emitReadable(this); } } } @@ -25774,10 +25696,9 @@ Readable.prototype.wrap = function (stream) { } // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the // underlying stream. @@ -25869,7 +25790,7 @@ function copyFromBufferString(n, list) { // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { - var ret = bufferShim.allocUnsafe(n); + var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); @@ -25930,7 +25851,28 @@ function indexOf(xs, x) { return -1; } }).call(this,require('_process')) -},{"./_stream_duplex":90,"./internal/streams/BufferList":95,"_process":85,"buffer":9,"buffer-shims":8,"core-util-is":11,"events":38,"inherits":41,"isarray":44,"process-nextick-args":84,"string_decoder/":124,"util":6}],93:[function(require,module,exports){ +},{"./_stream_duplex":89,"./internal/streams/BufferList":94,"./internal/streams/destroy":95,"./internal/streams/stream":96,"_process":84,"core-util-is":10,"events":37,"inherits":40,"isarray":43,"process-nextick-args":83,"safe-buffer":101,"string_decoder/":127,"util":6}],92:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where @@ -26004,7 +25946,9 @@ function afterTransform(stream, er, data) { var cb = ts.writecb; - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + if (!cb) { + return stream.emit('error', new Error('write callback called multiple times')); + } ts.writechunk = null; ts.writecb = null; @@ -26097,6 +26041,15 @@ Transform.prototype._read = function (n) { } }; +Transform.prototype._destroy = function (err, cb) { + var _this = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this.emit('close'); + }); +}; + function done(stream, er, data) { if (er) return stream.emit('error', er); @@ -26113,20 +26066,63 @@ function done(stream, er, data) { return stream.push(null); } -},{"./_stream_duplex":90,"core-util-is":11,"inherits":41}],94:[function(require,module,exports){ +},{"./_stream_duplex":89,"core-util-is":10,"inherits":40}],93:[function(require,module,exports){ (function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; -module.exports = Writable; - /**/ + var processNextTick = require('process-nextick-args'); /**/ +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + /**/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; /**/ @@ -26149,32 +26145,25 @@ var internalUtil = { /**/ /**/ -var Stream; -(function () { - try { - Stream = require('st' + 'ream'); - } catch (_) {} finally { - if (!Stream) Stream = require('events').EventEmitter; - } -})(); +var Stream = require('./internal/streams/stream'); /**/ -var Buffer = require('buffer').Buffer; /**/ -var bufferShim = require('buffer-shims'); +var Buffer = require('safe-buffer').Buffer; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]' || Buffer.isBuffer(obj); +} /**/ +var destroyImpl = require('./internal/streams/destroy'); + util.inherits(Writable, Stream); function nop() {} -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} - function WritableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); @@ -26194,7 +26183,10 @@ function WritableState(options, stream) { this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; // drain event flag. this.needDrain = false; @@ -26205,6 +26197,9 @@ function WritableState(options, stream) { // when 'finish' is emitted this.finished = false; + // has it been destroyed + this.destroyed = false; + // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. @@ -26286,7 +26281,7 @@ WritableState.prototype.getBuffer = function getBuffer() { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); @@ -26332,6 +26327,10 @@ function Writable(options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); @@ -26372,7 +26371,11 @@ function validChunk(stream, state, chunk, cb) { Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; - var isBuf = Buffer.isBuffer(chunk); + var isBuf = _isUint8Array(chunk) && !state.objectMode; + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } if (typeof encoding === 'function') { cb = encoding; @@ -26417,7 +26420,7 @@ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = bufferShim.from(chunk, encoding); + chunk = Buffer.from(chunk, encoding); } return chunk; } @@ -26427,8 +26430,12 @@ function decodeChunk(state, chunk, encoding) { // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } } var len = state.objectMode ? 1 : chunk.length; @@ -26440,7 +26447,13 @@ function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (state.writing || state.corked) { var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; if (last) { last.next = state.lastBufferedRequest; } else { @@ -26465,10 +26478,26 @@ function doWrite(stream, state, writev, len, chunk, encoding, cb) { function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; - if (sync) processNextTick(cb, er);else cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + processNextTick(cb, er); + // this can emit finish, and it will always happen + // after error + processNextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } } function onwriteStateUpdate(state) { @@ -26533,11 +26562,14 @@ function clearBuffer(stream, state) { holder.entry = entry; var count = 0; + var allBuffers = true; while (entry) { buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } + buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); @@ -26611,23 +26643,37 @@ Writable.prototype.end = function (chunk, encoding, cb) { function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } - -function prefinish(stream, state) { - if (!state.prefinished) { +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } state.prefinished = true; stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + processNextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { + prefinish(stream, state); if (state.pendingcb === 0) { - prefinish(stream, state); state.finished = true; stream.emit('finish'); - } else { - prefinish(stream, state); } } return need; @@ -26643,99 +26689,205 @@ function endWritable(stream, state, cb) { stream.writable = false; } -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} - this.next = null; - this.entry = null; - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; } - }; -} + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; + }).call(this,require('_process')) -},{"./_stream_duplex":90,"_process":85,"buffer":9,"buffer-shims":8,"core-util-is":11,"events":38,"inherits":41,"process-nextick-args":84,"util-deprecate":128}],95:[function(require,module,exports){ +},{"./_stream_duplex":89,"./internal/streams/destroy":95,"./internal/streams/stream":96,"_process":84,"core-util-is":10,"inherits":40,"process-nextick-args":83,"safe-buffer":101,"util-deprecate":131}],94:[function(require,module,exports){ 'use strict'; -var Buffer = require('buffer').Buffer; /**/ -var bufferShim = require('buffer-shims'); -/**/ -module.exports = BufferList; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; +var Buffer = require('safe-buffer').Buffer; +/**/ + +function copyBuffer(src, target, offset) { + src.copy(target, offset); } -BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; -}; +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); -BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; -}; + this.head = null; + this.tail = null; + this.length = 0; + } -BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; -}; + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; -BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; -}; + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; -BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; -}; + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); +},{"safe-buffer":101}],95:[function(require,module,exports){ +'use strict'; + +/**/ + +var processNextTick = require('process-nextick-args'); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + processNextTick(emitErrorNT, this, err); + } + return; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks -BufferList.prototype.concat = function (n) { - if (this.length === 0) return bufferShim.alloc(0); - if (this.length === 1) return this.head.data; - var ret = bufferShim.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; + if (this._readableState) { + this._readableState.destroyed = true; } - return ret; + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + processNextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy }; -},{"buffer":9,"buffer-shims":8}],96:[function(require,module,exports){ +},{"process-nextick-args":83}],96:[function(require,module,exports){ +module.exports = require('events').EventEmitter; + +},{"events":37}],97:[function(require,module,exports){ module.exports = require('./readable').PassThrough -},{"./readable":97}],97:[function(require,module,exports){ +},{"./readable":98}],98:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; @@ -26744,13 +26896,77 @@ exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); -},{"./lib/_stream_duplex.js":90,"./lib/_stream_passthrough.js":91,"./lib/_stream_readable.js":92,"./lib/_stream_transform.js":93,"./lib/_stream_writable.js":94}],98:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":89,"./lib/_stream_passthrough.js":90,"./lib/_stream_readable.js":91,"./lib/_stream_transform.js":92,"./lib/_stream_writable.js":93}],99:[function(require,module,exports){ module.exports = require('./readable').Transform -},{"./readable":97}],99:[function(require,module,exports){ +},{"./readable":98}],100:[function(require,module,exports){ module.exports = require('./lib/_stream_writable.js'); -},{"./lib/_stream_writable.js":94}],100:[function(require,module,exports){ +},{"./lib/_stream_writable.js":93}],101:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + +},{"buffer":8}],102:[function(require,module,exports){ var hasProp = Object.prototype.hasOwnProperty; function throwsMessage(err) { @@ -26811,7 +27027,7 @@ module.exports = function(data) { module.exports.ensureProperties = ensureProperties; -},{}],101:[function(require,module,exports){ +},{}],103:[function(require,module,exports){ /* search-index-adder @@ -26830,7 +27046,6 @@ const RecalibrateDB = require('./lib/delete.js').RecalibrateDB const bunyan = require('bunyan') const del = require('./lib/delete.js') const docProc = require('docproc') -const leveldown = require('leveldown') const levelup = require('levelup') const pumpify = require('pumpify') @@ -26841,33 +27056,60 @@ module.exports = function (givenOptions, callback) { var Indexer = {} Indexer.options = options - var q = async.queue(function (batch, callback) { - const s = new Readable({ objectMode: true }) - batch.batch.forEach(function (doc) { - s.push(doc) - }) - s.push(null) - s.pipe(Indexer.defaultPipeline(batch.batchOps)) - .pipe(Indexer.add()) - .on('data', function (data) {}) - .on('end', function () { - return callback() + var q = async.queue(function (batch, done) { + var s + if (batch.operation === 'add') { + s = new Readable({ objectMode: true }) + batch.batch.forEach(function (doc) { + s.push(doc) }) - .on('error', function (err) { - return callback(err) + s.push(null) + s.pipe(Indexer.defaultPipeline(batch.batchOps)) + .pipe(Indexer.add()) + // .on('data', function (data) {}) + .on('finish', function () { + return done() + }) + .on('error', function (err) { + return done(err) + }) + } else if (batch.operation === 'delete') { + s = new Readable() + batch.docIds.forEach(function (docId) { + s.push(JSON.stringify(docId)) }) + s.push(null) + s.pipe(Indexer.deleteStream(options)) + .on('data', function () { + // nowt + }) + .on('end', function () { + done(null) + }) + } }, 1) Indexer.add = function () { return pumpify.obj( new IndexBatch(Indexer), - new DBWriteMergeStream(options)) + new DBWriteMergeStream(options) + ) } Indexer.concurrentAdd = function (batchOps, batch, done) { q.push({ batch: batch, - batchOps: batchOps + batchOps: batchOps, + operation: 'add' + }, function (err) { + done(err) + }) + } + + Indexer.concurrentDel = function (docIds, done) { + q.push({ + docIds: docIds, + operation: 'delete' }, function (err) { done(err) }) @@ -26936,7 +27178,7 @@ module.exports = function (givenOptions, callback) { const getOptions = function (options, done) { options = Object.assign({}, { deletable: true, - batchSize: 100000, + batchSize: 1000, fieldedSearch: true, fieldOptions: {}, preserveCase: false, @@ -26947,7 +27189,7 @@ const getOptions = function (options, done) { logLevel: 'error', nGramLength: 1, nGramSeparator: ' ', - separator: /\\n|[|' ><.,\-|]+|\\u0003/, + separator: /\s|\\n|\\u0003|[-.,<>]/, stopwords: [], weight: 0 }, options) @@ -26956,6 +27198,7 @@ const getOptions = function (options, done) { level: options.logLevel }) if (!options.indexes) { + const leveldown = require('leveldown') levelup(options.indexPath || 'si', { valueEncoding: 'json', db: leveldown @@ -26968,7 +27211,7 @@ const getOptions = function (options, done) { } } -},{"./lib/add.js":102,"./lib/delete.js":103,"./lib/replicate.js":104,"async":4,"bunyan":10,"docproc":19,"leveldown":58,"levelup":71,"pumpify":88,"stream":122}],102:[function(require,module,exports){ +},{"./lib/add.js":104,"./lib/delete.js":105,"./lib/replicate.js":106,"async":4,"bunyan":9,"docproc":18,"leveldown":57,"levelup":70,"pumpify":87,"stream":125}],104:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27028,7 +27271,7 @@ IndexBatch.prototype._flush = function (end) { return end() } -},{"stream":122,"util":131}],103:[function(require,module,exports){ +},{"stream":125,"util":134}],105:[function(require,module,exports){ // deletes all references to a document from the search index const util = require('util') @@ -27149,19 +27392,20 @@ RecalibrateDB.prototype._transform = function (dbEntry, encoding, end) { }) } -},{"stream":122,"util":131}],104:[function(require,module,exports){ +},{"stream":125,"util":134}],106:[function(require,module,exports){ const Transform = require('stream').Transform +const Writable = require('stream').Writable const util = require('util') const DBWriteMergeStream = function (options) { this.options = options - Transform.call(this, { objectMode: true }) + Writable.call(this, { objectMode: true }) } exports.DBWriteMergeStream = DBWriteMergeStream -util.inherits(DBWriteMergeStream, Transform) -DBWriteMergeStream.prototype._transform = function (data, encoding, end) { +util.inherits(DBWriteMergeStream, Writable) +DBWriteMergeStream.prototype._write = function (data, encoding, end) { if (data.totalKeys) { - this.push(data) + // this.push(data) return end() } const sep = this.options.keySeparator @@ -27173,8 +27417,11 @@ DBWriteMergeStream.prototype._transform = function (data, encoding, end) { if (data.key.substring(0, 3) === 'TF' + sep) { // sort first on magnitude then on ID newVal = data.value.concat(val || []).sort(function (a, b) { - if (a[0] === b[0]) return b[1] - a[1] - else return b[0] - a[0] + if (a[0] < b[0]) return 1 + if (a[0] > b[0]) return -1 + if (a[1] < b[1]) return 1 + if (a[1] > b[1]) return -1 + return 0 }) } else if (data.key.substring(0, 3) === 'DF' + sep) { newVal = data.value.concat(val || []).sort() @@ -27185,7 +27432,7 @@ DBWriteMergeStream.prototype._transform = function (data, encoding, end) { } that.options.indexes.put(data.key, newVal, function (err) { err // do something with this error - that.push(data) + // that.push(data) end() }) }) @@ -27223,7 +27470,7 @@ DBWriteCleanStream.prototype._flush = function (end) { } exports.DBWriteCleanStream = DBWriteCleanStream -},{"stream":122,"util":131}],105:[function(require,module,exports){ +},{"stream":125,"util":134}],107:[function(require,module,exports){ const AvailableFields = require('./lib/AvailableFields.js').AvailableFields const CalculateBuckets = require('./lib/CalculateBuckets.js').CalculateBuckets const CalculateCategories = require('./lib/CalculateCategories.js').CalculateCategories @@ -27231,6 +27478,7 @@ const CalculateEntireResultSet = require('./lib/CalculateEntireResultSet.js').Ca const CalculateResultSetPerClause = require('./lib/CalculateResultSetPerClause.js').CalculateResultSetPerClause const CalculateTopScoringDocs = require('./lib/CalculateTopScoringDocs.js').CalculateTopScoringDocs const CalculateTotalHits = require('./lib/CalculateTotalHits.js').CalculateTotalHits +const Classify = require('./lib/Classify.js').Classify const FetchDocsFromDB = require('./lib/FetchDocsFromDB.js').FetchDocsFromDB const FetchStoredDoc = require('./lib/FetchStoredDoc.js').FetchStoredDoc const GetIntersectionStream = require('./lib/GetIntersectionStream.js').GetIntersectionStream @@ -27271,6 +27519,10 @@ const initModule = function (err, Searcher, moduleReady) { .pipe(new CalculateCategories(Searcher.options, q)) } + Searcher.classify = function (ops) { + return new Classify(Searcher, ops) + } + Searcher.close = function (callback) { Searcher.options.indexes.close(function (err) { while (!Searcher.options.indexes.isClosed()) { @@ -27411,7 +27663,7 @@ module.exports = function (givenOptions, moduleReady) { }) } -},{"./lib/AvailableFields.js":106,"./lib/CalculateBuckets.js":107,"./lib/CalculateCategories.js":108,"./lib/CalculateEntireResultSet.js":109,"./lib/CalculateResultSetPerClause.js":110,"./lib/CalculateTopScoringDocs.js":111,"./lib/CalculateTotalHits.js":112,"./lib/FetchDocsFromDB.js":113,"./lib/FetchStoredDoc.js":114,"./lib/GetIntersectionStream.js":115,"./lib/MergeOrConditions.js":116,"./lib/ScoreDocsOnField.js":117,"./lib/ScoreTopScoringDocsTFIDF.js":118,"./lib/SortTopScoringDocs.js":119,"./lib/matcher.js":120,"./lib/siUtil.js":121,"bunyan":10,"levelup":71,"stream":122}],106:[function(require,module,exports){ +},{"./lib/AvailableFields.js":108,"./lib/CalculateBuckets.js":109,"./lib/CalculateCategories.js":110,"./lib/CalculateEntireResultSet.js":111,"./lib/CalculateResultSetPerClause.js":112,"./lib/CalculateTopScoringDocs.js":113,"./lib/CalculateTotalHits.js":114,"./lib/Classify.js":115,"./lib/FetchDocsFromDB.js":116,"./lib/FetchStoredDoc.js":117,"./lib/GetIntersectionStream.js":118,"./lib/MergeOrConditions.js":119,"./lib/ScoreDocsOnField.js":120,"./lib/ScoreTopScoringDocsTFIDF.js":121,"./lib/SortTopScoringDocs.js":122,"./lib/matcher.js":123,"./lib/siUtil.js":124,"bunyan":9,"levelup":70,"stream":125}],108:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27426,7 +27678,7 @@ AvailableFields.prototype._transform = function (field, encoding, end) { return end() } -},{"stream":122,"util":131}],107:[function(require,module,exports){ +},{"stream":125,"util":134}],109:[function(require,module,exports){ const _intersection = require('lodash.intersection') const _uniq = require('lodash.uniq') const Transform = require('stream').Transform @@ -27467,7 +27719,7 @@ CalculateBuckets.prototype._transform = function (mergedQueryClauses, encoding, }) } -},{"lodash.intersection":75,"lodash.uniq":80,"stream":122,"util":131}],108:[function(require,module,exports){ +},{"lodash.intersection":73,"lodash.uniq":78,"stream":125,"util":134}],110:[function(require,module,exports){ const _intersection = require('lodash.intersection') const Transform = require('stream').Transform const util = require('util') @@ -27530,7 +27782,7 @@ CalculateCategories.prototype._transform = function (mergedQueryClauses, encodin }) } -},{"lodash.intersection":75,"stream":122,"util":131}],109:[function(require,module,exports){ +},{"lodash.intersection":73,"stream":125,"util":134}],111:[function(require,module,exports){ const Transform = require('stream').Transform const _union = require('lodash.union') const util = require('util') @@ -27553,7 +27805,7 @@ CalculateEntireResultSet.prototype._flush = function (end) { return end() } -},{"lodash.union":79,"stream":122,"util":131}],110:[function(require,module,exports){ +},{"lodash.union":77,"stream":125,"util":134}],112:[function(require,module,exports){ const Transform = require('stream').Transform const _difference = require('lodash.difference') const _intersection = require('lodash.intersection') @@ -27648,7 +27900,7 @@ CalculateResultSetPerClause.prototype._transform = function (queryClause, encodi }) } -},{"./siUtil.js":121,"lodash.difference":74,"lodash.intersection":75,"lodash.spread":78,"stream":122,"util":131}],111:[function(require,module,exports){ +},{"./siUtil.js":124,"lodash.difference":72,"lodash.intersection":73,"lodash.spread":76,"stream":125,"util":134}],113:[function(require,module,exports){ const Transform = require('stream').Transform const _sortedIndexOf = require('lodash.sortedindexof') const util = require('util') @@ -27701,7 +27953,7 @@ CalculateTopScoringDocs.prototype._transform = function (clauseSet, encoding, en }) } -},{"lodash.sortedindexof":77,"stream":122,"util":131}],112:[function(require,module,exports){ +},{"lodash.sortedindexof":75,"stream":125,"util":134}],114:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27718,7 +27970,78 @@ CalculateTotalHits.prototype._transform = function (mergedQueryClauses, encoding end() } -},{"stream":122,"util":131}],113:[function(require,module,exports){ +},{"stream":125,"util":134}],115:[function(require,module,exports){ +const Transform = require('stream').Transform +const ngraminator = require('ngraminator') +const util = require('util') + +const checkTokens = function (that, potentialMatches, field, done) { + var i = 0 // eslint-disable-line + var match = function (i) { + if (i === potentialMatches.length) return done() + var matchQuery = { + beginsWith: potentialMatches[i], + // beginsWith: 'strl p 59', + field: field, + type: 'ID', + threshold: 0, + limit: 1 + } + that.searcher.match(matchQuery) + .on('data', function (match) { + if (match.token === potentialMatches[i]) { that.push(match) } + }).on('end', function () { + match(++i) + }) + } + match(0) +} + +const Classify = function (searcher, options) { + this.options = Object.assign({}, searcher.options, options) + this.searcher = searcher + // should maybe be maxNGramLength + this.maxNGramLength = this.options.maxNGramLength || 1 + this.field = this.options.field || '*' + this.stack = [] + Transform.call(this, { objectMode: true }) +} + +exports.Classify = Classify + +util.inherits(Classify, Transform) + +Classify.prototype._transform = function (token, encoding, end) { + var stack = this.stack + var t = token.toString() + var that = this + var potentialMatches = [] + stack.push(t) + if (stack.length < this.maxNGramLength) return end() + stack.forEach(function (item, i) { + potentialMatches.push(stack.slice(0, (1 + i)).join(' ').toLowerCase()) + }) + checkTokens(that, potentialMatches, this.field, function () { + stack.shift() + return end() + }) +} + +Classify.prototype._flush = function (end) { + var that = this + var stack = this.stack + var potentialMatches = ngraminator.ngram(stack, { + gte: 1, + lte: that.maxNGramLength + }).map(function (token) { + return token.join(' ').toLowerCase() + }) + checkTokens(that, potentialMatches, this.field, function () { + return end() + }) +} + +},{"ngraminator":80,"stream":125,"util":134}],116:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27739,7 +28062,7 @@ FetchDocsFromDB.prototype._transform = function (line, encoding, end) { }) } -},{"stream":122,"util":131}],114:[function(require,module,exports){ +},{"stream":125,"util":134}],117:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27763,7 +28086,7 @@ FetchStoredDoc.prototype._transform = function (doc, encoding, end) { }) } -},{"stream":122,"util":131}],115:[function(require,module,exports){ +},{"stream":125,"util":134}],118:[function(require,module,exports){ const Transform = require('stream').Transform const iats = require('intersect-arrays-to-stream') const util = require('util') @@ -27798,7 +28121,7 @@ GetIntersectionStream.prototype._transform = function (line, encoding, end) { }) } -},{"intersect-arrays-to-stream":42,"stream":122,"util":131}],116:[function(require,module,exports){ +},{"intersect-arrays-to-stream":41,"stream":125,"util":134}],119:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27861,7 +28184,7 @@ MergeOrConditions.prototype._flush = function (end) { return end() } -},{"stream":122,"util":131}],117:[function(require,module,exports){ +},{"stream":125,"util":134}],120:[function(require,module,exports){ const Transform = require('stream').Transform const _sortedIndexOf = require('lodash.sortedindexof') const util = require('util') @@ -27900,7 +28223,7 @@ ScoreDocsOnField.prototype._transform = function (clauseSet, encoding, end) { }) } -},{"lodash.sortedindexof":77,"stream":122,"util":131}],118:[function(require,module,exports){ +},{"lodash.sortedindexof":75,"stream":125,"util":134}],121:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27978,7 +28301,7 @@ ScoreTopScoringDocsTFIDF.prototype._transform = function (clause, encoding, end) }) } -},{"stream":122,"util":131}],119:[function(require,module,exports){ +},{"stream":125,"util":134}],122:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -28024,7 +28347,7 @@ SortTopScoringDocs.prototype._flush = function (end) { return end() } -},{"stream":122,"util":131}],120:[function(require,module,exports){ +},{"stream":125,"util":134}],123:[function(require,module,exports){ const Readable = require('stream').Readable const Transform = require('stream').Transform const util = require('util') @@ -28038,27 +28361,6 @@ MatcherStream.prototype._transform = function (q, encoding, end) { const sep = this.options.keySeparator const that = this var results = [] - - const formatMatches = function (item) { - if (q.type === 'ID') { - that.push([item.key.split(sep)[2], item.value]) - } else if (q.type === 'count') { - that.push([item.key.split(sep)[2], item.value.length]) - } else { - that.push(item.key.split(sep)[2]) - } - } - - const sortResults = function (err) { - if (err) console.log(err) // TODO something clever with err - results.sort(function (a, b) { - return b.value.length - a.value.length - }) - .slice(0, q.limit) - .forEach(formatMatches) - end() - } - this.options.indexes.createReadStream({ start: 'DF' + sep + q.field + sep + q.beginsWith, end: 'DF' + sep + q.field + sep + q.beginsWith + sep @@ -28069,7 +28371,29 @@ MatcherStream.prototype._transform = function (q, encoding, end) { .on('error', function (err) { that.options.log.error('Oh my!', err) }) - .on('end', sortResults) + // .on('end', sortResults) + .on('end', function () { + results.sort(function (a, b) { + return b.value.length - a.value.length + }) + .slice(0, q.limit) + .forEach(function (item) { + var m = {} + switch (q.type) { + case 'ID': m = { + token: item.key.split(sep)[2], + documents: item.value + }; break + case 'count': m = { + token: item.key.split(sep)[2], + documentCount: item.value.length + }; break + default: m = item.key.split(sep)[2] + } + that.push(m) + }) + return end() + }) } exports.match = function (q, options) { @@ -28091,7 +28415,7 @@ exports.match = function (q, options) { return s.pipe(new MatcherStream(q, options)) } -},{"stream":122,"util":131}],121:[function(require,module,exports){ +},{"stream":125,"util":134}],124:[function(require,module,exports){ exports.getKeySet = function (clause, sep) { var keySet = [] for (var fieldName in clause) { @@ -28140,7 +28464,7 @@ exports.getQueryDefaults = function (q) { }, q) } -},{}],122:[function(require,module,exports){ +},{}],125:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -28269,7 +28593,7 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"events":38,"inherits":41,"readable-stream/duplex.js":89,"readable-stream/passthrough.js":96,"readable-stream/readable.js":97,"readable-stream/transform.js":98,"readable-stream/writable.js":99}],123:[function(require,module,exports){ +},{"events":37,"inherits":40,"readable-stream/duplex.js":88,"readable-stream/passthrough.js":97,"readable-stream/readable.js":98,"readable-stream/transform.js":99,"readable-stream/writable.js":100}],126:[function(require,module,exports){ module.exports = shift function shift (stream) { @@ -28291,11 +28615,10 @@ function getStateLength (state) { return state.length } -},{}],124:[function(require,module,exports){ +},{}],127:[function(require,module,exports){ 'use strict'; -var Buffer = require('buffer').Buffer; -var bufferShim = require('buffer-shims'); +var Buffer = require('safe-buffer').Buffer; var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; @@ -28372,7 +28695,7 @@ function StringDecoder(encoding) { } this.lastNeed = 0; this.lastTotal = 0; - this.lastChar = bufferShim.allocUnsafe(nb); + this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { @@ -28565,7 +28888,7 @@ function simpleWrite(buf) { function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } -},{"buffer":9,"buffer-shims":8}],125:[function(require,module,exports){ +},{"safe-buffer":101}],128:[function(require,module,exports){ exports.doubleNormalization0point5 = 'doubleNormalization0point5' exports.logNormalization = 'logNormalization' exports.raw = 'raw' @@ -28615,7 +28938,7 @@ exports.getTermFrequency = function (docVector, options) { } } -},{}],126:[function(require,module,exports){ +},{}],129:[function(require,module,exports){ /** * search-index module. * @module term-vector @@ -28681,7 +29004,7 @@ var getTermVectorForNgramLength = function (tokens, nGramLength) { return vector } -},{"lodash.isequal":76}],127:[function(require,module,exports){ +},{"lodash.isequal":74}],130:[function(require,module,exports){ (function (Buffer){ /** * Convert a typed array to a Buffer without a copy @@ -28704,7 +29027,7 @@ module.exports = function (arr) { } }).call(this,require("buffer").Buffer) -},{"buffer":9}],128:[function(require,module,exports){ +},{"buffer":8}],131:[function(require,module,exports){ (function (global){ /** @@ -28775,16 +29098,16 @@ function config (name) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],129:[function(require,module,exports){ -arguments[4][41][0].apply(exports,arguments) -},{"dup":41}],130:[function(require,module,exports){ +},{}],132:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"dup":40}],133:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -},{}],131:[function(require,module,exports){ +},{}],134:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -29374,7 +29697,7 @@ function hasOwnProperty(obj, prop) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":130,"_process":85,"inherits":129}],132:[function(require,module,exports){ +},{"./support/isBuffer":133,"_process":84,"inherits":132}],135:[function(require,module,exports){ // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. @@ -29409,7 +29732,7 @@ function wrappy (fn, cb) { } } -},{}],133:[function(require,module,exports){ +},{}],136:[function(require,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; diff --git a/dist/search-index.min.js b/dist/search-index.min.js index b9008494..9126d5ef 100644 --- a/dist/search-index.min.js +++ b/dist/search-index.min.js @@ -1,17 +1,13 @@ -!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.SearchIndex=f()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;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}for(var i="function"==typeof require&&require,o=0;oi;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return y>x?-1:x>y?1:0}function isBuffer(b){return global.Buffer&&"function"==typeof global.Buffer.isBuffer?global.Buffer.isBuffer(b):!(null==b||!b._isBuffer)}function pToString(obj){return Object.prototype.toString.call(obj)}function isView(arrbuf){return isBuffer(arrbuf)?!1:"function"!=typeof global.ArrayBuffer?!1:"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(arrbuf):arrbuf?arrbuf instanceof DataView?!0:arrbuf.buffer&&arrbuf.buffer instanceof ArrayBuffer?!0:!1:!1}function getName(func){if(util.isFunction(func)){if(functionsHaveNames)return func.name;var str=func.toString(),match=str.match(regex);return match&&match[1]}}function truncate(s,n){return"string"==typeof s?s.length=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return Error.isPrototypeOf(expected)?!1:expected.call({},actual)===!0}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert["throws"]=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":131}],4:[function(require,module,exports){(function(process,global){!function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory(global.async=global.async||{})}(this,function(exports){"use strict";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 overRest$1(func,start,transform){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&&MAX_SAFE_INTEGER>=value}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function noop(){}function once(fn){return function(){if(null!==fn){var callFn=fn;fn=null,callFn.apply(this,arguments)}}}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index-1&&value%1==0&&length>value}function baseIsTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]}function baseUnary(func){return function(value){return func(value)}}function arrayLikeKeys(value,inherited){var isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value)!inherited&&!hasOwnProperty$1.call(value,key)||skipIndexes&&("length"==key||isBuff&&("offset"==key||"parent"==key)||isType&&("buffer"==key||"byteLength"==key||"byteOffset"==key)||isIndex(key,length))||result.push(key);return result}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto$5;return value===proto}function overArg(func,transform){return function(arg){return func(transform(arg))}}function baseKeys(object){if(!isPrototype(object))return nativeKeys(object);var result=[];for(var key in Object(object))hasOwnProperty$3.call(object,key)&&"constructor"!=key&&result.push(key);return result}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function createArrayIterator(coll){var i=-1,len=coll.length;return function(){return++ii?{value:obj[key],key:key}:null}}function iterator(coll){if(isArrayLike(coll))return createArrayIterator(coll);var iterator=getIterator(coll);return iterator?createES2015Iterator(iterator):createObjectIterator(coll)}function onlyOnce(fn){return function(){if(null===fn)throw new Error("Callback was already called.");var callFn=fn;fn=null,callFn.apply(this,arguments)}}function _eachOfLimit(limit){return function(obj,iteratee,callback){function iterateeCallback(err,value){if(running-=1,err)done=!0,callback(err);else{if(value===breakLoop||done&&0>=running)return done=!0,callback(null);replenish()}}function replenish(){for(;limit>running&&!done;){var elem=nextElem();if(null===elem)return done=!0,void(0>=running&&callback(null));running+=1,iteratee(elem.value,elem.key,onlyOnce(iterateeCallback))}}if(callback=once(callback||noop),0>=limit||!obj)return callback(null);var nextElem=iterator(obj),done=!1,running=0;replenish()}}function eachOfLimit(coll,limit,iteratee,callback){_eachOfLimit(limit)(coll,wrapAsync$1(iteratee),callback)}function doLimit(fn,limit){return function(iterable,iteratee,callback){return fn(iterable,limit,iteratee,callback)}}function eachOfArrayLike(coll,iteratee,callback){function iteratorCallback(err,value){err?callback(err):(++completed===length||value===breakLoop)&&callback(null)}callback=once(callback||noop);var index=0,completed=0,length=coll.length;for(0===length&&callback(null);length>index;index++)iteratee(coll[index],index,onlyOnce(iteratorCallback))}function doParallel(fn){return function(obj,iteratee,callback){return fn(eachOf,obj,wrapAsync$1(iteratee),callback)}}function _asyncMap(eachfn,arr,iteratee,callback){callback=callback||noop,arr=arr||[];var results=[],counter=0,_iteratee=wrapAsync$1(iteratee);eachfn(arr,function(value,_,callback){var index=counter++;_iteratee(value,function(err,v){results[index]=v,callback(err)})},function(err){callback(err,results)})}function doParallelLimit(fn){return function(obj,limit,iteratee,callback){return fn(_eachOfLimit(limit),obj,wrapAsync$1(iteratee),callback)}}function arrayEach(array,iteratee){for(var index=-1,length=null==array?0:array.length;++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function charsStartIndex(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index-1;);return index}function asciiToArray(string){return string.split("")}function hasUnicode(string){return reHasUnicode.test(string)}function unicodeToArray(string){return string.match(reUnicode)||[]}function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string)}function toString(value){return null==value?"":baseToString(value)}function trim(string,chars,guard){if(string=toString(string),string&&(guard||void 0===chars))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function parseParams(func){return func=func.toString().replace(STRIP_COMMENTS,""),func=func.match(FN_ARGS)[2].replace(" ",""),func=func?func.split(FN_ARG_SPLIT):[],func=func.map(function(arg){return trim(arg.replace(FN_ARG,""))})}function autoInject(tasks,callback){var newTasks={};baseForOwn(tasks,function(taskFn,key){function newTask(results,taskCb){var newArgs=arrayMap(params,function(name){return results[name]});newArgs.push(taskCb),wrapAsync$1(taskFn).apply(null,newArgs)}var params,fnIsAsync=isAsync(taskFn),hasNoDeps=!fnIsAsync&&1===taskFn.length||fnIsAsync&&0===taskFn.length;if(isArray(taskFn))params=taskFn.slice(0,-1),taskFn=taskFn[taskFn.length-1],newTasks[key]=params.concat(params.length>0?newTask:taskFn);else if(hasNoDeps)newTasks[key]=taskFn;else{if(params=parseParams(taskFn),0===taskFn.length&&!fnIsAsync&&0===params.length)throw new Error("autoInject task functions require explicit parameters.");fnIsAsync||params.pop(),newTasks[key]=params.concat(newTask)}}),auto(newTasks,callback)}function fallback(fn){setTimeout(fn,0)}function wrap(defer){return rest(function(fn,args){defer(function(){fn.apply(null,args)})})}function DLL(){this.head=this.tail=null,this.length=0}function setInitial(dll,node){dll.length=1,dll.head=dll.tail=node}function queue(worker,concurrency,payload){function _insert(data,insertAtFront,callback){if(null!=callback&&"function"!=typeof callback)throw new Error("task callback must be a function");if(q.started=!0,isArray(data)||(data=[data]),0===data.length&&q.idle())return setImmediate$1(function(){q.drain()});for(var i=0,l=data.length;l>i;i++){var item={data:data[i],callback:callback||noop};insertAtFront?q._tasks.unshift(item):q._tasks.push(item)}setImmediate$1(q.process)}function _next(tasks){return rest(function(args){numRunning-=1;for(var i=0,l=tasks.length;l>i;i++){var task=tasks[i],index=baseIndexOf(workersList,task,0);index>=0&&workersList.splice(index),task.callback.apply(task,args),null!=args[0]&&q.error(args[0],task.data)}numRunning<=q.concurrency-q.buffer&&q.unsaturated(),q.idle()&&q.drain(),q.process()})}if(null==concurrency)concurrency=1;else if(0===concurrency)throw new Error("Concurrency must not be zero");var _worker=wrapAsync$1(worker),numRunning=0,workersList=[],isProcessing=!1,q={_tasks:new DLL,concurrency:concurrency,payload:payload,saturated:noop,unsaturated:noop,buffer:concurrency/4,empty:noop,drain:noop,error:noop,started:!1,paused:!1,push:function(data,callback){_insert(data,!1,callback)},kill:function(){q.drain=noop,q._tasks.empty()},unshift:function(data,callback){_insert(data,!0,callback)},process:function(){if(!isProcessing){for(isProcessing=!0;!q.paused&&numRunningi;i++){var node=q._tasks.shift();tasks.push(node),data.push(node.data)}0===q._tasks.length&&q.empty(),numRunning+=1,workersList.push(tasks[0]),numRunning===q.concurrency&&q.saturated();var cb=onlyOnce(_next(tasks));_worker(data,cb)}isProcessing=!1}},length:function(){return q._tasks.length},running:function(){return numRunning},workersList:function(){return workersList},idle:function(){return q._tasks.length+numRunning===0},pause:function(){q.paused=!0},resume:function(){q.paused!==!1&&(q.paused=!1,setImmediate$1(q.process))}};return q}function cargo(worker,payload){return queue(worker,1,payload)}function reduce(coll,memo,iteratee,callback){callback=once(callback||noop);var _iteratee=wrapAsync$1(iteratee);eachOfSeries(coll,function(x,i,callback){_iteratee(memo,x,function(err,v){memo=v,callback(err)})},function(err){callback(err,memo)})}function concat$1(eachfn,arr,fn,callback){var result=[];eachfn(arr,function(x,index,cb){fn(x,function(err,y){result=result.concat(y||[]),cb(err)})},function(err){callback(err,result)})}function doSeries(fn){return function(obj,iteratee,callback){return fn(eachOfSeries,obj,wrapAsync$1(iteratee),callback)}}function _createTester(check,getResult){return function(eachfn,arr,iteratee,cb){cb=cb||noop;var testResult,testPassed=!1;eachfn(arr,function(value,_,callback){iteratee(value,function(err,result){err?callback(err):check(result)&&!testResult?(testPassed=!0,testResult=getResult(!0,value),callback(null,breakLoop)):callback()})},function(err){err?cb(err):cb(null,testPassed?testResult:getResult(!1))})}}function _findGetResult(v,x){return x}function consoleFunc(name){return rest(function(fn,args){wrapAsync$1(fn).apply(null,args.concat(rest(function(err,args){"object"==typeof console&&(err?console.error&&console.error(err):console[name]&&arrayEach(args,function(x){console[name](x)}))})))})}function doDuring(fn,test,callback){function check(err,truth){return err?callback(err):truth?void _fn(next):callback(null)}callback=onlyOnce(callback||noop);var _fn=wrapAsync$1(fn),_test=wrapAsync$1(test),next=rest(function(err,args){return err?callback(err):(args.push(check),void _test.apply(this,args))});check(null,!0)}function doWhilst(iteratee,test,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync$1(iteratee),next=rest(function(err,args){return err?callback(err):test.apply(this,args)?_iteratee(next):void callback.apply(null,[null].concat(args))});_iteratee(next)}function doUntil(iteratee,test,callback){doWhilst(iteratee,function(){return!test.apply(this,arguments)},callback)}function during(test,fn,callback){function next(err){return err?callback(err):void _test(check)}function check(err,truth){return err?callback(err):truth?void _fn(next):callback(null)}callback=onlyOnce(callback||noop);var _fn=wrapAsync$1(fn),_test=wrapAsync$1(test);_test(check)}function _withoutIndex(iteratee){return function(value,index,callback){return iteratee(value,callback)}}function eachLimit(coll,iteratee,callback){eachOf(coll,_withoutIndex(wrapAsync$1(iteratee)),callback)}function eachLimit$1(coll,limit,iteratee,callback){_eachOfLimit(limit)(coll,_withoutIndex(wrapAsync$1(iteratee)),callback)}function ensureAsync(fn){return isAsync(fn)?fn:initialParams(function(args,callback){var sync=!0;args.push(function(){var innerArgs=arguments;sync?setImmediate$1(function(){callback.apply(null,innerArgs)}):callback.apply(null,innerArgs)}),fn.apply(this,args),sync=!1})}function notId(v){return!v}function baseProperty(key){return function(object){return null==object?void 0:object[key]}}function filterArray(eachfn,arr,iteratee,callback){var truthValues=new Array(arr.length);eachfn(arr,function(x,index,callback){iteratee(x,function(err,v){truthValues[index]=!!v,callback(err)})},function(err){if(err)return callback(err);for(var results=[],i=0;ii;i++)q[i].apply(null,args)}))))});return memoized.memo=memo,memoized.unmemoized=fn,memoized}function _parallel(eachfn,tasks,callback){callback=callback||noop;var results=isArrayLike(tasks)?[]:{};eachfn(tasks,function(task,key,callback){wrapAsync$1(task)(rest(function(err,args){args.length<=1&&(args=args[0]),results[key]=args,callback(err)}))},function(err){callback(err,results)})}function parallelLimit(tasks,callback){_parallel(eachOf,tasks,callback)}function parallelLimit$1(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)}function race(tasks,callback){if(callback=once(callback||noop),!isArray(tasks))return callback(new TypeError("First argument to race must be an array of functions"));if(!tasks.length)return callback();for(var i=0,l=tasks.length;l>i;i++)wrapAsync$1(tasks[i])(callback)}function reduceRight(array,memo,iteratee,callback){var reversed=slice.call(array).reverse();reduce(reversed,memo,iteratee,callback)}function reflect(fn){var _fn=wrapAsync$1(fn);return initialParams(function(args,reflectCallback){return args.push(rest(function(err,cbArgs){if(err)reflectCallback(null,{error:err});else{var value=null;1===cbArgs.length?value=cbArgs[0]:cbArgs.length>1&&(value=cbArgs),reflectCallback(null,{value:value})}})),_fn.apply(this,args)})}function reject$1(eachfn,arr,iteratee,callback){_filter(eachfn,arr,function(value,cb){iteratee(value,function(err,v){cb(err,!v)})},callback)}function reflectAll(tasks){var results;return isArray(tasks)?results=arrayMap(tasks,reflect):(results={},baseForOwn(tasks,function(task,key){results[key]=reflect.call(this,task)})),results}function constant$1(value){return function(){return value}}function retry(opts,task,callback){function parseTimes(acc,t){if("object"==typeof t)acc.times=+t.times||DEFAULT_TIMES,acc.intervalFunc="function"==typeof t.interval?t.interval:constant$1(+t.interval||DEFAULT_INTERVAL),acc.errorFilter=t.errorFilter;else{if("number"!=typeof t&&"string"!=typeof t)throw new Error("Invalid arguments for async.retry");acc.times=+t||DEFAULT_TIMES}}function retryAttempt(){_task(function(err){err&&attempt++a?-1:a>b?1:0}var _iteratee=wrapAsync$1(iteratee);map(coll,function(x,callback){_iteratee(x,function(err,criteria){return err?callback(err):void callback(null,{value:x,criteria:criteria})})},function(err,results){return err?callback(err):void callback(null,arrayMap(results.sort(comparator),baseProperty("value")))})}function timeout(asyncFn,milliseconds,info){function injectedCallback(){timedOut||(originalCallback.apply(null,arguments),clearTimeout(timer))}function timeoutCallback(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,originalCallback(error)}var originalCallback,timer,timedOut=!1,fn=wrapAsync$1(asyncFn);return initialParams(function(args,origCallback){originalCallback=origCallback,timer=setTimeout(timeoutCallback,milliseconds),fn.apply(null,args.concat(injectedCallback))})}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax$1(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function timeLimit(count,limit,iteratee,callback){var _iteratee=wrapAsync$1(iteratee);mapLimit(baseRange(0,count,1),limit,_iteratee,callback)}function transform(coll,accumulator,iteratee,callback){arguments.length<=3&&(callback=iteratee,iteratee=accumulator,accumulator=isArray(coll)?[]:{}),callback=once(callback||noop);var _iteratee=wrapAsync$1(iteratee);eachOf(coll,function(v,k,cb){_iteratee(accumulator,v,k,cb)},function(err){callback(err,accumulator)})}function unmemoize(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}}function whilst(test,iteratee,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync$1(iteratee);if(!test())return callback(null);var next=rest(function(err,args){return err?callback(err):test()?_iteratee(next):void callback.apply(null,[null].concat(args))});_iteratee(next)}function until(test,iteratee,callback){whilst(function(){return!test.apply(this,arguments)},iteratee,callback)}var nativeMax=Math.max,initialParams=function(fn){return rest(function(args){var callback=args.pop();fn.call(this,args,callback)})},supportsSymbol="function"==typeof Symbol,wrapAsync$1=supportsAsync()?wrapAsync:identity,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol$1=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag$1=Symbol$1?Symbol$1.toStringTag:void 0,objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString,nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$1?Symbol$1.toStringTag:void 0,asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]",MAX_SAFE_INTEGER=9007199254740991,breakLoop={},iteratorSymbol="function"==typeof Symbol&&Symbol.iterator,getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()},argsTag="[object Arguments]",objectProto$3=Object.prototype,hasOwnProperty$2=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$2.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,MAX_SAFE_INTEGER$1=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/,argsTag$1="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag$1="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",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]",typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag$1]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,objectProto$2=Object.prototype,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=overArg(Object.keys,Object),objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty,eachOfGeneric=doLimit(eachOfLimit,1/0),eachOf=function(coll,iteratee,callback){var eachOfImplementation=isArrayLike(coll)?eachOfArrayLike:eachOfGeneric;eachOfImplementation(coll,wrapAsync$1(iteratee),callback)},map=doParallel(_asyncMap),applyEach=applyEach$1(map),mapLimit=doParallelLimit(_asyncMap),mapSeries=doLimit(mapLimit,1),applyEachSeries=applyEach$1(mapSeries),apply$2=rest(function(fn,args){return rest(function(callArgs){return fn.apply(null,args.concat(callArgs))})}),baseFor=createBaseFor(),auto=function(tasks,concurrency,callback){function enqueueTask(key,task){readyTasks.push(function(){runTask(key,task)})}function processQueue(){if(0===readyTasks.length&&0===runningTasks)return callback(null,results);for(;readyTasks.length&&concurrency>runningTasks;){var run=readyTasks.shift();run()}}function addListener(taskName,fn){var taskListeners=listeners[taskName];taskListeners||(taskListeners=listeners[taskName]=[]),taskListeners.push(fn)}function taskComplete(taskName){var taskListeners=listeners[taskName]||[];arrayEach(taskListeners,function(fn){fn()}),processQueue()}function runTask(key,task){if(!hasError){var taskCallback=onlyOnce(rest(function(err,args){if(runningTasks--,args.length<=1&&(args=args[0]),err){var safeResults={};baseForOwn(results,function(val,rkey){safeResults[rkey]=val}),safeResults[key]=args,hasError=!0,listeners=Object.create(null),callback(err,safeResults)}else results[key]=args,taskComplete(key)}));runningTasks++;var taskFn=wrapAsync$1(task[task.length-1]);task.length>1?taskFn(results,taskCallback):taskFn(taskCallback)}}function checkForDeadlocks(){for(var currentTask,counter=0;readyToCheck.length;)currentTask=readyToCheck.pop(),counter++,arrayEach(getDependents(currentTask),function(dependent){0===--uncheckedDependencies[dependent]&&readyToCheck.push(dependent)});if(counter!==numTasks)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function getDependents(taskName){var result=[];return baseForOwn(tasks,function(task,key){isArray(task)&&baseIndexOf(task,taskName,0)>=0&&result.push(key)}),result}"function"==typeof concurrency&&(callback=concurrency,concurrency=null),callback=once(callback||noop);var keys$$1=keys(tasks),numTasks=keys$$1.length;if(!numTasks)return callback(null);concurrency||(concurrency=numTasks);var results={},runningTasks=0,hasError=!1,listeners=Object.create(null),readyTasks=[],readyToCheck=[],uncheckedDependencies={};baseForOwn(tasks,function(task,key){if(!isArray(task))return enqueueTask(key,[task]),void readyToCheck.push(key);var dependencies=task.slice(0,task.length-1),remainingDependencies=dependencies.length;return 0===remainingDependencies?(enqueueTask(key,task),void readyToCheck.push(key)):(uncheckedDependencies[key]=remainingDependencies,void arrayEach(dependencies,function(dependencyName){if(!tasks[dependencyName])throw new Error("async.auto task `"+key+"` has a non-existent dependency `"+dependencyName+"` in "+dependencies.join(", "));addListener(dependencyName,function(){remainingDependencies--,0===remainingDependencies&&enqueueTask(key,task)})}))}),checkForDeadlocks(),processQueue()},symbolTag="[object Symbol]",INFINITY=1/0,symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),rsAstralRange$1="\\ud800-\\udfff",rsComboMarksRange$1="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange$1="\\u20d0-\\u20f0",rsVarRange$1="\\ufe0e\\ufe0f",rsAstral="["+rsAstralRange$1+"]",rsCombo="["+rsComboMarksRange$1+rsComboSymbolsRange$1+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange$1+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsZWJ$1="\\u200d",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange$1+"]?",rsOptJoin="(?:"+rsZWJ$1+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reTrim=/^\s+|\s+$/g,FN_ARGS=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,FN_ARG_SPLIT=/,/,FN_ARG=/(=.+)?(\s*)$/,STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,hasSetImmediate="function"==typeof setImmediate&&setImmediate,hasNextTick="object"==typeof process&&"function"==typeof process.nextTick,_defer;_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback;var setImmediate$1=wrap(_defer);DLL.prototype.removeLink=function(node){return node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev,node.prev=node.next=null,this.length-=1,node},DLL.prototype.empty=DLL,DLL.prototype.insertAfter=function(node,newNode){newNode.prev=node,newNode.next=node.next,node.next?node.next.prev=newNode:this.tail=newNode,node.next=newNode,this.length+=1},DLL.prototype.insertBefore=function(node,newNode){newNode.prev=node.prev,newNode.next=node,node.prev?node.prev.next=newNode:this.head=newNode,node.prev=newNode,this.length+=1},DLL.prototype.unshift=function(node){this.head?this.insertBefore(this.head,node):setInitial(this,node)},DLL.prototype.push=function(node){this.tail?this.insertAfter(this.tail,node):setInitial(this,node)},DLL.prototype.shift=function(){return this.head&&this.removeLink(this.head)},DLL.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)};var eachOfSeries=doLimit(eachOfLimit,1),seq$1=rest(function(functions){var _functions=arrayMap(functions,wrapAsync$1);return rest(function(args){var that=this,cb=args[args.length-1];"function"==typeof cb?args.pop():cb=noop,reduce(_functions,args,function(newargs,fn,cb){fn.apply(that,newargs.concat(rest(function(err,nextargs){cb(err,nextargs)})))},function(err,results){cb.apply(that,[err].concat(results))})})}),compose=rest(function(args){return seq$1.apply(null,args.reverse())}),concat=doParallel(concat$1),concatSeries=doSeries(concat$1),constant=rest(function(values){var args=[null].concat(values);return initialParams(function(ignoredArgs,callback){return callback.apply(this,args)})}),detect=doParallel(_createTester(identity,_findGetResult)),detectLimit=doParallelLimit(_createTester(identity,_findGetResult)),detectSeries=doLimit(detectLimit,1),dir=consoleFunc("dir"),eachSeries=doLimit(eachLimit$1,1),every=doParallel(_createTester(notId,notId)),everyLimit=doParallelLimit(_createTester(notId,notId)),everySeries=doLimit(everyLimit,1),filter=doParallel(_filter),filterLimit=doParallelLimit(_filter),filterSeries=doLimit(filterLimit,1),groupByLimit=function(coll,limit,iteratee,callback){callback=callback||noop;var _iteratee=wrapAsync$1(iteratee);mapLimit(coll,limit,function(val,callback){_iteratee(val,function(err,key){return err?callback(err):callback(null,{key:key,val:val})})},function(err,mapResults){for(var result={},hasOwnProperty=Object.prototype.hasOwnProperty,i=0;i=nextNode.priority;)nextNode=nextNode.next;for(var i=0,l=data.length;l>i;i++){var item={data:data[i],priority:priority,callback:callback};nextNode?q._tasks.insertBefore(nextNode,item):q._tasks.push(item)}setImmediate$1(q.process)},delete q.unshift,q},slice=Array.prototype.slice,reject=doParallel(reject$1),rejectLimit=doParallelLimit(reject$1),rejectSeries=doLimit(rejectLimit,1),retryable=function(opts,task){task||(task=opts,opts=null);var _task=wrapAsync$1(task);return initialParams(function(args,callback){function taskFn(cb){_task.apply(null,args.concat(cb))}opts?retry(opts,taskFn,callback):retry(taskFn,callback)})},some=doParallel(_createTester(Boolean,identity)),someLimit=doParallelLimit(_createTester(Boolean,identity)),someSeries=doLimit(someLimit,1),nativeCeil=Math.ceil,nativeMax$1=Math.max,times=doLimit(timeLimit,1/0),timesSeries=doLimit(timeLimit,1),waterfall=function(tasks,callback){function nextTask(args){if(taskIndex===tasks.length)return callback.apply(null,[null].concat(args));var taskCallback=onlyOnce(rest(function(err,args){return err?callback.apply(null,[err].concat(args)):void nextTask(args)}));args.push(taskCallback);var task=wrapAsync$1(tasks[taskIndex++]);task.apply(null,args)}if(callback=once(callback||noop),!isArray(tasks))return callback(new Error("First argument to waterfall must be an array of functions"));if(!tasks.length)return callback();var taskIndex=0;nextTask([])},index={applyEach:applyEach,applyEachSeries:applyEachSeries,apply:apply$2,asyncify:asyncify,auto:auto,autoInject:autoInject,cargo:cargo,compose:compose,concat:concat,concatSeries:concatSeries,constant:constant,detect:detect,detectLimit:detectLimit,detectSeries:detectSeries,dir:dir,doDuring:doDuring,doUntil:doUntil,doWhilst:doWhilst,during:during,each:eachLimit,eachLimit:eachLimit$1,eachOf:eachOf,eachOfLimit:eachOfLimit,eachOfSeries:eachOfSeries,eachSeries:eachSeries,ensureAsync:ensureAsync,every:every,everyLimit:everyLimit,everySeries:everySeries,filter:filter,filterLimit:filterLimit,filterSeries:filterSeries,forever:forever,groupBy:groupBy,groupByLimit:groupByLimit,groupBySeries:groupBySeries,log:log,map:map,mapLimit:mapLimit,mapSeries:mapSeries,mapValues:mapValues,mapValuesLimit:mapValuesLimit,mapValuesSeries:mapValuesSeries,memoize:memoize,nextTick:nextTick,parallel:parallelLimit,parallelLimit:parallelLimit$1,priorityQueue:priorityQueue,queue:queue$1,race:race,reduce:reduce,reduceRight:reduceRight,reflect:reflect,reflectAll:reflectAll,reject:reject,rejectLimit:rejectLimit,rejectSeries:rejectSeries,retry:retry,retryable:retryable,seq:seq$1,series:series,setImmediate:setImmediate$1,some:some,someLimit:someLimit,someSeries:someSeries,sortBy:sortBy,timeout:timeout,times:times,timesLimit:timeLimit,timesSeries:timesSeries,transform:transform,unmemoize:unmemoize,until:until,waterfall:waterfall,whilst:whilst,all:every,any:some,forEach:eachLimit,forEachSeries:eachSeries,forEachLimit:eachLimit$1,forEachOf:eachOf,forEachOfSeries:eachOfSeries,forEachOfLimit:eachOfLimit,inject:reduce,foldl:reduce,foldr:reduceRight,select:filter,selectLimit:filterLimit,selectSeries:filterSeries,wrapSync:asyncify};exports["default"]=index,exports.applyEach=applyEach,exports.applyEachSeries=applyEachSeries,exports.apply=apply$2,exports.asyncify=asyncify,exports.auto=auto,exports.autoInject=autoInject,exports.cargo=cargo,exports.compose=compose,exports.concat=concat,exports.concatSeries=concatSeries,exports.constant=constant,exports.detect=detect,exports.detectLimit=detectLimit,exports.detectSeries=detectSeries,exports.dir=dir,exports.doDuring=doDuring,exports.doUntil=doUntil,exports.doWhilst=doWhilst,exports.during=during,exports.each=eachLimit,exports.eachLimit=eachLimit$1,exports.eachOf=eachOf,exports.eachOfLimit=eachOfLimit,exports.eachOfSeries=eachOfSeries,exports.eachSeries=eachSeries,exports.ensureAsync=ensureAsync,exports.every=every,exports.everyLimit=everyLimit,exports.everySeries=everySeries,exports.filter=filter,exports.filterLimit=filterLimit,exports.filterSeries=filterSeries,exports.forever=forever,exports.groupBy=groupBy,exports.groupByLimit=groupByLimit,exports.groupBySeries=groupBySeries,exports.log=log,exports.map=map,exports.mapLimit=mapLimit,exports.mapSeries=mapSeries,exports.mapValues=mapValues,exports.mapValuesLimit=mapValuesLimit,exports.mapValuesSeries=mapValuesSeries,exports.memoize=memoize,exports.nextTick=nextTick,exports.parallel=parallelLimit,exports.parallelLimit=parallelLimit$1,exports.priorityQueue=priorityQueue,exports.queue=queue$1,exports.race=race,exports.reduce=reduce,exports.reduceRight=reduceRight,exports.reflect=reflect,exports.reflectAll=reflectAll,exports.reject=reject,exports.rejectLimit=rejectLimit,exports.rejectSeries=rejectSeries,exports.retry=retry,exports.retryable=retryable,exports.seq=seq$1,exports.series=series,exports.setImmediate=setImmediate$1,exports.some=some,exports.someLimit=someLimit,exports.someSeries=someSeries,exports.sortBy=sortBy,exports.timeout=timeout,exports.times=times,exports.timesLimit=timeLimit,exports.timesSeries=timesSeries,exports.transform=transform,exports.unmemoize=unmemoize,exports.until=until,exports.waterfall=waterfall,exports.whilst=whilst,exports.all=every,exports.allLimit=everyLimit,exports.allSeries=everySeries,exports.any=some,exports.anyLimit=someLimit,exports.anySeries=someSeries,exports.find=detect,exports.findLimit=detectLimit,exports.findSeries=detectSeries,exports.forEach=eachLimit,exports.forEachSeries=eachSeries,exports.forEachLimit=eachLimit$1,exports.forEachOf=eachOf,exports.forEachOfSeries=eachOfSeries,exports.forEachOfLimit=eachOfLimit,exports.inject=reduce,exports.foldl=reduce,exports.foldr=reduceRight,exports.select=filter,exports.selectLimit=filterLimit,exports.selectSeries=filterSeries,exports.wrapSync=asyncify,Object.defineProperty(exports,"__esModule",{value:!0})})}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:85}],5:[function(require,module,exports){"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;l>i;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&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;end>i;i+=3)tmp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2],output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,output="",parts=[],maxChunkLength=16383,i=0,len2=len-extraBytes;len2>i;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?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;len>i;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63},{}],6:[function(){},{}],7:[function(require,module,exports){arguments[4][6][0].apply(exports,arguments)},{dup:6}],8:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer"),Buffer=buffer.Buffer,SlowBuffer=buffer.SlowBuffer,MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function(size,fill,encoding){if("function"==typeof Buffer.alloc)return Buffer.alloc(size,fill,encoding);if("number"==typeof encoding)throw new TypeError("encoding must not be number");if("number"!=typeof size)throw new TypeError("size must be a number");if(size>MAX_LEN)throw new RangeError("size is too large");var enc=encoding,_fill=fill;void 0===_fill&&(enc=void 0,_fill=0);var buf=new Buffer(size);if("string"==typeof _fill)for(var fillBuf=new Buffer(_fill,enc),flen=fillBuf.length,i=-1;++iMAX_LEN)throw new RangeError("size is too large");return new Buffer(size)},exports.from=function(value,encodingOrOffset,length){if("function"==typeof Buffer.from&&(!global.Uint8Array||Uint8Array.from!==Buffer.from))return Buffer.from(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError('"value" argument must not be a number');if("string"==typeof value)return new Buffer(value,encodingOrOffset);if("undefined"!=typeof ArrayBuffer&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(1===arguments.length)return new Buffer(value);"undefined"==typeof offset&&(offset=0);var len=length;if("undefined"==typeof len&&(len=value.byteLength-offset),offset>=value.byteLength)throw new RangeError("'offset' is out of bounds");if(len>value.byteLength-offset)throw new RangeError("'length' is out of bounds");return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);return value.copy(out,0,0,value.length),out}if(value){if(Array.isArray(value)||"undefined"!=typeof ArrayBuffer&&value.buffer instanceof ArrayBuffer||"length"in value)return new Buffer(value);if("Buffer"===value.type&&Array.isArray(value.data))return new Buffer(value.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},exports.allocUnsafeSlow=function(size){if("function"==typeof Buffer.allocUnsafeSlow)return Buffer.allocUnsafeSlow(size);if("number"!=typeof size)throw new TypeError("size must be a number");if(size>=MAX_LEN)throw new RangeError("size is too large");return new SlowBuffer(size)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{buffer:9}],9:[function(require,module,exports){(function(global){"use strict";function typedArraySupport(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()size)throw new RangeError('"size" argument must not be negative')}function alloc(that,size,fill,encoding){return assertSize(size),0>=size?createBuffer(that,size):void 0!==fill?"string"==typeof encoding?createBuffer(that,size).fill(fill,encoding):createBuffer(that,size).fill(fill):createBuffer(that,size)}function allocUnsafe(that,size){if(assertSize(size),that=createBuffer(that,0>size?0:0|checked(size)),!Buffer.TYPED_ARRAY_SUPPORT)for(var i=0;size>i;++i)that[i]=0;return that}function fromString(that,string,encoding){if(("string"!=typeof encoding||""===encoding)&&(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError('"encoding" must be a valid string encoding');var length=0|byteLength(string,encoding);that=createBuffer(that,length);var actual=that.write(string,encoding);return actual!==length&&(that=that.slice(0,actual)),that}function fromArrayLike(that,array){var length=array.length<0?0:0|checked(array.length);that=createBuffer(that,length);for(var i=0;length>i;i+=1)that[i]=255&array[i];return that}function fromArrayBuffer(that,array,byteOffset,length){if(array.byteLength,0>byteOffset||array.byteLength=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||0>start)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),0>=end)return"";if(end>>>=0,start>>>=0,start>=end)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:-2147483648>byteOffset&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),0>byteOffset&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(0>byteOffset){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&val,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;arrLength>i;i++)if(read(arr,i)===read(val,-1===foundIndex?0:i-foundIndex)){if(-1===foundIndex&&(foundIndex=i),i-foundIndex+1===valLength)return foundIndex*indexSize}else-1!==foundIndex&&(i-=i-foundIndex),foundIndex=-1}else for(byteOffset+valLength>arrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;valLength>j;j++)if(read(arr,i+j)!==read(val,j)){found=!1;break}if(found)return i}return-1}function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;length?(length=Number(length),length>remaining&&(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;length>i;++i){var parsed=parseInt(string.substr(2*i,2),16);if(isNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}function base64Slice(buf,start,end){return base64.fromByteArray(0===start&&end===buf.length?buf:buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);for(var res=[],i=start;end>i;){var firstByte=buf[i],codePoint=null,bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(end>=i+bytesPerSequence){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:128>firstByte&&(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&&(55296>tempCodePoint||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&&1114112>tempCodePoint&&(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(MAX_ARGUMENTS_LENGTH>=len)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;len>i;)res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH));return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;end>i;++i)ret+=String.fromCharCode(127&buf[i]);return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;end>i;++i)ret+=String.fromCharCode(buf[i]);return ret}function hexSlice(buf,start,end){var len=buf.length;(!start||0>start)&&(start=0),(!end||0>end||end>len)&&(end=len);for(var out="",i=start;end>i;++i)out+=toHex(buf[i]);return out}function utf16leSlice(buf,start,end){for(var bytes=buf.slice(start,end),res="",i=0;ioffset)throw new RangeError("offset is not uint");if(offset+ext>length)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||min>value)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){0>value&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);j>i;++i)buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){0>value&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);j>i;++i)buf[offset+i]=value>>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(0>offset)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 16>n?"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;length>i;++i){if(codePoint=string.charCodeAt(i),codePoint>55295&&57344>codePoint){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(56320>codePoint){(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,128>codePoint){if((units-=1)<0)break;bytes.push(codePoint)}else if(2048>codePoint){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(65536>codePoint){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(1114112>codePoint))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;length>i&&!(i+offset>=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");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);len>i;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return y>x?-1:x>y?1:0},Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Buffer.concat=function(list,length){if(!isArray(list))throw new TypeError('"list" argument must be an Array of Buffers');if(0===list.length)return Buffer.alloc(0);var i;if(void 0===length)for(length=0,i=0;ii;i+=2)swap(this,i,i+1);return this},Buffer.prototype.swap32=function(){var len=this.length;if(len%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var i=0;len>i;i+=4)swap(this,i,i+3),swap(this,i+1,i+2);return this},Buffer.prototype.swap64=function(){var len=this.length;if(len%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var i=0;len>i;i+=8)swap(this,i,i+7),swap(this,i+1,i+6),swap(this,i+2,i+5),swap(this,i+3,i+4);return this},Buffer.prototype.toString=function(){var length=0|this.length;return 0===length?"":0===arguments.length?utf8Slice(this,0,length):slowToString.apply(this,arguments)},Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return this===b?!0:0===Buffer.compare(this,b)},Buffer.prototype.inspect=function(){var str="",max=exports.INSPECT_MAX_BYTES;return this.length>0&&(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),0>start||end>target.length||0>thisStart||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;len>i;++i)if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i],y=targetCopy[i];break}return y>x?-1:x>y?1:0},Buffer.prototype.includes=function(val,byteOffset,encoding){return-1!==this.indexOf(val,byteOffset,encoding)},Buffer.prototype.indexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!0)},Buffer.prototype.lastIndexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!1)},Buffer.prototype.write=function(string,offset,length,encoding){if(void 0===offset)encoding="utf8",length=this.length,offset=0;else if(void 0===length&&"string"==typeof offset)encoding=offset,length=this.length,offset=0;else{if(!isFinite(offset))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");offset=0|offset,isFinite(length)?(length=0|length,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0)}var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),string.length>0&&(0>length||0>offset)||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,0>start?(start+=len,0>start&&(start=0)):start>len&&(start=len),0>end?(end+=len,0>end&&(end=0)):end>len&&(end=len),start>end&&(end=start);var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT)newBuf=this.subarray(start,end),newBuf.__proto__=Buffer.prototype;else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,void 0);for(var i=0;sliceLen>i;++i)newBuf[i]=this[i+start]}return newBuf},Buffer.prototype.readUIntLE=function(offset,byteLength,noAssert){offset=0|offset,byteLength=0|byteLength,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i0&&(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|offset,byteLength=0|byteLength,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|offset,byteLength=0|byteLength,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]?-1*(255-this[offset]+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|offset,byteLength=0|byteLength,!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,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|offset,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|offset,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|offset,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|offset,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|offset,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|offset,!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;++ivalue&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset=0|offset,!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);)0>value&&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|offset,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),0>value&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset=0|offset,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|offset,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|offset,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|offset,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),0>value&&(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&&start>end&&(end=start),end===start)return 0;if(0===target.length||0===this.length)return 0;if(0>targetStart)throw new RangeError("targetStart out of bounds");if(0>start||start>=this.length)throw new RangeError("sourceStart out of bounds");if(0>end)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStartstart&&end>targetStart)for(i=len-1;i>=0;--i)target[i+targetStart]=this[i+start];else if(1e3>len||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;len>i;++i)target[i+targetStart]=this[i+start];else Uint8Array.prototype.set.call(target,this.subarray(start,start+len),targetStart);return len},Buffer.prototype.fill=function(val,start,end,encoding){if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=this.length):"string"==typeof end&&(encoding=end,end=this.length),1===val.length){var code=val.charCodeAt(0);256>code&&(val=code)}if(void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding)}else"number"==typeof val&&(val=255&val);if(0>start||this.length=end)return this;start>>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;end>i;++i)this[i]=val;else{var bytes=Buffer.isBuffer(val)?val:utf8ToBytes(new Buffer(val,encoding).toString()),len=bytes.length;for(i=0;end-start>i;++i)this[i+start]=bytes[i%len]}return this};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":5,ieee754:40,isarray:44}],10:[function(require,module){(function(Buffer,process){function objCopy(obj){if(null==obj)return obj;if(Array.isArray(obj))return obj.slice();if("object"==typeof obj){var copy={};return Object.keys(obj).forEach(function(k){copy[k]=obj[k]}),copy}return obj}function getCaller3Info(){if(void 0!==this){var obj={},saveLimit=Error.stackTraceLimit,savePrepare=Error.prepareStackTrace;return Error.stackTraceLimit=3,Error.prepareStackTrace=function(_,stack){var caller=stack[2];sourceMapSupport&&(caller=sourceMapSupport.wrapCallSite(caller)),obj.file=caller.getFileName(),obj.line=caller.getLineNumber();var func=caller.getFunctionName();func&&(obj.func=func)},Error.captureStackTrace(this,getCaller3Info),this.stack,Error.stackTraceLimit=saveLimit,Error.prepareStackTrace=savePrepare,obj}}function _indent(s,indent){indent||(indent=" ");var lines=s.split(/\r?\n/g);return indent+lines.join("\n"+indent)}function _warn(msg,dedupKey){if(assert.ok(msg),dedupKey){if(_warned[dedupKey])return;_warned[dedupKey]=!0}process.stderr.write(msg+"\n")}function _haveWarned(dedupKey){return _warned[dedupKey]}function ConsoleRawStream(){}function resolveLevel(nameOrNum){var level,type=typeof nameOrNum;if("string"===type){if(level=levelFromName[nameOrNum.toLowerCase()],!level)throw new Error(format('unknown level name: "%s"',nameOrNum))}else{if("number"!==type)throw new TypeError(format("cannot resolve level: invalid arg (%s):",type,nameOrNum));if(0>nameOrNum||Math.floor(nameOrNum)!==nameOrNum)throw new TypeError(format("level is not a positive integer: %s",nameOrNum));level=nameOrNum}return level}function isWritable(obj){return obj instanceof stream.Writable?!0:"function"==typeof obj.write}function Logger(options,_childOptions,_childSimple){if(xxx("Logger start:",options),!(this instanceof Logger))return new Logger(options,_childOptions);var parent;if(void 0!==_childOptions&&(parent=options,options=_childOptions,!(parent instanceof Logger)))throw new TypeError("invalid Logger creation: do not pass a second arg");if(!options)throw new TypeError("options (object) is required");if(parent){if(options.name)throw new TypeError("invalid options.name: child cannot set logger name")}else if(!options.name)throw new TypeError("options.name (string) is required");if(options.stream&&options.streams)throw new TypeError('cannot mix "streams" and "stream" options');if(options.streams&&!Array.isArray(options.streams))throw new TypeError("invalid options.streams: must be an array");if(options.serializers&&("object"!=typeof options.serializers||Array.isArray(options.serializers)))throw new TypeError("invalid options.serializers: must be an object");if(EventEmitter.call(this),parent&&_childSimple){this._isSimpleChild=!0,this._level=parent._level,this.streams=parent.streams,this.serializers=parent.serializers,this.src=parent.src;for(var fields=this.fields={},parentFieldNames=Object.keys(parent.fields),i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":return fastAndSafeJsonStringify(args[i++]);case"%%":return"%";default:return x}}),x=args[i];len>i;x=args[++i])str+=null===x||"object"!=typeof x?" "+x:" "+inspect(x);return str}}var _warned={};ConsoleRawStream.prototype.write=function(rec){rec.leveli;i++)this.streams[i].level=newLevel;this._level=newLevel},Logger.prototype.levels=function(name,value){if(void 0===name)return assert.equal(value,void 0),this.streams.map(function(s){return s.level});var stream;if("number"==typeof name){if(stream=this.streams[name],void 0===stream)throw new Error("invalid stream index: "+name)}else{for(var len=this.streams.length,i=0;len>i;i++){var s=this.streams[i];if(s.name===name){stream=s;break}}if(!stream)throw new Error(format('no stream with name "%s"',name))}if(void 0===value)return stream.level;var newLevel=resolveLevel(value);stream.level=newLevel,newLevel=0,format('rotating-file stream "count" is not >= 0: %j in %j',this.count,this)),options.period){var period={hourly:"1h",daily:"1d",weekly:"1w",monthly:"1m",yearly:"1y"}[options.period]||options.period,m=/^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);if(!m)throw new Error(format('invalid period: "%s"',options.period));this.periodNum=Number(m[1]),this.periodScope=m[2]}else this.periodNum=1,this.periodScope="d";var lastModified=null;try{var fileInfo=fs.statSync(this.path);lastModified=fileInfo.mtime.getTime()}catch(err){}var rotateAfterOpen=!1;if(lastModified){var lastRotTime=this._calcRotTime(0);lastRotTime>lastModified&&(rotateAfterOpen=!0)}this.stream=fs.createWriteStream(this.path,{flags:"a",encoding:"utf8"}),this.rotQueue=[],this.rotating=!1,rotateAfterOpen?(this._debug("rotateAfterOpen -> call rotate()"),this.rotate()):this._setupNextRot()},util.inherits(RotatingFileStream,EventEmitter),RotatingFileStream.prototype._debug=function(){return!1},RotatingFileStream.prototype._setupNextRot=function(){this.rotAt=this._calcRotTime(1),this._setRotationTimer()},RotatingFileStream.prototype._setRotationTimer=function(){var self=this,delay=this.rotAt-Date.now(),TIMEOUT_MAX=2147483647;delay>TIMEOUT_MAX&&(delay=TIMEOUT_MAX),this.timeout=setTimeout(function(){self._debug("_setRotationTimer timeout -> call rotate()"),self.rotate()},delay),"function"==typeof this.timeout.unref&&this.timeout.unref()},RotatingFileStream.prototype._calcRotTime=function(periodOffset){this._debug("_calcRotTime: %s%s",this.periodNum,this.periodScope);var d=new Date;this._debug(" now local: %s",d),this._debug(" now utc: %s",d.toISOString());var rotAt;switch(this.periodScope){case"ms":rotAt=this.rotAt?this.rotAt+this.periodNum*periodOffset:Date.now()+this.periodNum*periodOffset;break;case"h":rotAt=this.rotAt?this.rotAt+60*this.periodNum*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours()+periodOffset);break;case"d":rotAt=this.rotAt?this.rotAt+24*this.periodNum*60*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+periodOffset);break;case"w":if(this.rotAt)rotAt=this.rotAt+7*this.periodNum*24*60*60*1e3*periodOffset;else{var dayOffset=7-d.getUTCDay();1>periodOffset&&(dayOffset=-d.getUTCDay()),(periodOffset>1||-1>periodOffset)&&(dayOffset+=7*periodOffset),rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+dayOffset)}break;case"m":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+this.periodNum*periodOffset,1):Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+periodOffset,1);break;case"y":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear()+this.periodNum*periodOffset,0,1):Date.UTC(d.getUTCFullYear()+periodOffset,0,1);break;default:assert.fail(format('invalid period scope: "%s"',this.periodScope))}if(this._debug()){this._debug(" **rotAt**: %s (utc: %s)",rotAt,new Date(rotAt).toUTCString());var now=Date.now();this._debug(" now: %s (%sms == %smin == %sh to go)",now,rotAt-now,(rotAt-now)/1e3/60,(rotAt-now)/1e3/60/60)}return rotAt},RotatingFileStream.prototype.rotate=function(){function del(){var toDel=self.path+"."+String(n-1);0===n&&(toDel=self.path),n-=1,self._debug(" rm %s",toDel),fs.unlink(toDel,function(){moves()})}function moves(){if(0===self.count||0>n)return finish();var before=self.path,after=self.path+"."+String(n);n>0&&(before+="."+String(n-1)),n-=1,fs.exists(before,function(exists){exists?(self._debug(" mv %s %s",before,after),mv(before,after,function(mvErr){mvErr?(self.emit("error",mvErr),finish()):moves()})):moves()})}function finish(){self._debug(" open %s",self.path),self.stream=fs.createWriteStream(self.path,{flags:"a",encoding:"utf8"});for(var q=self.rotQueue,len=q.length,i=0;len>i;i++)self.stream.write(q[i]);self.rotQueue=[],self.rotating=!1,self.emit("drain"),self._setupNextRot()}var self=this;if(self.rotAt&&self.rotAt>Date.now())return self._setRotationTimer();if(this._debug("rotate"),self.rotating)throw new TypeError("cannot start a rotation when already rotating");self.rotating=!0,self.stream.end();var n=this.count;del()},RotatingFileStream.prototype.write=function(s){return this.rotating?(this.rotQueue.push(s),!1):this.stream.write(s)},RotatingFileStream.prototype.end=function(){this.stream.end()},RotatingFileStream.prototype.destroy=function(){this.stream.destroy()},RotatingFileStream.prototype.destroySoon=function(){this.stream.destroySoon()}),util.inherits(RingBuffer,EventEmitter),RingBuffer.prototype.write=function(record){if(!this.writable)throw new Error("RingBuffer has been ended already");return this.records.push(record),this.records.length>this.limit&&this.records.shift(),!0},RingBuffer.prototype.end=function(){arguments.length>0&&this.write.apply(this,Array.prototype.slice.call(arguments)),this.writable=!1},RingBuffer.prototype.destroy=function(){this.writable=!1,this.emit("close")},RingBuffer.prototype.destroySoon=function(){this.destroy()},module.exports=Logger,module.exports.TRACE=TRACE,module.exports.DEBUG=DEBUG,module.exports.INFO=INFO,module.exports.WARN=WARN,module.exports.ERROR=ERROR,module.exports.FATAL=FATAL,module.exports.resolveLevel=resolveLevel,module.exports.levelFromName=levelFromName,module.exports.nameFromLevel=nameFromLevel,module.exports.VERSION=VERSION,module.exports.LOG_VERSION=LOG_VERSION,module.exports.createLogger=function(options){return new Logger(options)},module.exports.RingBuffer=RingBuffer,module.exports.RotatingFileStream=RotatingFileStream,module.exports.safeCycles=safeCycles}).call(this,{isBuffer:require("../../is-buffer/index.js")},require("_process"))},{"../../is-buffer/index.js":43,_process:85,assert:3,events:38,fs:7,os:83,"safe-json-stringify":100,stream:122,util:131}],11:[function(require,module,exports){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}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"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)}function isError(e){return"[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||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":43}],12:[function(require,module){function DeferredIterator(options){AbstractIterator.call(this,options),this._options=options,this._iterator=null,this._operations=[]}var util=require("util"),AbstractIterator=require("abstract-leveldown").AbstractIterator;util.inherits(DeferredIterator,AbstractIterator),DeferredIterator.prototype.setDb=function(db){var it=this._iterator=db.iterator(this._options);this._operations.forEach(function(op){it[op.method].apply(it,op.args)})},DeferredIterator.prototype._operation=function(method,args){return this._iterator?this._iterator[method].apply(this._iterator,args):void this._operations.push({method:method,args:args})},"next end".split(" ").forEach(function(m){DeferredIterator.prototype["_"+m]=function(){this._operation(m,arguments)}}),module.exports=DeferredIterator},{"abstract-leveldown":17,util:131}],13:[function(require,module){(function(Buffer,process){function DeferredLevelDOWN(location){AbstractLevelDOWN.call(this,"string"==typeof location?location:""),this._db=void 0,this._operations=[],this._iterators=[]}var util=require("util"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,DeferredIterator=require("./deferred-iterator");util.inherits(DeferredLevelDOWN,AbstractLevelDOWN),DeferredLevelDOWN.prototype.setDb=function(db){this._db=db,this._operations.forEach(function(op){db[op.method].apply(db,op.args)}),this._iterators.forEach(function(it){it.setDb(db)})},DeferredLevelDOWN.prototype._open=function(options,callback){return process.nextTick(callback)},DeferredLevelDOWN.prototype._operation=function(method,args){return this._db?this._db[method].apply(this._db,args):void this._operations.push({method:method,args:args})},"put get del batch approximateSize".split(" ").forEach(function(m){DeferredLevelDOWN.prototype["_"+m]=function(){this._operation(m,arguments)}}),DeferredLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},DeferredLevelDOWN.prototype._iterator=function(options){if(this._db)return this._db.iterator.apply(this._db,arguments);var it=new DeferredIterator(options);return this._iterators.push(it),it},module.exports=DeferredLevelDOWN,module.exports.DeferredIterator=DeferredIterator}).call(this,{isBuffer:require("../is-buffer/index.js")},require("_process"))},{"../is-buffer/index.js":43,"./deferred-iterator":12,_process:85,"abstract-leveldown":17,util:131}],14:[function(require,module){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:85}],15:[function(require,module){(function(process){function AbstractIterator(db){this.db=db,this._ended=!1,this._nexting=!1}AbstractIterator.prototype.next=function(callback){var self=this;if("function"!=typeof callback)throw new Error("next() requires a callback argument");return self._ended?callback(new Error("cannot call next() after end()")):self._nexting?callback(new Error("cannot call next() before previous next() has completed")):(self._nexting=!0,"function"==typeof self._next?self._next(function(){self._nexting=!1,callback.apply(null,arguments)}):void process.nextTick(function(){self._nexting=!1,callback()}))},AbstractIterator.prototype.end=function(callback){if("function"!=typeof callback)throw new Error("end() requires a callback argument");return this._ended?callback(new Error("end() already called on iterator")):(this._ended=!0,"function"==typeof this._end?this._end(callback):void process.nextTick(callback))},module.exports=AbstractIterator}).call(this,require("_process"))},{_process:85}],16:[function(require,module){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location,this.status="new"}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){var self=this,oldStatus=this.status;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");"object"!=typeof options&&(options={}),options.createIfMissing=0!=options.createIfMissing,options.errorIfExists=!!options.errorIfExists,"function"==typeof this._open?(this.status="opening",this._open(options,function(err){return err?(self.status=oldStatus,callback(err)):(self.status="open",void callback())})):(this.status="open",process.nextTick(callback))},AbstractLevelDOWN.prototype.close=function(callback){var self=this,oldStatus=this.status;if("function"!=typeof callback)throw new Error("close() requires a callback argument");"function"==typeof this._close?(this.status="closing",this._close(function(err){return err?(self.status=oldStatus,callback(err)):(self.status="closed",void callback())})):(this.status="closed",process.nextTick(callback))},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),options.asBuffer=0!=options.asBuffer,"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),null==value||this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"==typeof array&&(callback=array),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));options&&"object"==typeof options||(options={});for(var e,err,i=0,l=array.length;l>i;i++)if(e=array[i],"object"==typeof e){if(err=this._checkKey(e.type,"type",this._isBuffer))return callback(err);if(err=this._checkKey(e.key,"key",this._isBuffer))return callback(err)}return"function"==typeof this._batch?this._batch(array,options,callback):void process.nextTick(callback)},AbstractLevelDOWN.prototype.approximateSize=function(start,end,callback){if(null==start||null==end||"function"==typeof start||"function"==typeof end)throw new Error("approximateSize() requires valid `start`, `end` and `callback` arguments");if("function"!=typeof callback)throw new Error("approximateSize() requires a callback argument");return this._isBuffer(start)||(start=String(start)),this._isBuffer(end)||(end=String(end)),"function"==typeof this._approximateSize?this._approximateSize(start,end,callback):void process.nextTick(function(){callback(null,0)})},AbstractLevelDOWN.prototype._setupIteratorOptions=function(options){var self=this;return options=xtend(options),["start","end","gt","gte","lt","lte"].forEach(function(o){options[o]&&self._isBuffer(options[o])&&0===options[o].length&&delete options[o]}),options.reverse=!!options.reverse,options.keys=0!=options.keys,options.values=0!=options.values,options.limit="limit"in options?options.limit:-1,options.keyAsBuffer=0!=options.keyAsBuffer,options.valueAsBuffer=0!=options.valueAsBuffer,options},AbstractLevelDOWN.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),options=this._setupIteratorOptions(options),"function"==typeof this._iterator?this._iterator(options):new AbstractIterator(this)},AbstractLevelDOWN.prototype._chainedBatch=function(){return new AbstractChainedBatch(this)},AbstractLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},AbstractLevelDOWN.prototype._checkKey=function(obj,type){if(null===obj||void 0===obj)return new Error(type+" cannot be `null` or `undefined`");if(this._isBuffer(obj)){if(0===obj.length)return new Error(type+" cannot be an empty Buffer")}else if(""===String(obj))return new Error(type+" cannot be an empty String")},module.exports=AbstractLevelDOWN}).call(this,{isBuffer:require("../../../is-buffer/index.js")},require("_process"))},{"../../../is-buffer/index.js":43,"./abstract-chained-batch":14,"./abstract-iterator":15,_process:85,xtend:133}],17:[function(require,module,exports){exports.AbstractLevelDOWN=require("./abstract-leveldown"),exports.AbstractIterator=require("./abstract-iterator"),exports.AbstractChainedBatch=require("./abstract-chained-batch"),exports.isLevelDOWN=require("./is-leveldown")},{"./abstract-chained-batch":14,"./abstract-iterator":15,"./abstract-leveldown":16,"./is-leveldown":18}],18:[function(require,module){function isLevelDOWN(db){return db&&"object"==typeof db?Object.keys(AbstractLevelDOWN.prototype).filter(function(name){return"_"!=name[0]&&"approximateSize"!=name}).every(function(name){return"function"==typeof db[name]}):!1}var AbstractLevelDOWN=require("./abstract-leveldown");module.exports=isLevelDOWN},{"./abstract-leveldown":16}],19:[function(require,module,exports){const pumpify=require("pumpify"),stopwords=[],CalculateTermFrequency=exports.CalculateTermFrequency=require("./pipeline/CalculateTermFrequency.js"),CreateCompositeVector=exports.CreateCompositeVector=require("./pipeline/CreateCompositeVector.js"),CreateSortVectors=exports.CreateSortVectors=require("./pipeline/CreateSortVectors.js"),CreateStoredDocument=exports.CreateStoredDocument=require("./pipeline/CreateStoredDocument.js"),FieldedSearch=exports.FieldedSearch=require("./pipeline/FieldedSearch.js"),IngestDoc=exports.IngestDoc=require("./pipeline/IngestDoc.js"),LowCase=exports.LowCase=require("./pipeline/LowCase.js"),NormaliseFields=exports.NormaliseFields=require("./pipeline/NormaliseFields.js"),RemoveStopWords=exports.RemoveStopWords=require("./pipeline/RemoveStopWords.js"),Tokeniser=(exports.Spy=require("./pipeline/Spy.js"),exports.Tokeniser=require("./pipeline/Tokeniser.js"));exports.pipeline=function(options){options=Object.assign({},{separator:/[|' .,\-|(\\\n)]+/,searchable:!0,stopwords:stopwords,nGramLength:1,fieldedSearch:!0},options);var pl=[new IngestDoc(options),new CreateStoredDocument,new NormaliseFields,new LowCase,new Tokeniser,new RemoveStopWords,new CalculateTermFrequency,new CreateCompositeVector,new CreateSortVectors,new FieldedSearch];return pumpify.obj.apply(this,pl)},exports.customPipeline=function(pl){return pumpify.obj.apply(this,pl)}},{"./pipeline/CalculateTermFrequency.js":20,"./pipeline/CreateCompositeVector.js":21,"./pipeline/CreateSortVectors.js":22,"./pipeline/CreateStoredDocument.js":23,"./pipeline/FieldedSearch.js":24,"./pipeline/IngestDoc.js":25,"./pipeline/LowCase.js":26,"./pipeline/NormaliseFields.js":27,"./pipeline/RemoveStopWords.js":28,"./pipeline/Spy.js":29,"./pipeline/Tokeniser.js":30,pumpify:88}],20:[function(require,module){const tv=require("term-vector"),tf=require("term-frequency"),Transform=require("stream").Transform,util=require("util"),objectify=function(result,item){return result[item[0].join(" ")]=item[1],result},CalculateTermFrequency=function(){Transform.call(this,{objectMode:!0})};module.exports=CalculateTermFrequency,util.inherits(CalculateTermFrequency,Transform),CalculateTermFrequency.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},nGramLength:1,searchable:!0,weight:0},doc.options||{});for(var fieldName in doc.tokenised){var fieldOptions=Object.assign({},{nGramLength:options.nGramLength,searchable:options.searchable,weight:options.weight},options.fieldOptions[fieldName]),field=doc.tokenised[fieldName];fieldOptions.searchable&&(doc.vector[fieldName]=tf.getTermFrequency(tv.getVector(field,fieldOptions.nGramLength),{scheme:tf.doubleNormalization0point5,weight:fieldOptions.weight}).reduce(objectify,{}),doc.vector[fieldName]["*"]=1)}return this.push(doc),end()}},{stream:122,"term-frequency":125,"term-vector":126,util:131}],21:[function(require,module){const Transform=require("stream").Transform,util=require("util"),CreateCompositeVector=function(){Transform.call(this,{objectMode:!0})};module.exports=CreateCompositeVector,util.inherits(CreateCompositeVector,Transform),CreateCompositeVector.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},searchable:!0},doc.options||{});doc.vector["*"]={};for(var fieldName in doc.vector){var fieldOptions=Object.assign({},{searchable:options.searchable},options.fieldOptions[fieldName]);if(fieldOptions.searchable){var vec=doc.vector[fieldName];for(var token in vec)doc.vector["*"][token]=doc.vector["*"][token]||vec[token],doc.vector["*"][token]=(doc.vector["*"][token]+vec[token])/2}}return this.push(doc),end()}},{stream:122,util:131}],22:[function(require,module){const tf=require("term-frequency"),tv=require("term-vector"),Transform=require("stream").Transform,util=require("util"),objectify=function(result,item){return result[item[0]]=item[1],result},CreateSortVectors=function(){Transform.call(this,{objectMode:!0})};module.exports=CreateSortVectors,util.inherits(CreateSortVectors,Transform),CreateSortVectors.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},sortable:!1},doc.options||{});for(var fieldName in doc.vector){var fieldOptions=Object.assign({},{sortable:options.sortable},options.fieldOptions[fieldName]);fieldOptions.sortable&&(doc.vector[fieldName]=tf.getTermFrequency(tv.getVector(doc.tokenised[fieldName]),{scheme:tf.selfString}).reduce(objectify,{}))}return this.push(doc),end()}},{stream:122,"term-frequency":125,"term-vector":126,util:131}],23:[function(require,module){const Transform=require("stream").Transform,util=require("util"),CreateStoredDocument=function(){Transform.call(this,{objectMode:!0})};module.exports=CreateStoredDocument,util.inherits(CreateStoredDocument,Transform),CreateStoredDocument.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},storeable:!0},doc.options||{});for(var fieldName in doc.raw){var fieldOptions=Object.assign({},{storeable:options.storeable},options.fieldOptions[fieldName]);"id"===fieldName&&(fieldOptions.storeable=!0),fieldOptions.storeable&&(doc.stored[fieldName]=JSON.parse(JSON.stringify(doc.raw[fieldName])))}return this.push(doc),end()}},{stream:122,util:131}],24:[function(require,module){const Transform=require("stream").Transform,util=require("util"),FieldedSearch=function(){Transform.call(this,{objectMode:!0})};module.exports=FieldedSearch,util.inherits(FieldedSearch,Transform),FieldedSearch.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},fieldedSearch:!0},doc.options||{});for(var fieldName in doc.vector){var fieldOptions=Object.assign({},{fieldedSearch:options.fieldedSearch},options.fieldOptions[fieldName]);fieldOptions.fieldedSearch||"*"===fieldName||delete doc.vector[fieldName]}return options.log&&options.log.info(doc),this.push(doc),end()}},{stream:122,util:131}],25:[function(require,module){const util=require("util"),Transform=require("stream").Transform,IngestDoc=function(options){this.options=options,this.i=0,Transform.call(this,{objectMode:!0})};module.exports=IngestDoc,util.inherits(IngestDoc,Transform),IngestDoc.prototype._transform=function(doc,encoding,end){var that=this,ingestedDoc={ -normalised:{},options:that.options,raw:JSON.parse(JSON.stringify(doc)),stored:{},tokenised:{},vector:{}};return ingestedDoc.id=doc.id?String(doc.id):Date.now()+"-"+ ++this.i,this.push(ingestedDoc),end()}},{stream:122,util:131}],26:[function(require,module){const Transform=require("stream").Transform,util=require("util"),LowCase=function(){Transform.call(this,{objectMode:!0})};module.exports=LowCase,util.inherits(LowCase,Transform),LowCase.prototype._transform=function(doc,encoding,end){var options=this.options=Object.assign({},{fieldOptions:{},preserveCase:!1},doc.options||{});for(var fieldName in doc.normalised)if("id"!==fieldName){var fieldOptions=Object.assign({},{preserveCase:options.preserveCase},options.fieldOptions[fieldName]);fieldOptions.preserveCase||("[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.normalised[fieldName].map(function(token){return token.toLowerCase()}):doc.normalised[fieldName]=doc.normalised[fieldName].toLowerCase())}return this.push(doc),end()}},{stream:122,util:131}],27:[function(require,module){const util=require("util"),Transform=require("stream").Transform,NormaliseFields=function(){Transform.call(this,{objectMode:!0})};module.exports=NormaliseFields,util.inherits(NormaliseFields,Transform),NormaliseFields.prototype._transform=function(doc,encoding,end){for(var fieldName in doc.raw)doc.normalised[fieldName]="[object Array]"===Object.prototype.toString.call(doc.raw[fieldName])?doc.raw[fieldName].map(function(item){return JSON.stringify(item).split(/[[\],{}:"]+/).join(" ").trim()}):"[object String]"!==Object.prototype.toString.call(doc.raw[fieldName])?JSON.stringify(doc.raw[fieldName]).split(/[[\],{}:"]+/).join(" ").trim():doc.raw[fieldName].trim();return this.push(doc),end()}},{stream:122,util:131}],28:[function(require,module){const Transform=require("stream").Transform,util=require("util"),RemoveStopWords=function(){Transform.call(this,{objectMode:!0})};module.exports=RemoveStopWords,util.inherits(RemoveStopWords,Transform),RemoveStopWords.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},stopwords:[]},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{stopwords:options.stopwords},options.fieldOptions[fieldName]);doc.tokenised[fieldName]=doc.tokenised[fieldName].filter(function(item){return-1===fieldOptions.stopwords.indexOf(item)}).filter(function(i){return i})}return this.push(doc),end()}},{stream:122,util:131}],29:[function(require,module){const Transform=require("stream").Transform,util=require("util"),Spy=function(){Transform.call(this,{objectMode:!0})};module.exports=Spy,util.inherits(Spy,Transform),Spy.prototype._transform=function(doc,encoding,end){return console.log(JSON.stringify(doc,null,2)),this.push(doc),end()}},{stream:122,util:131}],30:[function(require,module){const Transform=require("stream").Transform,util=require("util"),Tokeniser=function(){Transform.call(this,{objectMode:!0})};module.exports=Tokeniser,util.inherits(Tokeniser,Transform),Tokeniser.prototype._transform=function(doc,encoding,end){var options=this.options=Object.assign({},{fieldOptions:{},separator:/\\n|[|' ><.,\-|]+|\\u0003/},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{separator:options.separator},options.fieldOptions[fieldName]);doc.tokenised[fieldName]="[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.normalised[fieldName]:doc.normalised[fieldName].split(fieldOptions.separator)}return this.push(doc),end()}},{stream:122,util:131}],31:[function(require,module){(function(process,Buffer){var stream=require("readable-stream"),eos=require("end-of-stream"),inherits=require("inherits"),shift=require("stream-shift"),SIGNAL_FLUSH=new Buffer([0]),onuncork=function(self,fn){self._corked?self.once("uncork",fn):fn()},destroyer=function(self,end){return function(err){err?self.destroy("premature close"===err.message?null:err):end&&!self._ended&&self.end()}},end=function(ws,fn){return ws?ws._writableState&&ws._writableState.finished?fn():ws._writableState?ws.end(fn):(ws.end(),void fn()):fn()},toStreams2=function(rs){return new stream.Readable({objectMode:!0,highWaterMark:16}).wrap(rs)},Duplexify=function(writable,readable,opts){return this instanceof Duplexify?(stream.Duplex.call(this,opts),this._writable=null,this._readable=null,this._readable2=null,this._forwardDestroy=!opts||opts.destroy!==!1,this._forwardEnd=!opts||opts.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,writable&&this.setWritable(writable),void(readable&&this.setReadable(readable))):new Duplexify(writable,readable,opts)};inherits(Duplexify,stream.Duplex),Duplexify.obj=function(writable,readable,opts){return opts||(opts={}),opts.objectMode=!0,opts.highWaterMark=16,new Duplexify(writable,readable,opts)},Duplexify.prototype.cork=function(){1===++this._corked&&this.emit("cork")},Duplexify.prototype.uncork=function(){this._corked&&0===--this._corked&&this.emit("uncork")},Duplexify.prototype.setWritable=function(writable){if(this._unwrite&&this._unwrite(),this.destroyed)return void(writable&&writable.destroy&&writable.destroy());if(null===writable||writable===!1)return void this.end();var self=this,unend=eos(writable,{writable:!0,readable:!1},destroyer(this,this._forwardEnd)),ondrain=function(){var ondrain=self._ondrain;self._ondrain=null,ondrain&&ondrain()},clear=function(){self._writable.removeListener("drain",ondrain),unend()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=clear,this.uncork()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)return void(readable&&readable.destroy&&readable.destroy());if(null===readable||readable===!1)return this.push(null),void this.resume();var self=this,unend=eos(readable,{writable:!1,readable:!0},destroyer(this)),onreadable=function(){self._forward()},onend=function(){self.push(null)},clear=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()};this._drained=!0,this._readable=readable,this._readable2=readable._readableState?readable:toStreams2(readable),this._readable2.on("readable",onreadable),this._readable2.on("end",onend),this._unread=clear,this._forward()},Duplexify.prototype._read=function(){this._drained=!0,this._forward()},Duplexify.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){this._forwarding=!0;for(var data;this._drained&&null!==(data=shift(this._readable2));)this.destroyed||(this._drained=this.push(data));this._forwarding=!1}},Duplexify.prototype.destroy=function(err){if(!this.destroyed){this.destroyed=!0;var self=this;process.nextTick(function(){self._destroy(err)})}},Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null,ondrain?ondrain(err):this.emit("error",err)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},Duplexify.prototype._write=function(data,enc,cb){return this.destroyed?cb():this._corked?onuncork(this,this._write.bind(this,data,enc,cb)):data===SIGNAL_FLUSH?this._finish(cb):this._writable?void(this._writable.write(data)===!1?this._ondrain=cb:cb()):cb()},Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend"),onuncork(this,function(){end(self._forwardEnd&&self._writable,function(){self._writableState.prefinished===!1&&(self._writableState.prefinished=!0),self.emit("prefinish"),onuncork(self,cb)})})},Duplexify.prototype.end=function(data,enc,cb){return"function"==typeof data?this.end(null,null,data):"function"==typeof enc?this.end(data,null,enc):(this._ended=!0,data&&this.write(data),this._writableState.ending||this.write(SIGNAL_FLUSH),stream.Writable.prototype.end.call(this,cb))},module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:85,buffer:9,"end-of-stream":32,inherits:41,"readable-stream":97,"stream-shift":123}],32:[function(require,module){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||opts.readable!==!1&&stream.readable,writable=opts.writable||opts.writable!==!1&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback()},onend=function(){readable=!1,writable||callback()},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback(new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),opts.error!==!1&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:33}],33:[function(require,module){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0})})},{wrappy:132}],34:[function(require,module){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||opts.readable!==!1&&stream.readable,writable=opts.writable||opts.writable!==!1&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback.call(stream)},onend=function(){readable=!1,writable||callback.call(stream)},onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback.call(stream,new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),opts.error!==!1&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:82}],35:[function(require,module){function init(type,message,cause){prr(this,{type:type,name:type,cause:"string"!=typeof message?message:cause,message:message&&"string"!=typeof message?message.message:message},"ewr")}function CustomError(message,cause){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),init.call(this,"CustomError",message,cause)}function createError(errno,type,proto){var err=function(message,cause){init.call(this,type,message,cause),"FilesystemError"==type&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(errno.errno[this.cause.errno]?errno.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return err.prototype=proto?new proto:new CustomError,err}var prr=require("prr");CustomError.prototype=new Error,module.exports=function(errno){var ce=function(type,proto){return createError(errno,type,proto)};return{CustomError:CustomError,FilesystemError:ce("FilesystemError"),createError:ce}}},{prr:37}],36:[function(require,module){var all=module.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];module.exports.errno={},module.exports.code={},all.forEach(function(error){module.exports.errno[error.errno]=error,module.exports.code[error.code]=error}),module.exports.custom=require("./custom")(module.exports),module.exports.create=module.exports.custom.createError},{"./custom":35}],37:[function(require,module){!function(name,context,definition){"undefined"!=typeof module&&module.exports?module.exports=definition():context[name]=definition()}("prr",this,function(){var setProperty="function"==typeof Object.defineProperty?function(obj,key,options){return Object.defineProperty(obj,key,options),obj}:function(obj,key,options){return obj[key]=options.value,obj},makeOptions=function(value,options){var oo="object"==typeof options,os=!oo&&"string"==typeof options,op=function(p){return oo?!!options[p]:os?options.indexOf(p[0])>-1:!1};return{enumerable:op("enumerable"),configurable:op("configurable"),writable:op("writable"),value:value}},prr=function(obj,key,value,options){var k;if(options=makeOptions(value,options),"object"==typeof key){for(k in key)Object.hasOwnProperty.call(key,k)&&(options.value=key[k],setProperty(obj,k,options));return obj}return setProperty(obj,key,options)};return prr})},{}],38:[function(require,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args);return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned&&(m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&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(0>position)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){var ret;return ret=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)}},{}],39:[function(require,module){!function(name,definition,global){"use strict";"function"==typeof define?define(definition):"undefined"!=typeof module&&module.exports?module.exports=definition():global[name]=definition()}("IDBStore",function(){"use strict";function mixin(target,source){var name,s;for(name in source)s=source[name],s!==empty[name]&&s!==target[name]&&(target[name]=s);return target}function hasVersionError(errorEvent){return"error"in errorEvent.target?"VersionError"==errorEvent.target.error.name:"errorCode"in errorEvent.target?12==errorEvent.target.errorCode:!1}var defaultErrorHandler=function(error){throw error},defaultSuccessHandler=function(){},defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:!0,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]},IDBStore=function(kwArgs,onStoreReady){"undefined"==typeof onStoreReady&&"function"==typeof kwArgs&&(onStoreReady=kwArgs),"[object Object]"!=Object.prototype.toString.call(kwArgs)&&(kwArgs={});for(var key in defaults)this[key]="undefined"!=typeof kwArgs[key]?kwArgs[key]:defaults[key];this.dbName=this.storePrefix+this.storeName,this.dbVersion=parseInt(this.dbVersion,10)||1,onStoreReady&&(this.onStoreReady=onStoreReady);var env="object"==typeof window?window:self,availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0],this.idb=env[this.implementation],this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange,this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"},this.openDB()},proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion),preventSuccessCallback=!1;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent))this.onError(new Error("The version number provided is lower than the existing one."));else{var error;if(errorEvent.target.error)error=errorEvent.target.error;else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;"errorCode"in errorEvent.target&&(errorMessage+=" with error code "+errorEvent.target.errorCode),error=new Error(errorMessage)}this.onError(error)}}.bind(this),openRequest.onsuccess=function(event){if(!preventSuccessCallback){if(this.db)return void this.onStoreReady();if(this.db=event.target.result,"string"==typeof this.db.version)return void this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));if(!this.db.objectStoreNames.contains(this.storeName))return void this.onError(new Error("Object store couldn't be created."));var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName)return preventSuccessCallback=!0,void this.onError(new Error("Cannot create index: No index name given."));if(this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName),complies=this.indexComplies(actualIndex,indexData);complies||(preventSuccessCallback=!0,this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else preventSuccessCallback=!0,this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))},this),existingIndexes.length&&(preventSuccessCallback=!0,this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),preventSuccessCallback||this.onStoreReady()}}.bind(this),openRequest.onupgradeneeded=function(event){if(this.db=event.target.result,this.db.objectStoreNames.contains(this.storeName))this.store=event.target.transaction.objectStore(this.storeName);else{var optionalParameters={autoIncrement:this.autoIncrement};null!==this.keyPath&&(optionalParameters.keyPath=this.keyPath),this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(indexName||(preventSuccessCallback=!0,this.onError(new Error("Cannot create index: No index name given."))),this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName),complies=this.indexComplies(actualIndex,indexData);complies||(this.store.deleteIndex(indexName),this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})},this),existingIndexes.length&&existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess,deleteRequest.onerror=onError}else onError(new Error("Browser does not support IndexedDB deleteDatabase!"))},put:function(key,value,onSuccess,onError){null!==this.keyPath&&(onError=onSuccess,onSuccess=value,value=key),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var putRequest,hasSuccess=!1,result=null,putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);return putTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},putTransaction.onabort=onError,putTransaction.onerror=onError,null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=putTransaction.objectStore(this.storeName).put(value)):putRequest=putTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},putRequest.onerror=onError,putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},getTransaction.onabort=onError,getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);return getRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getRequest.onerror=onError,getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},removeTransaction.onabort=onError,removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName)["delete"](key);return deleteRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},deleteRequest.onerror=onError,removeTransaction},batch:function(dataArray,onSuccess,onError){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),"[object Array]"!=Object.prototype.toString.call(dataArray))onError(new Error("dataArray argument must be of type Array."));else if(0===dataArray.length)return onSuccess(!0);var count=dataArray.length,called=!1,hasSuccess=!1,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(hasSuccess)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(){count--,0!==count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(operation){var type=operation.type,key=operation.key,value=operation.value,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err,type,key))};if("remove"==type){var deleteRequest=batchTransaction.objectStore(this.storeName)["delete"](key);deleteRequest.onsuccess=onItemSuccess,deleteRequest.onerror=onItemError}else if("put"==type){ -var putRequest;null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=batchTransaction.objectStore(this.storeName).put(value)):putRequest=batchTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError}},this),batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}});return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){"function"==typeof options&&(onSuccess=options,onError=onSuccess,options={}),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),options||(options={}),"[object Array]"!=Object.prototype.toString.call(dataArray)&&onError(new Error("dataArray argument must be of type Array."));var keyField=options.keyField||this.keyPath,count=dataArray.length,called=!1,hasSuccess=!1,index=0,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){hasSuccess?onSuccess(dataArray):onError(!1)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){var record=dataArray[index++];record[keyField]=event.target.result,count--,0!==count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(record){var putRequest,key=record.key,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err))};null!==this.keyPath?(this._addIdPropertyIfNeeded(record),putRequest=batchTransaction.objectStore(this.storeName).put(record)):putRequest=batchTransaction.objectStore(this.storeName).put(record,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError},this),batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),arrayType||(arrayType="sparse"),"[object Array]"!=Object.prototype.toString.call(keyArray))onError(new Error("keyArray argument must be of type Array."));else if(0===keyArray.length)return onSuccess([]);var data=[],count=keyArray.length,called=!1,hasSuccess=!1,result=null,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){event.target.result||"dense"==arrayType?data.push(event.target.result):"sparse"==arrayType&&data.length++,count--,0===count&&(called=!0,hasSuccess=!0,result=data)};return keyArray.forEach(function(key){var onItemError=function(err){called=!0,result=err,onError(err),batchTransaction.abort()},getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=onItemError},this),batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY),store=getAllTransaction.objectStore(this.storeName);return store.getAll?this._getAllNative(getAllTransaction,store,onSuccess,onError):this._getAllCursor(getAllTransaction,store,onSuccess,onError),getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;cursor?(all.push(cursor.value),cursor["continue"]()):(hasSuccess=!0,result=all)},cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},clearTransaction.onabort=onError,clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();return clearRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},clearRequest.onerror=onError,clearTransaction},_addIdPropertyIfNeeded:function(dataObj){"undefined"==typeof dataObj[this.keyPath]&&(dataObj[this.keyPath]=this._insertIdCount++ +Date.now())},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name,indexData.unique=!!indexData.unique,indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){var complies=["keyPath","unique","multiEntry"].every(function(key){if("multiEntry"==key&&void 0===actual[key]&&expected[key]===!1)return!0;if("keyPath"==key&&"[object Array]"==Object.prototype.toString.call(expected[key])){var exp=expected.keyPath,act=actual.keyPath;if("string"==typeof act)return exp.toString()==act;if("function"!=typeof act.contains&&"function"!=typeof act.indexOf)return!1;if(act.length!==exp.length)return!1;for(var i=0,m=exp.length;m>i;i++)if(!(act.contains&&act.contains(exp[i])||act.indexOf(-1!==exp[i])))return!1;return!0}return expected[key]==actual[key]});return complies},iterate:function(onItem,options){options=mixin({index:null,order:"ASC",autoContinue:!0,filterDuplicates:!1,keyRange:null,writeAccess:!1,onEnd:null,onError:defaultErrorHandler,limit:1/0,offset:0,allowItemRejection:!1},options||{});var directionType="desc"==options.order.toLowerCase()?"PREV":"NEXT";options.filterDuplicates&&(directionType+="_NO_DUPLICATE");var hasSuccess=!1,cursorTransaction=this.db.transaction([this.storeName],this.consts[options.writeAccess?"READ_WRITE":"READ_ONLY"]),cursorTarget=cursorTransaction.objectStore(this.storeName);options.index&&(cursorTarget=cursorTarget.index(options.index));var recordCount=0;cursorTransaction.oncomplete=function(){return hasSuccess?void(options.onEnd?options.onEnd():onItem(null)):void options.onError(null)},cursorTransaction.onabort=options.onError,cursorTransaction.onerror=options.onError;var cursorRequest=cursorTarget.openCursor(options.keyRange,this.consts[directionType]);return cursorRequest.onerror=options.onError,cursorRequest.onsuccess=function(event){var cursor=event.target.result;if(cursor)if(options.offset)cursor.advance(options.offset),options.offset=0;else{var onItemReturn=onItem(cursor.value,cursor,cursorTransaction);options.allowItemRejection&&onItemReturn===!1||recordCount++,options.autoContinue&&(recordCount+options.offset>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?0/0:(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=0>value||0===value&&0>1/value?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}},{}],41:[function(require,module){module.exports="function"==typeof Object.create?function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],42:[function(require,module,exports){var Readable=require("stream").Readable;exports.getIntersectionStream=function(sortedSets){for(var s=new Readable,i=0,ii=[],k=0;ksortedSets[i+1][ii[i+1]])ii[i+1]++;else if(i+2=sortedSets[k].length&&(finished=!0);i=0}return s.push(null),s}},{stream:122}],43:[function(require,module){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],44:[function(require,module){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],45:[function(require,module){function isBuffer(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}var Buffer=require("buffer").Buffer;module.exports=isBuffer},{buffer:9}],46:[function(require,module){function Codec(opts){this.opts=opts||{},this.encodings=encodings}var encodings=require("./lib/encodings");module.exports=Codec,Codec.prototype._encoding=function(encoding){return"string"==typeof encoding&&(encoding=encodings[encoding]),encoding||(encoding=encodings.id),encoding},Codec.prototype._keyEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&batchOpts.keyEncoding||opts&&opts.keyEncoding||this.opts.keyEncoding)},Codec.prototype._valueEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&(batchOpts.valueEncoding||batchOpts.encoding)||opts&&(opts.valueEncoding||opts.encoding)||this.opts.valueEncoding||this.opts.encoding)},Codec.prototype.encodeKey=function(key,opts,batchOpts){return this._keyEncoding(opts,batchOpts).encode(key)},Codec.prototype.encodeValue=function(value,opts,batchOpts){return this._valueEncoding(opts,batchOpts).encode(value)},Codec.prototype.decodeKey=function(key,opts){return this._keyEncoding(opts).decode(key)},Codec.prototype.decodeValue=function(value,opts){return this._valueEncoding(opts).decode(value)},Codec.prototype.encodeBatch=function(ops,opts){var self=this;return ops.map(function(_op){var op={type:_op.type,key:self.encodeKey(_op.key,opts,_op)};return self.keyAsBuffer(opts,_op)&&(op.keyEncoding="binary"),_op.prefix&&(op.prefix=_op.prefix),"value"in _op&&(op.value=self.encodeValue(_op.value,opts,_op),self.valueAsBuffer(opts,_op)&&(op.valueEncoding="binary")),op})};var ltgtKeys=["lt","gt","lte","gte","start","end"];Codec.prototype.encodeLtgt=function(ltgt){var self=this,ret={};return Object.keys(ltgt).forEach(function(key){ret[key]=ltgtKeys.indexOf(key)>-1?self.encodeKey(ltgt[key],ltgt):ltgt[key]}),ret},Codec.prototype.createStreamDecoder=function(opts){var self=this;return opts.keys&&opts.values?function(key,value){return{key:self.decodeKey(key,opts),value:self.decodeValue(value,opts)}}:opts.keys?function(key){return self.decodeKey(key,opts)}:opts.values?function(_,value){return self.decodeValue(value,opts)}:function(){}},Codec.prototype.keyAsBuffer=function(opts){return this._keyEncoding(opts).buffer},Codec.prototype.valueAsBuffer=function(opts){return this._valueEncoding(opts).buffer}},{"./lib/encodings":47}],47:[function(require,module,exports){(function(Buffer){function identity(value){return value}function isBinary(data){return void 0===data||null===data||Buffer.isBuffer(data)}exports.utf8=exports["utf-8"]={encode:function(data){return isBinary(data)?data:String(data)},decode:identity,buffer:!1,type:"utf8"},exports.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},exports.binary={encode:function(data){return isBinary(data)?data:new Buffer(data)},decode:identity,buffer:!0,type:"binary"},exports.id={encode:function(data){return data},decode:function(data){return data},buffer:!1,type:"id"};var bufferEncodings=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];bufferEncodings.forEach(function(type){exports[type]={encode:function(data){return isBinary(data)?data:new Buffer(data,type)},decode:function(buffer){return buffer.toString(type)},buffer:!0,type:type}})}).call(this,require("buffer").Buffer)},{buffer:9}],48:[function(require,module){var createError=require("errno").create,LevelUPError=createError("LevelUPError"),NotFoundError=createError("NotFoundError",LevelUPError);NotFoundError.prototype.notFound=!0,NotFoundError.prototype.status=404,module.exports={LevelUPError:LevelUPError,InitializationError:createError("InitializationError",LevelUPError),OpenError:createError("OpenError",LevelUPError),ReadError:createError("ReadError",LevelUPError),WriteError:createError("WriteError",LevelUPError),NotFoundError:NotFoundError,EncodingError:createError("EncodingError",LevelUPError)}},{errno:36}],49:[function(require,module){function ReadStream(iterator,options){return this instanceof ReadStream?(Readable.call(this,extend(options,{objectMode:!0})),this._iterator=iterator,this._destroyed=!1,this._decoder=null,options&&options.decoder&&(this._decoder=options.decoder),void this.on("end",this._cleanup.bind(this))):new ReadStream(iterator,options)}var inherits=require("inherits"),Readable=require("readable-stream").Readable,extend=require("xtend"),EncodingError=require("level-errors").EncodingError;module.exports=ReadStream,inherits(ReadStream,Readable),ReadStream.prototype._read=function(){var self=this;this._destroyed||this._iterator.next(function(err,key,value){if(!self._destroyed){if(err)return self.emit("error",err);if(void 0===key&&void 0===value)self.push(null);else{if(!self._decoder)return self.push({key:key,value:value});try{var value=self._decoder(key,value)}catch(err){return self.emit("error",new EncodingError(err)),void self.push(null)}self.push(value)}}})},ReadStream.prototype.destroy=ReadStream.prototype._cleanup=function(){var self=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(err){return err?self.emit("error",err):void self.emit("close")}))}},{inherits:41,"level-errors":48,"readable-stream":56,xtend:133}],50:[function(require,module){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],51:[function(require,module){(function(process){function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;l>i;i++)f(xs[i],i)}module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys},util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable),forEach(objectKeys(Writable.prototype),function(method){Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method])})}).call(this,require("_process"))},{"./_stream_readable":53,"./_stream_writable":55,_process:85,"core-util-is":11,inherits:41}],52:[function(require,module){function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=require("./_stream_transform"),util=require("core-util-is");util.inherits=require("inherits"),util.inherits(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":54,"core-util-is":11,inherits:41}],53:[function(require,module){(function(process){function ReadableState(options,stream){var Duplex=require("./_stream_duplex");options=options||{};var hwm=options.highWaterMark,defaultHwm=options.objectMode?16:16384;this.highWaterMark=hwm||0===hwm?hwm:defaultHwm,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.objectMode=!!options.objectMode,stream instanceof Duplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.defaultEncoding=options.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){require("./_stream_duplex");return this instanceof Readable?(this._readableState=new ReadableState(options,this),this.readable=!0,void Stream.call(this)):new Readable(options)}function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er)stream.emit("error",er);else if(util.isNullOrUndefined(chunk))state.reading=!1,state.ended||onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;32>p;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:isNaN(n)||util.isNull(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:0>=n?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return util.isBuffer(chunk)||util.isString(chunk)||util.isNullOrUndefined(chunk)||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(ni&&n>c;i++){var buf=list[0],cpy=Math.min(n-c,buf.length);stringMode?ret+=buf.slice(0,cpy):buf.copy(ret,c,0,cpy),cpy0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;l>i;i++)f(xs[i],i)}function indexOf(xs,x){for(var i=0,l=xs.length;l>i;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var isArray=require("isarray"),Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;EE.listenerCount||(EE.listenerCount=function(emitter,type){return emitter.listeners(type).length});var Stream=require("stream"),util=require("core-util-is");util.inherits=require("inherits");var StringDecoder,debug=require("util");debug=debug&&debug.debuglog?debug.debuglog("stream"):function(){},util.inherits(Readable,Stream),Readable.prototype.push=function(chunk,encoding){var state=this._readableState;return util.isString(chunk)&&!state.objectMode&&(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=new Buffer(chunk,encoding),encoding="")),readableAddChunk(this,state,chunk,encoding,!1)},Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",!0)},Readable.prototype.setEncoding=function(enc){return StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this._readableState.decoder=new StringDecoder(enc),this._readableState.encoding=enc,this};var MAX_HWM=8388608;Readable.prototype.read=function(n){debug("read",n);var state=this._readableState,nOrig=n;if((!util.isNumber(n)||n>0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,util.isNull(ret)&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),util.isNull(ret)||this.emit("data",ret),ret},Readable.prototype._read=function(){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);!1===ret&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;len>i;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);return-1===i?this:(state.pipes.splice(i,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if("data"===ev&&!1!==this._readableState.flowing&&this.resume(),"readable"===ev&&this.readable){var state=this._readableState;if(!state.readableListening)if(state.readableListening=!0,state.emittedReadable=!1,state.needReadable=!0,state.reading)state.length&&emitReadable(this,state);else{var self=this;process.nextTick(function(){debug("readable nexttick read 0"),self.read(0)})}}return res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!0,state.reading||(debug("resume read 0"),this.read(0)),resume(this,state)),this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Readable.prototype.wrap=function(stream){var state=this._readableState,paused=!1,self=this;stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&self.push(chunk)}self.push(null)}),stream.on("data",function(chunk){if(debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),chunk&&(state.objectMode||chunk.length)){var ret=self.push(chunk);ret||(paused=!0,stream.pause())}});for(var i in stream)util.isFunction(stream[i])&&util.isUndefined(this[i])&&(this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i));var events=["error","close","destroy","pause","resume"];return forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))}),self._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},self},Readable._fromList=fromList}).call(this,require("_process"))},{"./_stream_duplex":51,_process:85,buffer:9,"core-util-is":11,events:38,inherits:41,isarray:50,stream:122,"string_decoder/":57,util:6}],54:[function(require,module){function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)},this.needTransform=!1, -this.transforming=!1,this.writecb=null,this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=!1;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null,ts.writecb=null,util.isNullOrUndefined(data)||stream.push(data),cb&&cb(er);var rs=stream._readableState;rs.reading=!1,(rs.needReadable||rs.length1){for(var cbs=[],c=0;c=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&56319>=charCode)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&56319>=charCode){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(2>=i&&c>>4==14){this.charLength=3;break}if(3>=i&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:9}],58:[function(require,module){(function(Buffer){function Level(location){if(!(this instanceof Level))return new Level(location);if(!location)throw new Error("constructor requires at least a location argument");this.IDBOptions={},this.location=location}module.exports=Level;var IDB=require("idb-wrapper"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,util=require("util"),Iterator=require("./iterator"),isBuffer=require("isbuffer"),xtend=require("xtend"),toBuffer=require("typedarray-to-buffer");util.inherits(Level,AbstractLevelDOWN),Level.prototype._open=function(options,callback){var self=this,idbOpts={storeName:this.location,autoIncrement:!1,keyPath:null,onStoreReady:function(){callback&&callback(null,self.idb)},onError:function(err){callback&&callback(err)}};xtend(idbOpts,options),this.IDBOptions=idbOpts,this.idb=new IDB(idbOpts)},Level.prototype._get=function(key,options,callback){this.idb.get(key,function(value){if(void 0===value)return callback(new Error("NotFound"));var asBuffer=!0;return options.asBuffer===!1&&(asBuffer=!1),options.raw&&(asBuffer=!1),asBuffer&&(value=value instanceof Uint8Array?toBuffer(value):new Buffer(String(value))),callback(null,value,key)},callback)},Level.prototype._del=function(id,options,callback){this.idb.remove(id,callback,callback)},Level.prototype._put=function(key,value,options,callback){value instanceof ArrayBuffer&&(value=toBuffer(new Uint8Array(value)));var obj=this.convertEncoding(key,value,options);Buffer.isBuffer(obj.value)&&(obj.value=new Uint8Array("function"==typeof value.toArrayBuffer?value.toArrayBuffer():value)),this.idb.put(obj.key,obj.value,function(){callback()},callback)},Level.prototype.convertEncoding=function(key,value,options){if(options.raw)return{key:key,value:value};if(value){var stringed=value.toString();"NaN"===stringed&&(value="NaN")}var valEnc=options.valueEncoding,obj={key:key,value:value};return!value||valEnc&&"binary"===valEnc||"object"!=typeof obj.value&&(obj.value=stringed),obj},Level.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),new Iterator(this.idb,options)},Level.prototype._batch=function(array,options,callback){var i,k,copiedOp,currentOp,modified=[];if(0===array.length)return setTimeout(callback,0);for(i=0;i0&&this._count++>=this._limit&&(shouldCall=!1),shouldCall&&this.callback(!1,cursor.key,cursor.value),cursor&&cursor["continue"]()},Iterator.prototype._next=function(callback){return callback?this._keyRangeError?callback():(this._started||(this.createIterator(),this._started=!0),void(this.callback=callback)):new Error("next() requires a callback argument")}},{"abstract-leveldown":62,ltgt:81,util:131}],60:[function(require,module){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;if(err=this._db._checkKeyValue(value,"value",this._db._isBuffer))throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:85}],61:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{_process:85,dup:15}],62:[function(require,module){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");return"object"!=typeof options&&(options={}),"function"==typeof this._open?this._open(options,callback):void process.nextTick(callback)},AbstractLevelDOWN.prototype.close=function(callback){if("function"!=typeof callback)throw new Error("close() requires a callback argument");return"function"==typeof this._close?this._close(callback):void process.nextTick(callback)},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(err=this._checkKeyValue(value,"value",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));"object"!=typeof options&&(options={});for(var e,err,i=0,l=array.length;l>i;i++)if(e=array[i],"object"==typeof e){if(err=this._checkKeyValue(e.type,"type",this._isBuffer))return callback(err);if(err=this._checkKeyValue(e.key,"key",this._isBuffer))return callback(err);if("put"==e.type&&(err=this._checkKeyValue(e.value,"value",this._isBuffer)))return callback(err)}return"function"==typeof this._batch?this._batch(array,options,callback):void process.nextTick(callback)},AbstractLevelDOWN.prototype.approximateSize=function(start,end,callback){if(null==start||null==end||"function"==typeof start||"function"==typeof end)throw new Error("approximateSize() requires valid `start`, `end` and `callback` arguments");if("function"!=typeof callback)throw new Error("approximateSize() requires a callback argument");return this._isBuffer(start)||(start=String(start)),this._isBuffer(end)||(end=String(end)),"function"==typeof this._approximateSize?this._approximateSize(start,end,callback):void process.nextTick(function(){callback(null,0)})},AbstractLevelDOWN.prototype._setupIteratorOptions=function(options){var self=this;return options=xtend(options),["start","end","gt","gte","lt","lte"].forEach(function(o){options[o]&&self._isBuffer(options[o])&&0===options[o].length&&delete options[o]}),options.reverse=!!options.reverse,options.reverse&&options.lt&&(options.start=options.lt),options.reverse&&options.lte&&(options.start=options.lte),!options.reverse&&options.gt&&(options.start=options.gt),!options.reverse&&options.gte&&(options.start=options.gte),(options.reverse&&options.lt&&!options.lte||!options.reverse&&options.gt&&!options.gte)&&(options.exclusiveStart=!0),options},AbstractLevelDOWN.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),options=this._setupIteratorOptions(options),"function"==typeof this._iterator?this._iterator(options):new AbstractIterator(this)},AbstractLevelDOWN.prototype._chainedBatch=function(){return new AbstractChainedBatch(this)},AbstractLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},AbstractLevelDOWN.prototype._checkKeyValue=function(obj,type){if(null===obj||void 0===obj)return new Error(type+" cannot be `null` or `undefined`");if(this._isBuffer(obj)){if(0===obj.length)return new Error(type+" cannot be an empty Buffer")}else if(""===String(obj))return new Error(type+" cannot be an empty String")},module.exports.AbstractLevelDOWN=AbstractLevelDOWN,module.exports.AbstractIterator=AbstractIterator,module.exports.AbstractChainedBatch=AbstractChainedBatch}).call(this,{isBuffer:require("../../../is-buffer/index.js")},require("_process"))},{"../../../is-buffer/index.js":43,"./abstract-chained-batch":60,"./abstract-iterator":61,_process:85,xtend:63}],63:[function(require,module){function extend(){for(var target={},i=0;i2?arguments[2]:null;if(l===+l)for(i=0;l>i;i++)null===context?fn(isString?obj.charAt(i):obj[i],i,obj):fn.call(context,isString?obj.charAt(i):obj[i],i,obj);else for(k in obj)hasOwn.call(obj,k)&&(null===context?fn(obj[k],k,obj):fn.call(context,obj[k],k,obj))}},{}],65:[function(require,module){module.exports=Object.keys||require("./shim")},{"./shim":67}],66:[function(require,module){var toString=Object.prototype.toString;module.exports=function isArguments(value){var str=toString.call(value),isArguments="[object Arguments]"===str;return isArguments||(isArguments="[object Array]"!==str&&null!==value&&"object"==typeof value&&"number"==typeof value.length&&value.length>=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],67:[function(require,module){!function(){"use strict";var keysShim,has=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,forEach=require("./foreach"),isArgs=require("./isArguments"),hasDontEnumBug=!{toString:null}.propertyIsEnumerable("toString"),hasProtoEnumBug=function(){}.propertyIsEnumerable("prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];keysShim=function(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toString.call(object),isArguments=isArgs(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");if(isArguments)forEach(object,function(value){theKeys.push(value)});else{var name,skipProto=hasProtoEnumBug&&isFunction;for(name in object)skipProto&&"prototype"===name||!has.call(object,name)||theKeys.push(name)}if(hasDontEnumBug){var ctor=object.constructor,skipConstructor=ctor&&ctor.prototype===object;forEach(dontEnums,function(dontEnum){skipConstructor&&"constructor"===dontEnum||!has.call(object,dontEnum)||theKeys.push(dontEnum)})}return theKeys},module.exports=keysShim}()},{"./foreach":64,"./isArguments":66}],68:[function(require,module){function hasKeys(source){return null!==source&&("object"==typeof source||"function"==typeof source)}module.exports=hasKeys},{}],69:[function(require,module){function extend(){for(var target={},i=0;i=1.3.5 <2.0.0",type:"range"},"/Users/fergusmcdowall/node/search-index"]],_from:"levelup@>=1.3.5 <2.0.0",_id:"levelup@1.3.5",_inCache:!0,_installable:!0,_location:"/levelup",_nodeVersion:"7.4.0",_npmOperationalInternal:{host:"packages-18-east.internal.npmjs.com",tmp:"tmp/levelup-1.3.5.tgz_1488477248468_0.036320413229987025"},_npmUser:{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},_npmVersion:"4.0.5",_phantomChildren:{},_requested:{raw:"levelup@^1.3.5",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"^1.3.5",spec:">=1.3.5 <2.0.0",type:"range"},_requiredBy:["/","/search-index-adder","/search-index-searcher"],_resolved:"https://registry.npmjs.org/levelup/-/levelup-1.3.5.tgz",_shasum:"fa80a972b74011f2537c8b65678bd8b5188e4e66",_shrinkwrap:null,_spec:"levelup@^1.3.5",_where:"/Users/fergusmcdowall/node/search-index",browser:{leveldown:!1,"leveldown/package":!1,semver:!1},bugs:{url:"https://github.com/level/levelup/issues"},contributors:[{name:"Rod Vagg",email:"r@va.gg",url:"https://github.com/rvagg"},{name:"John Chesley",email:"john@chesl.es",url:"https://github.com/chesles/"},{name:"Jake Verbaten",email:"raynos2@gmail.com",url:"https://github.com/raynos"},{name:"Dominic Tarr",email:"dominic.tarr@gmail.com",url:"https://github.com/dominictarr"},{name:"Max Ogden",email:"max@maxogden.com",url:"https://github.com/maxogden"},{name:"Lars-Magnus Skog",email:"ralphtheninja@riseup.net",url:"https://github.com/ralphtheninja"},{name:"David Björklund",email:"david.bjorklund@gmail.com",url:"https://github.com/kesla"},{name:"Julian Gruber",email:"julian@juliangruber.com",url:"https://github.com/juliangruber"},{name:"Paolo Fragomeni",email:"paolo@async.ly",url:"https://github.com/0x00a"},{name:"Anton Whalley",email:"anton.whalley@nearform.com",url:"https://github.com/No9"},{name:"Matteo Collina",email:"matteo.collina@gmail.com",url:"https://github.com/mcollina"},{name:"Pedro Teixeira",email:"pedro.teixeira@gmail.com",url:"https://github.com/pgte"},{name:"James Halliday",email:"mail@substack.net",url:"https://github.com/substack"},{name:"Jarrett Cruger",email:"jcrugzz@gmail.com",url:"https://github.com/jcrugzz"}],dependencies:{"deferred-leveldown":"~1.2.1","level-codec":"~6.1.0","level-errors":"~1.0.3","level-iterator-stream":"~1.3.0",prr:"~1.0.1",semver:"~5.1.0",xtend:"~4.0.0"},description:"Fast & simple storage - a Node.js-style LevelDB wrapper",devDependencies:{async:"~1.5.0",bustermove:"~1.0.0",delayed:"~1.0.1",faucet:"~0.0.1",leveldown:"^1.1.0",memdown:"~1.1.0","msgpack-js":"~0.3.0",referee:"~1.2.0",rimraf:"~2.4.3","slow-stream":"0.0.4",tap:"~2.3.1",tape:"~4.2.1"},directories:{},dist:{shasum:"fa80a972b74011f2537c8b65678bd8b5188e4e66",tarball:"https://registry.npmjs.org/levelup/-/levelup-1.3.5.tgz"},gitHead:"ed5a54202085839784f1189f1266e9c379d64081",homepage:"https://github.com/level/levelup",keywords:["leveldb","stream","database","db","store","storage","json"],license:"MIT",main:"lib/levelup.js",maintainers:[{name:"rvagg",email:"rod@vagg.org"},{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},{name:"juliangruber",email:"julian@juliangruber.com"}],name:"levelup",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/level/levelup.git"},scripts:{test:"tape test/*-test.js | faucet"},version:"1.3.5"}},{}],74:[function(require,module){(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){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++indexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?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){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor;return pattern.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&&MAX_SAFE_INTEGER>=value}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 difference=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,!0)):[]}),isArray=Array.isArray;module.exports=difference}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],75:[function(require,module){(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){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++indexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=120&&array.length>=120)?new SetCache(othIndex&&array):void 0}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++index-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,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.*?")+"$"),splice=arrayProto.splice,nativeMax=Math.max,nativeMin=Math.min,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 intersection=baseRest(function(arrays){var mapped=arrayMap(arrays,castArrayLikeObject);return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped):[]});module.exports=intersection}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],76:[function(require,module,exports){(function(global){function arrayFilter(array,predicate){for(var index=-1,length=null==array?0:array.length,resIndex=0,result=[];++indexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;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&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&length>value}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function objectToString(value){return nativeObjectToString.call(value)}function toSource(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+""}catch(e){}}return""}function eq(value,other){return value===other||value!==value&&other!==other}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isEqual(value,other){return baseIsEqual(value,other)}function isFunction(value){if(!isObject(value))return!1;var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function stubArray(){return[]}function stubFalse(){return!1}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",asyncTag="[object AsyncFunction]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",nullTag="[object Null]",objectTag="[object Object]",promiseTag="[object Promise]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",undefinedTag="[object Undefined]",weakMapTag="[object WeakMap]",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]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!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 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&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),nativeObjectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Buffer=moduleExports?root.Buffer:void 0,Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,nativeKeys=overArg(Object.keys,Object),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;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 getSymbols=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray,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=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag}return result});var isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isBuffer=nativeIsBuffer||stubFalse,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module.exports=isEqual}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],77:[function(require,module){function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if("number"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=void 0===value;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=void 0!==computed,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function sortedIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value);if(length>index&&eq(array[index],value))return index}return-1}function eq(value,other){return value===other||value!==value&&other!==other}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function identity(value){return value}var MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,symbolTag="[object Symbol]",objectProto=Object.prototype,objectToString=objectProto.toString,nativeFloor=Math.floor,nativeMin=Math.min;module.exports=sortedIndexOf},{}],78:[function(require,module){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 arrayPush(array,values){for(var index=-1,length=values.length,offset=array.length;++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=void 0===start?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}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){var sign=0>value?-1:1;return sign*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 FUNC_ERROR_TEXT="Expected a function",INFINITY=1/0,MAX_INTEGER=1.7976931348623157e308,NAN=0/0,symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString,nativeMax=Math.max;module.exports=spread},{}],79:[function(require,module){(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){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++indexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?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){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor;return pattern.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&&MAX_SAFE_INTEGER>=value}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,union=baseRest(function(arrays){return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,!0))}),isArray=Array.isArray;module.exports=union}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],80:[function(require,module){(function(global){function arrayIncludes(array,value){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++indexindex)return!1;var lastIndex=data.length-1; - -return index==lastIndex?data.pop():splice.call(data,index,1),!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?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){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexi;i++){var cmp=a[i]-b[i];if(cmp)return cmp}return a.length-b.length}return b>a?-1:a>b?1:0};var lowerBoundKey=exports.lowerBoundKey=function(range){return hasKey(range,"gt")||hasKey(range,"gte")||hasKey(range,"min")||(range.reverse?hasKey(range,"end"):hasKey(range,"start"))||void 0},lowerBound=exports.lowerBound=function(range){var k=lowerBoundKey(range);return k&&range[k]},lowerBoundInclusive=exports.lowerBoundInclusive=function(range){return has(range,"gt")?!1:!0},upperBoundInclusive=exports.upperBoundInclusive=function(range){return has(range,"lt")?!1:!0},lowerBoundExclusive=exports.lowerBoundExclusive=function(range){return!lowerBoundInclusive(range)},upperBoundExclusive=exports.upperBoundExclusive=function(range){return!upperBoundInclusive(range)},upperBoundKey=exports.upperBoundKey=function(range){return hasKey(range,"lt")||hasKey(range,"lte")||hasKey(range,"max")||(range.reverse?hasKey(range,"start"):hasKey(range,"end"))||void 0},upperBound=exports.upperBound=function(range){var k=upperBoundKey(range);return k&&range[k]};exports.toLtgt=function(range,_range,map,lower,upper){_range=_range||{},map=map||id;var defaults=arguments.length>3,lb=exports.lowerBoundKey(range),ub=exports.upperBoundKey(range);return lb?"gt"===lb?_range.gt=map(range.gt,!1):_range.gte=map(range[lb],!1):defaults&&(_range.gte=map(lower,!1)),ub?"lt"===ub?_range.lt=map(range.lt,!0):_range.lte=map(range[ub],!0):defaults&&(_range.lte=map(upper,!0)),null!=range.reverse&&(_range.reverse=!!range.reverse),has(_range,"max")&&delete _range.max,has(_range,"min")&&delete _range.min,has(_range,"start")&&delete _range.start,has(_range,"end")&&delete _range.end,_range},exports.contains=function(range,key,compare){compare=compare||exports.compare;var lb=lowerBound(range);if(isDef(lb)){var cmp=compare(key,lb);if(0>cmp||0===cmp&&lowerBoundExclusive(range))return!1}var ub=upperBound(range);if(isDef(ub)){var cmp=compare(key,ub);if(cmp>0||0===cmp&&upperBoundExclusive(range))return!1}return!0},exports.filter=function(range,compare){return function(key){return exports.contains(range,key,compare)}}}).call(this,{isBuffer:require("../is-buffer/index.js")})},{"../is-buffer/index.js":43}],82:[function(require,module){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:132}],83:[function(require,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],84:[function(require,module){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i1)for(var i=1;i0;return destroyer(stream,reading,writing,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)};module.exports=pump},{"end-of-stream":34,fs:6,once:82}],88:[function(require,module){var pump=require("pump"),inherits=require("inherits"),Duplexify=require("duplexify"),toArray=function(args){return args.length?Array.isArray(args[0])?args[0]:Array.prototype.slice.call(args):[]},define=function(opts){var Pumpify=function(){var streams=toArray(arguments);return this instanceof Pumpify?(Duplexify.call(this,null,null,opts),void(streams.length&&this.setPipeline(streams))):new Pumpify(streams)};return inherits(Pumpify,Duplexify),Pumpify.prototype.setPipeline=function(){var streams=toArray(arguments),self=this,ended=!1,w=streams[0],r=streams[streams.length-1];r=r.readable?r:null,w=w.writable?w:null;var onclose=function(){streams[0].emit("error",new Error("stream was destroyed"))};return this.on("close",onclose),this.on("prefinish",function(){ended||self.cork()}),pump(streams,function(err){return self.removeListener("close",onclose),err?self.destroy(err):(ended=!0,void self.uncork())}),this.destroyed?onclose():(this.setWritable(w),void this.setReadable(r))},Pumpify};module.exports=define({destroy:!1}),module.exports.obj=define({destroy:!1,objectMode:!0,highWaterMark:16})},{duplexify:31,inherits:41,pump:87}],89:[function(require,module){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":90}],90:[function(require,module){"use strict";function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var processNextTick=require("process-nextick-args"),util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,list.head=p.next?p.next:list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,list.head=p.next?p.next:list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;l>i;i++)f(xs[i],i)}function indexOf(xs,x){for(var i=0,l=xs.length;l>i;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var Duplex,processNextTick=require("process-nextick-args"),isArray=require("isarray");Readable.ReadableState=ReadableState;var Stream,EElistenerCount=(require("events").EventEmitter,function(emitter,type){return emitter.listeners(type).length});!function(){try{Stream=require("stream")}catch(_){}finally{Stream||(Stream=require("events").EventEmitter)}}();var Buffer=require("buffer").Buffer,bufferShim=require("buffer-shims"),util=require("core-util-is");util.inherits=require("inherits");var debugUtil=require("util"),debug=void 0;debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function(){};var StringDecoder,BufferList=require("./internal/streams/BufferList");util.inherits(Readable,Stream),Readable.prototype.push=function(chunk,encoding){var state=this._readableState;return state.objectMode||"string"!=typeof chunk||(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=bufferShim.from(chunk,encoding),encoding="")),readableAddChunk(this,state,chunk,encoding,!1)},Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",!0)},Readable.prototype.isPaused=function(){return this._readableState.flowing===!1},Readable.prototype.setEncoding=function(enc){return StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this._readableState.decoder=new StringDecoder(enc),this._readableState.encoding=enc,this};var MAX_HWM=8388608;Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1;var ret=dest.write(chunk);!1!==ret||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;len>i;i++)dests[i].emit("unpipe",this);return this}var index=indexOf(state.pipes,dest);return-1===index?this:(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if("data"===ev)this._readableState.flowing!==!1&&this.resume();else if("readable"===ev){var state=this._readableState;state.endEmitted||state.readableListening||(state.readableListening=state.needReadable=!0,state.emittedReadable=!1,state.reading?state.length&&emitReadable(this,state):processNextTick(nReadingNextTick,this))}return res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!0,resume(this,state)),this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Readable.prototype.wrap=function(stream){var state=this._readableState,paused=!1,self=this;stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&self.push(chunk)}self.push(null)}),stream.on("data",function(chunk){if(debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),(!state.objectMode||null!==chunk&&void 0!==chunk)&&(state.objectMode||chunk&&chunk.length)){var ret=self.push(chunk);ret||(paused=!0,stream.pause())}});for(var i in stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i));var events=["error","close","destroy","pause","resume"];return forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))}),self._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},self},Readable._fromList=fromList}).call(this,require("_process"))},{"./_stream_duplex":90,"./internal/streams/BufferList":95,_process:85,buffer:9,"buffer-shims":8,"core-util-is":11,events:38,inherits:41,isarray:44,"process-nextick-args":84,"string_decoder/":124,util:6}],93:[function(require,module){"use strict";function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=!1;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null,ts.writecb=null,null!==data&&void 0!==data&&stream.push(data),cb(er); - -var rs=stream._readableState;rs.reading=!1,(rs.needReadable||rs.length-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream,internalUtil={deprecate:require("util-deprecate")};!function(){try{Stream=require("stream")}catch(_){}finally{Stream||(Stream=require("events").EventEmitter)}}();var Buffer=require("buffer").Buffer,bufferShim=require("buffer-shims");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return realHasInstance.call(this,object)?!0:object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=Buffer.isBuffer(chunk);return"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(this,require("_process"))},{"./_stream_duplex":90,_process:85,buffer:9,"buffer-shims":8,"core-util-is":11,events:38,inherits:41,"process-nextick-args":84,"util-deprecate":128}],95:[function(require,module){"use strict";function BufferList(){this.head=null,this.tail=null,this.length=0}var bufferShim=(require("buffer").Buffer,require("buffer-shims"));module.exports=BufferList,BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return bufferShim.alloc(0);if(1===this.length)return this.head.data;for(var ret=bufferShim.allocUnsafe(n>>>0),p=this.head,i=0;p;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},{buffer:9,"buffer-shims":8}],96:[function(require,module){module.exports=require("./readable").PassThrough},{"./readable":97}],97:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":90,"./lib/_stream_passthrough.js":91,"./lib/_stream_readable.js":92,"./lib/_stream_transform.js":93,"./lib/_stream_writable.js":94}],98:[function(require,module){module.exports=require("./readable").Transform},{"./readable":97}],99:[function(require,module){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":94}],100:[function(require,module){function throwsMessage(err){return"[Throws: "+(err?err.message:"?")+"]"}function safeGetValueFromPropertyOnObject(obj,property){if(hasProp.call(obj,property))try{return obj[property]}catch(err){return throwsMessage(err)}return obj[property]}function ensureProperties(obj){function visit(obj){if(null===obj||"object"!=typeof obj)return obj;if(-1!==seen.indexOf(obj))return"[Circular]";if(seen.push(obj),"function"==typeof obj.toJSON)try{return visit(obj.toJSON())}catch(err){return throwsMessage(err)}return Array.isArray(obj)?obj.map(visit):Object.keys(obj).reduce(function(result,prop){return result[prop]=visit(safeGetValueFromPropertyOnObject(obj,prop)),result},{})}var seen=[];return visit(obj)}var hasProp=Object.prototype.hasOwnProperty;module.exports=function(data){return JSON.stringify(ensureProperties(data))},module.exports.ensureProperties=ensureProperties},{}],101:[function(require,module){const DBEntries=require("./lib/delete.js").DBEntries,DBWriteCleanStream=require("./lib/replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./lib/replicate.js").DBWriteMergeStream,DocVector=require("./lib/delete.js").DocVector,IndexBatch=require("./lib/add.js").IndexBatch,Readable=require("stream").Readable,RecalibrateDB=require("./lib/delete.js").RecalibrateDB,bunyan=require("bunyan"),del=require("./lib/delete.js"),docProc=require("docproc"),leveldown=require("leveldown"),levelup=require("levelup"),pumpify=require("pumpify"),async=require("async");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){var Indexer={};Indexer.options=options;var q=async.queue(function(batch,callback){const s=new Readable({objectMode:!0});batch.batch.forEach(function(doc){s.push(doc)}),s.push(null),s.pipe(Indexer.defaultPipeline(batch.batchOps)).pipe(Indexer.add()).on("data",function(){}).on("end",function(){return callback()}).on("error",function(err){return callback(err)})},1);return Indexer.add=function(){return pumpify.obj(new IndexBatch(Indexer),new DBWriteMergeStream(options))},Indexer.concurrentAdd=function(batchOps,batch,done){q.push({batch:batch,batchOps:batchOps},function(err){done(err)})},Indexer.close=function(callback){options.indexes.close(function(err){for(;!options.indexes.isClosed();)options.log.debug("closing...");options.indexes.isClosed()&&(options.log.debug("closed..."),callback(err))})},Indexer.dbWriteStream=function(streamOps){return streamOps=Object.assign({},{merge:!0},streamOps),streamOps.merge?new DBWriteMergeStream(options):new DBWriteCleanStream(options)},Indexer.defaultPipeline=function(batchOptions){return batchOptions=Object.assign({},options,batchOptions),docProc.pipeline(batchOptions)},Indexer.deleteStream=function(options){return pumpify.obj(new DocVector(options),new DBEntries(options),new RecalibrateDB(options))},Indexer.deleter=function(docIds,done){const s=new Readable;docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)})},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},callback(err,Indexer)})};const getOptions=function(options,done){options=Object.assign({},{deletable:!0,batchSize:1e5,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\\n|[|' ><.,\-|]+|\\u0003/,stopwords:[],weight:0},options),options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes?done(null,options):levelup(options.indexPath||"si",{valueEncoding:"json",db:leveldown},function(err,db){options.indexes=db,done(err,options)})}},{"./lib/add.js":102,"./lib/delete.js":103,"./lib/replicate.js":104,async:4,bunyan:10,docproc:19,leveldown:58,levelup:71,pumpify:88,stream:122}],102:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),emitIndexKeys=function(s){for(var key in s.deltaIndex)s.push({key:key,value:s.deltaIndex[key]});s.deltaIndex={}},IndexBatch=function(indexer){this.indexer=indexer,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.indexer.options.keySeparator;var that=this;this.indexer.deleter([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.indexer.options.log.info("processing doc "+ingestedDoc.id),that.deltaIndex["DOCUMENT"+sep+ingestedDoc.id+sep]=ingestedDoc.stored;for(var fieldName in ingestedDoc.vector){that.deltaIndex["FIELD"+sep+fieldName]=fieldName;for(var token in ingestedDoc.vector[fieldName]){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token,dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id]),that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.deltaIndex["DOCUMENT-VECTOR"+sep+ingestedDoc.id+sep+fieldName+sep]=ingestedDoc.vector[fieldName]}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.indexer.options.batchSize&&(that.push({totalKeys:totalKeys}),that.indexer.options.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:122,util:131}],103:[function(require,module,exports){const util=require("util"),Transform=require("stream").Transform;exports.flush=function(options,callback){const sep=options.keySeparator;var deleteOps=[];options.indexes.createKeyStream({gte:"0",lte:sep}).on("data",function(data){deleteOps.push({type:"del",key:data})}).on("error",function(err){return options.log.error(err," failed to empty index"),callback(err)}).on("end",function(){options.indexes.batch(deleteOps,callback)})};const DocVector=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DocVector=DocVector,util.inherits(DocVector,Transform),DocVector.prototype._transform=function(docId,encoding,end){docId=JSON.parse(docId);const sep=this.options.keySeparator;var that=this;this.options.indexes.createReadStream({gte:"DOCUMENT-VECTOR"+sep+docId+sep,lte:"DOCUMENT-VECTOR"+sep+docId+sep+sep}).on("data",function(data){that.push(data)}).on("close",function(){return end()})};const DBEntries=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBEntries=DBEntries,util.inherits(DBEntries,Transform),DBEntries.prototype._transform=function(vector,encoding,end){const sep=this.options.keySeparator;var docId;for(var k in vector.value){docId=vector.key.split(sep)[1];var field=vector.key.split(sep)[2];this.push({key:"TF"+sep+field+sep+k,value:docId}),this.push({key:"DF"+sep+field+sep+k,value:docId})}return this.push({key:vector.key}),this.push({key:"DOCUMENT"+sep+docId+sep}),end()};const RecalibrateDB=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.RecalibrateDB=RecalibrateDB,util.inherits(RecalibrateDB,Transform),RecalibrateDB.prototype._transform=function(dbEntry,encoding,end){const sep=this.options.keySeparator;var that=this;this.options.indexes.get(dbEntry.key,function(err,value){err&&that.options.log.info(err),value||(value=[]);var docId=dbEntry.value,dbInstruction={};dbInstruction.key=dbEntry.key,dbEntry.key.substring(0,3)==="TF"+sep?(dbInstruction.value=value.filter(function(item){return item[1]!==docId}),dbInstruction.type=0===dbInstruction.value.length?"del":"put"):dbEntry.key.substring(0,3)==="DF"+sep?(value.splice(value.indexOf(docId),1),dbInstruction.value=value,dbInstruction.type=0===dbInstruction.value.length?"del":"put"):dbEntry.key.substring(0,9)==="DOCUMENT"+sep?dbInstruction.type="del":dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep&&(dbInstruction.type="del"),that.options.indexes.batch([dbInstruction],function(err){return end()})})}},{stream:122,util:131}],104:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),DBWriteMergeStream=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBWriteMergeStream=DBWriteMergeStream,util.inherits(DBWriteMergeStream,Transform),DBWriteMergeStream.prototype._transform=function(data,encoding,end){if(data.totalKeys)return this.push(data),end();const sep=this.options.keySeparator;var that=this;this.options.indexes.get(data.key,function(err,val){var newVal;newVal=data.key.substring(0,3)==="TF"+sep?data.value.concat(val||[]).sort(function(a,b){return a[0]===b[0]?b[1]-a[1]:b[0]-a[0]}):data.key.substring(0,3)==="DF"+sep?data.value.concat(val||[]).sort():"DOCUMENT-COUNT"===data.key?+val+(+data.value||0):data.value,that.options.indexes.put(data.key,newVal,function(err){that.push(data),end()})})};const DBWriteCleanStream=function(options){this.currentBatch=[],this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(DBWriteCleanStream,Transform),DBWriteCleanStream.prototype._transform=function(data,encoding,end){var that=this;this.currentBatch.push(data),this.currentBatch.length%this.options.batchSize===0?this.options.indexes.batch(this.currentBatch,function(err){that.push("indexing batch"),that.currentBatch=[],end()}):end()},DBWriteCleanStream.prototype._flush=function(end){var that=this;this.options.indexes.batch(this.currentBatch,function(err){that.push("remaining data indexed"),end()})},exports.DBWriteCleanStream=DBWriteCleanStream},{stream:122,util:131}],105:[function(require,module){const AvailableFields=require("./lib/AvailableFields.js").AvailableFields,CalculateBuckets=require("./lib/CalculateBuckets.js").CalculateBuckets,CalculateCategories=require("./lib/CalculateCategories.js").CalculateCategories,CalculateEntireResultSet=require("./lib/CalculateEntireResultSet.js").CalculateEntireResultSet,CalculateResultSetPerClause=require("./lib/CalculateResultSetPerClause.js").CalculateResultSetPerClause,CalculateTopScoringDocs=require("./lib/CalculateTopScoringDocs.js").CalculateTopScoringDocs,CalculateTotalHits=require("./lib/CalculateTotalHits.js").CalculateTotalHits,FetchDocsFromDB=require("./lib/FetchDocsFromDB.js").FetchDocsFromDB,FetchStoredDoc=require("./lib/FetchStoredDoc.js").FetchStoredDoc,GetIntersectionStream=require("./lib/GetIntersectionStream.js").GetIntersectionStream,MergeOrConditions=require("./lib/MergeOrConditions.js").MergeOrConditions,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,SortTopScoringDocs=require("./lib/SortTopScoringDocs.js").SortTopScoringDocs,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),initModule=function(err,Searcher,moduleReady){return Searcher.bucketStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateBuckets(Searcher.options,q.filter||{},q.buckets))},Searcher.categoryStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateCategories(Searcher.options,q))},Searcher.close=function(callback){Searcher.options.indexes.close(function(err){for(;!Searcher.options.indexes.isClosed();)Searcher.options.log.debug("closing...");Searcher.options.indexes.isClosed()&&(Searcher.options.log.debug("closed..."),callback(err))})},Searcher.availableFields=function(){const sep=Searcher.options.keySeparator;return Searcher.options.indexes.createReadStream({gte:"FIELD"+sep,lte:"FIELD"+sep+sep}).pipe(new AvailableFields(Searcher.options))},Searcher.get=function(docIDs){var s=new Readable({objectMode:!0});return docIDs.forEach(function(id){s.push(id)}),s.push(null),s.pipe(new FetchDocsFromDB(Searcher.options))},Searcher.fieldNames=function(){return Searcher.options.indexes.createReadStream({gte:"FIELD",lte:"FIELD"})},Searcher.match=function(q){return matcher.match(q,Searcher.options)},Searcher.dbReadStream=function(){return Searcher.options.indexes.createReadStream()},Searcher.search=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),q.sort?s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options)):s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreTopScoringDocsTFIDF(Searcher.options)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options))},Searcher.scan=function(q){q=siUtil.getQueryDefaults(q);var s=new Readable({objectMode:!0});return s.push("init"),s.push(null),s.pipe(new GetIntersectionStream(Searcher.options,siUtil.getKeySet(q.query[0].AND,Searcher.options.keySeparator))).pipe(new FetchDocsFromDB(Searcher.options))},Searcher.totalHits=function(q,callback){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateTotalHits(Searcher.options)).on("data",function(totalHits){return callback(null,totalHits)})},moduleReady(err,Searcher)},getOptions=function(options,done){var Searcher={};return Searcher.options=Object.assign({},{deletable:!0,fieldedSearch:!0,store:!0,indexPath:"si",keySeparator:"○",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:[]},options),Searcher.options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes?done(null,Searcher):void levelup(Searcher.options.indexPath||"si",{valueEncoding:"json"},function(err,db){return Searcher.options.indexes=db,done(err,Searcher)})};module.exports=function(givenOptions,moduleReady){getOptions(givenOptions,function(err,Searcher){initModule(err,Searcher,moduleReady)})}},{"./lib/AvailableFields.js":106,"./lib/CalculateBuckets.js":107,"./lib/CalculateCategories.js":108,"./lib/CalculateEntireResultSet.js":109,"./lib/CalculateResultSetPerClause.js":110,"./lib/CalculateTopScoringDocs.js":111,"./lib/CalculateTotalHits.js":112,"./lib/FetchDocsFromDB.js":113,"./lib/FetchStoredDoc.js":114,"./lib/GetIntersectionStream.js":115,"./lib/MergeOrConditions.js":116,"./lib/ScoreDocsOnField.js":117,"./lib/ScoreTopScoringDocsTFIDF.js":118,"./lib/SortTopScoringDocs.js":119,"./lib/matcher.js":120,"./lib/siUtil.js":121,bunyan:10,levelup:71,stream:122}],106:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),AvailableFields=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.AvailableFields=AvailableFields,util.inherits(AvailableFields,Transform),AvailableFields.prototype._transform=function(field,encoding,end){return this.push(field.key.split(this.options.keySeparator)[1]),end()}},{stream:122,util:131}],107:[function(require,module,exports){const _intersection=require("lodash.intersection"),_uniq=require("lodash.uniq"),Transform=require("stream").Transform,util=require("util"),CalculateBuckets=function(options,filter,requestedBuckets){this.buckets=requestedBuckets||[],this.filter=filter,this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateBuckets=CalculateBuckets,util.inherits(CalculateBuckets,Transform),CalculateBuckets.prototype._transform=function(mergedQueryClauses,encoding,end){const that=this,sep=this.options.keySeparator;var bucketsProcessed=0;that.buckets.forEach(function(bucket){const gte="DF"+sep+bucket.field+sep+bucket.gte,lte="DF"+sep+bucket.field+sep+bucket.lte+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){var IDSet=_intersection(data.value,mergedQueryClauses.set);IDSet.length>0&&(bucket.value=bucket.value||[],bucket.value=_uniq(bucket.value.concat(IDSet).sort()))}).on("close",function(){return bucket.set||(bucket.value=bucket.value.length),that.push(bucket),++bucketsProcessed===that.buckets.length?end():void 0})})}},{"lodash.intersection":75,"lodash.uniq":80,stream:122,util:131}],108:[function(require,module,exports){const _intersection=require("lodash.intersection"),Transform=require("stream").Transform,util=require("util"),CalculateCategories=function(options,q){var category=q.category||[];category.values=[],this.offset=+q.offset,this.pageSize=+q.pageSize,this.category=category,this.options=options,this.query=q.query,Transform.call(this,{objectMode:!0})};exports.CalculateCategories=CalculateCategories,util.inherits(CalculateCategories,Transform),CalculateCategories.prototype._transform=function(mergedQueryClauses,encoding,end){if(!this.category.field)return end(new Error("you need to specify a category"));const sep=this.options.keySeparator,that=this,gte="DF"+sep+this.category.field+sep,lte="DF"+sep+this.category.field+sep+sep;this.category.values=this.category.values||[];var i=this.offset+this.pageSize,j=0;const rs=that.options.indexes.createReadStream({gte:gte,lte:lte});rs.on("data",function(data){if(!(that.offset>j++)){var IDSet=_intersection(data.value,mergedQueryClauses.set);if(IDSet.length>0){var key=data.key.split(sep)[2],value=IDSet.length;that.category.set&&(value=IDSet);var result={key:key,value:value};if(1===that.query.length)try{that.query[0].AND[that.category.field].indexOf(key)>-1&&(result.filter=!0)}catch(e){}i-->that.offset?that.push(result):rs.destroy()}}}).on("close",function(){return end()})}},{"lodash.intersection":75,stream:122,util:131}],109:[function(require,module,exports){const Transform=require("stream").Transform,_union=require("lodash.union"),util=require("util"),CalculateEntireResultSet=function(options){this.options=options,this.setSoFar=[],Transform.call(this,{objectMode:!0})};exports.CalculateEntireResultSet=CalculateEntireResultSet,util.inherits(CalculateEntireResultSet,Transform),CalculateEntireResultSet.prototype._transform=function(queryClause,encoding,end){return this.setSoFar=_union(queryClause.set,this.setSoFar),end()},CalculateEntireResultSet.prototype._flush=function(end){return this.push({set:this.setSoFar}),end()}},{"lodash.union":79,stream:122,util:131}],110:[function(require,module,exports){const Transform=require("stream").Transform,_difference=require("lodash.difference"),_intersection=require("lodash.intersection"),_spread=require("lodash.spread"),siUtil=require("./siUtil.js"),util=require("util"),CalculateResultSetPerClause=function(options){ -this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateResultSetPerClause=CalculateResultSetPerClause,util.inherits(CalculateResultSetPerClause,Transform),CalculateResultSetPerClause.prototype._transform=function(queryClause,encoding,end){const sep=this.options.keySeparator,that=this,frequencies=[];var NOT=function(includeResults){const bigIntersect=_spread(_intersection);var include=bigIntersect(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,termFrequencies:frequencies,BOOST:queryClause.BOOST||0}),end();var i=0,excludeResults=[];siUtil.getKeySet(queryClause.NOT,sep).forEach(function(item){var excludeSet={};that.options.indexes.createReadStream({gte:item[0],lte:item[1]+sep}).on("data",function(data){for(var i=0;ib.id?-1:0}).reduce(function(merged,cur){var lastDoc=merged[merged.length-1];return 0===merged.length||cur.id!==lastDoc.id?merged.push(cur):cur.id===lastDoc.id&&(lastDoc.scoringCriteria=lastDoc.scoringCriteria.concat(cur.scoringCriteria)),merged},[]);return mergedResultSet.map(function(item){return item.scoringCriteria&&(item.score=item.scoringCriteria.reduce(function(acc,val){return{score:+acc.score+ +val.score}},{score:0}).score,item.score=item.score/item.scoringCriteria.length),item}),mergedResultSet.forEach(function(item){that.push(item)}),end()}},{stream:122,util:131}],117:[function(require,module,exports){const Transform=require("stream").Transform,_sortedIndexOf=require("lodash.sortedindexof"),util=require("util"),ScoreDocsOnField=function(options,seekLimit,sort){this.options=options,this.seekLimit=seekLimit,this.sort=sort,Transform.call(this,{objectMode:!0})};exports.ScoreDocsOnField=ScoreDocsOnField,util.inherits(ScoreDocsOnField,Transform),ScoreDocsOnField.prototype._transform=function(clauseSet,encoding,end){const sep=this.options.keySeparator,that=this,gte="TF"+sep+this.sort.field+sep,lte="TF"+sep+this.sort.field+sep+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){for(var i=0;ib.score?-2:a.idb.id?-1:0}:function(a,b){return a.score>b.score?2:a.scoreb.id?-1:0}),this.resultSet=this.resultSet.slice(this.q.offset,this.q.offset+this.q.pageSize),this.resultSet.forEach(function(hit){that.push(hit)}),end()}},{stream:122,util:131}],120:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatcherStream=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatcherStream,Transform),MatcherStream.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var results=[];const formatMatches=function(item){that.push("ID"===q.type?[item.key.split(sep)[2],item.value]:"count"===q.type?[item.key.split(sep)[2],item.value.length]:item.key.split(sep)[2])},sortResults=function(err){err&&console.log(err),results.sort(function(a,b){return b.value.length-a.value.length}).slice(0,q.limit).forEach(formatMatches),end()};this.options.indexes.createReadStream({start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep}).on("data",function(data){results.push(data)}).on("error",function(err){that.options.log.error("Oh my!",err)}).on("end",sortResults)},exports.match=function(q,options){var s=new Readable({objectMode:!0});return q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple"},q),q.beginsWith.length=byte?0:byte>>5===6?2:byte>>4===14?3:byte>>3===30?4:-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(i>j)return 0;var nb=utf8CheckByte(buf[j]);return nb>=0?(nb>0&&(self.lastNeed=nb-1),nb):--j=0?(nb>0&&(self.lastNeed=nb-2),nb):--j=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0))}function utf8CheckExtraBytes(self,buf,p){if(128!==(192&buf[0]))return self.lastNeed=0,"�".repeat(p);if(self.lastNeed>1&&buf.length>1){if(128!==(192&buf[1]))return self.lastNeed=1,"�".repeat(p+1);if(self.lastNeed>2&&buf.length>2&&128!==(192&buf[2]))return self.lastNeed=2,"�".repeat(p+2)}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�".repeat(this.lastTotal-this.lastNeed):r}function utf16Text(buf,i){if((buf.length-i)%2===0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&56319>=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("buffer").Buffer,bufferShim=require("buffer-shims"),isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return itokens.length)return[];for(var ngrams=[],i=0;i<=tokens.length-nGramLength;i++)ngrams.push(tokens.slice(i,i+nGramLength));if(ngrams=ngrams.sort(),1===ngrams.length)return[[ngrams[0],1]];for(var counter=1,lastToken=ngrams[0],vector=[],j=1;j=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){return str}function arrayToHash(array){var hash={};return array.forEach(function(val){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)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}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(0>recurseTimes)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;l>i;++i)output.push(hasOwnProperty(value,String(i))?formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),!0):"");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if(desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]},desc.get?str=desc.set?ctx.stylize("[Getter/Setter]","special"):ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(ctx.seen.indexOf(desc.value)<0?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),str.indexOf("\n")>-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,length=output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return length>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||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return 10>n?"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];len>i;x=args[++i])str+=isNull(x)||!isObject(x)?" "+x:" "+inspect(x);return str},exports.deprecate=function(fn,msg){function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);process.traceDeprecation?console.trace(msg):console.error(msg),warned=!0}return fn.apply(this,arguments)}if(isUndefined(global.process))return function(){return exports.deprecate(fn,msg).apply(this,arguments)};if(process.noDeprecation===!0)return fn;var warned=!1;return deprecated};var debugEnviron,debugs={};exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!debugs[set])if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":130,_process:85,inherits:129}],132:[function(require,module){function wrappy(fn,cb){function wrapper(){for(var args=new Array(arguments.length),i=0;i=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":134}],4:[function(require,module,exports){(function(process,global){!function(global,factory){"object"==typeof exports&&void 0!==module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory(global.async=global.async||{})}(this,function(exports){"use strict";function slice(arrayLike,start){start|=0;for(var newLen=Math.max(arrayLike.length-start,0),newArr=Array(newLen),idx=0;idx-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function noop(){}function once(fn){return function(){if(null!==fn){var callFn=fn;fn=null,callFn.apply(this,arguments)}}}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index-1&&value%1==0&&valuelength?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=length?array:baseSlice(array,start,end)}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function charsStartIndex(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index-1;);return index}function asciiToArray(string){return string.split("")}function hasUnicode(string){return reHasUnicode.test(string)}function unicodeToArray(string){return string.match(reUnicode)||[]}function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string)}function toString(value){return null==value?"":baseToString(value)}function trim(string,chars,guard){if((string=toString(string))&&(guard||void 0===chars))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars);return castSlice(strSymbols,charsStartIndex(strSymbols,chrSymbols),charsEndIndex(strSymbols,chrSymbols)+1).join("")}function parseParams(func){return func=func.toString().replace(STRIP_COMMENTS,""),func=func.match(FN_ARGS)[2].replace(" ",""),func=func?func.split(FN_ARG_SPLIT):[],func=func.map(function(arg){return trim(arg.replace(FN_ARG,""))})}function autoInject(tasks,callback){var newTasks={};baseForOwn(tasks,function(taskFn,key){function newTask(results,taskCb){var newArgs=arrayMap(params,function(name){return results[name]});newArgs.push(taskCb),wrapAsync(taskFn).apply(null,newArgs)}var params,fnIsAsync=isAsync(taskFn),hasNoDeps=!fnIsAsync&&1===taskFn.length||fnIsAsync&&0===taskFn.length;if(isArray(taskFn))params=taskFn.slice(0,-1),taskFn=taskFn[taskFn.length-1],newTasks[key]=params.concat(params.length>0?newTask:taskFn);else if(hasNoDeps)newTasks[key]=taskFn;else{if(params=parseParams(taskFn),0===taskFn.length&&!fnIsAsync&&0===params.length)throw new Error("autoInject task functions require explicit parameters.");fnIsAsync||params.pop(),newTasks[key]=params.concat(newTask)}}),auto(newTasks,callback)}function DLL(){this.head=this.tail=null,this.length=0}function setInitial(dll,node){dll.length=1,dll.head=dll.tail=node}function queue(worker,concurrency,payload){function _insert(data,insertAtFront,callback){if(null!=callback&&"function"!=typeof callback)throw new Error("task callback must be a function");if(q.started=!0,isArray(data)||(data=[data]),0===data.length&&q.idle())return setImmediate$1(function(){q.drain()});for(var i=0,l=data.length;i=0&&workersList.splice(index),task.callback.apply(task,arguments),null!=err&&q.error(err,task.data)}numRunning<=q.concurrency-q.buffer&&q.unsaturated(),q.idle()&&q.drain(),q.process()}}if(null==concurrency)concurrency=1;else if(0===concurrency)throw new Error("Concurrency must not be zero");var _worker=wrapAsync(worker),numRunning=0,workersList=[],isProcessing=!1,q={_tasks:new DLL,concurrency:concurrency,payload:payload,saturated:noop,unsaturated:noop,buffer:concurrency/4,empty:noop,drain:noop,error:noop,started:!1,paused:!1,push:function(data,callback){_insert(data,!1,callback)},kill:function(){q.drain=noop,q._tasks.empty()},unshift:function(data,callback){_insert(data,!0,callback)},remove:function(testFn){q._tasks.remove(testFn)},process:function(){if(!isProcessing){for(isProcessing=!0;!q.paused&&numRunning2&&(result=slice(arguments,1)),results[key]=result,callback(err)})},function(err){callback(err,results)})}function parallelLimit(tasks,callback){_parallel(eachOf,tasks,callback)}function parallelLimit$1(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)}function race(tasks,callback){if(callback=once(callback||noop),!isArray(tasks))return callback(new TypeError("First argument to race must be an array of functions"));if(!tasks.length)return callback();for(var i=0,l=tasks.length;ib?1:0}var _iteratee=wrapAsync(iteratee);map(coll,function(x,callback){_iteratee(x,function(err,criteria){ +if(err)return callback(err);callback(null,{value:x,criteria:criteria})})},function(err,results){if(err)return callback(err);callback(null,arrayMap(results.sort(comparator),baseProperty("value")))})}function timeout(asyncFn,milliseconds,info){var fn=wrapAsync(asyncFn);return initialParams(function(args,callback){function timeoutCallback(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)}var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(timeoutCallback,milliseconds),fn.apply(null,args)})}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function timeLimit(count,limit,iteratee,callback){var _iteratee=wrapAsync(iteratee);mapLimit(baseRange(0,count,1),limit,_iteratee,callback)}function transform(coll,accumulator,iteratee,callback){arguments.length<=3&&(callback=iteratee,iteratee=accumulator,accumulator=isArray(coll)?[]:{}),callback=once(callback||noop);var _iteratee=wrapAsync(iteratee);eachOf(coll,function(v,k,cb){_iteratee(accumulator,v,k,cb)},function(err){callback(err,accumulator)})}function tryEach(tasks,callback){var result,error=null;callback=callback||noop,eachSeries(tasks,function(task,callback){wrapAsync(task)(function(err,res){result=arguments.length>2?slice(arguments,1):res,error=err,callback(!err)})},function(){callback(error,result)})}function unmemoize(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}}function whilst(test,iteratee,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync(iteratee);if(!test())return callback(null);var next=function(err){if(err)return callback(err);if(test())return _iteratee(next);var args=slice(arguments,1);callback.apply(null,[null].concat(args))};_iteratee(next)}function until(test,iteratee,callback){whilst(function(){return!test.apply(this,arguments)},iteratee,callback)}var _defer,initialParams=function(fn){return function(){var args=slice(arguments),callback=args.pop();fn.call(this,args,callback)}},hasSetImmediate="function"==typeof setImmediate&&setImmediate,hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback;var setImmediate$1=wrap(_defer),supportsSymbol="function"==typeof Symbol,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol$1=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag$1=Symbol$1?Symbol$1.toStringTag:void 0,objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString,nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$1?Symbol$1.toStringTag:void 0,asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]",MAX_SAFE_INTEGER=9007199254740991,breakLoop={},iteratorSymbol="function"==typeof Symbol&&Symbol.iterator,getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()},argsTag="[object Arguments]",objectProto$3=Object.prototype,hasOwnProperty$2=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$2.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,MAX_SAFE_INTEGER$1=9007199254740991,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["[object Arguments]"]=typedArrayTags["[object Array]"]=typedArrayTags["[object ArrayBuffer]"]=typedArrayTags["[object Boolean]"]=typedArrayTags["[object DataView]"]=typedArrayTags["[object Date]"]=typedArrayTags["[object Error]"]=typedArrayTags["[object Function]"]=typedArrayTags["[object Map]"]=typedArrayTags["[object Number]"]=typedArrayTags["[object Object]"]=typedArrayTags["[object RegExp]"]=typedArrayTags["[object Set]"]=typedArrayTags["[object String]"]=typedArrayTags["[object WeakMap]"]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray,objectProto$2=Object.prototype,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty,eachOfGeneric=doLimit(eachOfLimit,1/0),eachOf=function(coll,iteratee,callback){(isArrayLike(coll)?eachOfArrayLike:eachOfGeneric)(coll,wrapAsync(iteratee),callback)},map=doParallel(_asyncMap),applyEach=applyEach$1(map),mapLimit=doParallelLimit(_asyncMap),mapSeries=doLimit(mapLimit,1),applyEachSeries=applyEach$1(mapSeries),apply=function(fn){var args=slice(arguments,1);return function(){var callArgs=slice(arguments);return fn.apply(null,args.concat(callArgs))}},baseFor=function(fromRight){return function(object,iteratee,keysFunc){for(var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;length--;){var key=props[fromRight?length:++index];if(!1===iteratee(iterable[key],key,iterable))break}return object}}(),auto=function(tasks,concurrency,callback){function enqueueTask(key,task){readyTasks.push(function(){runTask(key,task)})}function processQueue(){if(0===readyTasks.length&&0===runningTasks)return callback(null,results);for(;readyTasks.length&&runningTasks2&&(result=slice(arguments,1)),err){var safeResults={};baseForOwn(results,function(val,rkey){safeResults[rkey]=val}),safeResults[key]=result,hasError=!0,listeners=Object.create(null),callback(err,safeResults)}else results[key]=result,taskComplete(key)});runningTasks++;var taskFn=wrapAsync(task[task.length-1]);task.length>1?taskFn(results,taskCallback):taskFn(taskCallback)}}function getDependents(taskName){var result=[];return baseForOwn(tasks,function(task,key){isArray(task)&&baseIndexOf(task,taskName,0)>=0&&result.push(key)}),result}"function"==typeof concurrency&&(callback=concurrency,concurrency=null),callback=once(callback||noop);var keys$$1=keys(tasks),numTasks=keys$$1.length;if(!numTasks)return callback(null);concurrency||(concurrency=numTasks);var results={},runningTasks=0,hasError=!1,listeners=Object.create(null),readyTasks=[],readyToCheck=[],uncheckedDependencies={};baseForOwn(tasks,function(task,key){if(!isArray(task))return enqueueTask(key,[task]),void readyToCheck.push(key);var dependencies=task.slice(0,task.length-1),remainingDependencies=dependencies.length;if(0===remainingDependencies)return enqueueTask(key,task),void readyToCheck.push(key);uncheckedDependencies[key]=remainingDependencies,arrayEach(dependencies,function(dependencyName){if(!tasks[dependencyName])throw new Error("async.auto task `"+key+"` has a non-existent dependency `"+dependencyName+"` in "+dependencies.join(", "));addListener(dependencyName,function(){0===--remainingDependencies&&enqueueTask(key,task)})})}),function(){for(var currentTask,counter=0;readyToCheck.length;)currentTask=readyToCheck.pop(),counter++,arrayEach(getDependents(currentTask),function(dependent){0==--uncheckedDependencies[dependent]&&readyToCheck.push(dependent)});if(counter!==numTasks)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),processQueue()},symbolTag="[object Symbol]",INFINITY=1/0,symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0,reHasUnicode=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),rsCombo="[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",reOptMod="(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?",rsOptJoin="(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+rsOptJoin,rsSymbol="(?:"+["[^\\ud800-\\udfff]"+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,"[\\ud800-\\udfff]"].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reTrim=/^\s+|\s+$/g,FN_ARGS=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,FN_ARG_SPLIT=/,/,FN_ARG=/(=.+)?(\s*)$/,STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;DLL.prototype.removeLink=function(node){return node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev,node.prev=node.next=null,this.length-=1,node},DLL.prototype.empty=function(){for(;this.head;)this.shift();return this},DLL.prototype.insertAfter=function(node,newNode){newNode.prev=node,newNode.next=node.next,node.next?node.next.prev=newNode:this.tail=newNode,node.next=newNode,this.length+=1},DLL.prototype.insertBefore=function(node,newNode){newNode.prev=node.prev,newNode.next=node,node.prev?node.prev.next=newNode:this.head=newNode,node.prev=newNode,this.length+=1},DLL.prototype.unshift=function(node){this.head?this.insertBefore(this.head,node):setInitial(this,node)},DLL.prototype.push=function(node){this.tail?this.insertAfter(this.tail,node):setInitial(this,node)},DLL.prototype.shift=function(){return this.head&&this.removeLink(this.head)},DLL.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},DLL.prototype.toArray=function(){for(var arr=Array(this.length),curr=this.head,idx=0;idx=nextNode.priority;)nextNode=nextNode.next;for(var i=0,l=data.length;i0)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,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;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+16383));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;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&&("ucs2"===(encoding=String(encoding).toLowerCase())||"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)>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)>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)>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=65536+(leadSurrogate-55296<<10|codePoint-56320)}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 base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");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:function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}(),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)<0&&(start=0):start>len&&(start=len),end<0?(end+=len)<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]?-1*(255-this[offset]+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;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":return fastAndSafeJsonStringify(args[i++]);case"%%":return"%";default:return x}}),x=args[i];i=0,format('rotating-file stream "count" is not >= 0: %j in %j',this.count,this)),options.period){var period={hourly:"1h",daily:"1d",weekly:"1w",monthly:"1m",yearly:"1y"}[options.period]||options.period,m=/^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);if(!m)throw new Error(format('invalid period: "%s"',options.period));this.periodNum=Number(m[1]),this.periodScope=m[2]}else this.periodNum=1,this.periodScope="d";var lastModified=null;try{lastModified=fs.statSync(this.path).mtime.getTime()}catch(err){}var rotateAfterOpen=!1;if(lastModified){lastModified call rotate()"),this.rotate()):this._setupNextRot()},util.inherits(RotatingFileStream,EventEmitter),RotatingFileStream.prototype._debug=function(){return!1},RotatingFileStream.prototype._setupNextRot=function(){this.rotAt=this._calcRotTime(1),this._setRotationTimer()},RotatingFileStream.prototype._setRotationTimer=function(){var self=this,delay=this.rotAt-Date.now();delay>2147483647&&(delay=2147483647),this.timeout=setTimeout(function(){self._debug("_setRotationTimer timeout -> call rotate()"),self.rotate()},delay),"function"==typeof this.timeout.unref&&this.timeout.unref()},RotatingFileStream.prototype._calcRotTime=function(periodOffset){this._debug("_calcRotTime: %s%s",this.periodNum,this.periodScope);var d=new Date;this._debug(" now local: %s",d),this._debug(" now utc: %s",d.toISOString());var rotAt;switch(this.periodScope){case"ms":rotAt=this.rotAt?this.rotAt+this.periodNum*periodOffset:Date.now()+this.periodNum*periodOffset;break;case"h":rotAt=this.rotAt?this.rotAt+60*this.periodNum*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours()+periodOffset);break;case"d":rotAt=this.rotAt?this.rotAt+24*this.periodNum*60*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+periodOffset);break;case"w":if(this.rotAt)rotAt=this.rotAt+7*this.periodNum*24*60*60*1e3*periodOffset;else{var dayOffset=7-d.getUTCDay();periodOffset<1&&(dayOffset=-d.getUTCDay()),(periodOffset>1||periodOffset<-1)&&(dayOffset+=7*periodOffset),rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+dayOffset)}break;case"m":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+this.periodNum*periodOffset,1):Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+periodOffset,1);break;case"y":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear()+this.periodNum*periodOffset,0,1):Date.UTC(d.getUTCFullYear()+periodOffset,0,1);break;default:assert.fail(format('invalid period scope: "%s"',this.periodScope))}if(this._debug()){this._debug(" **rotAt**: %s (utc: %s)",rotAt,new Date(rotAt).toUTCString());var now=Date.now();this._debug(" now: %s (%sms == %smin == %sh to go)",now,rotAt-now,(rotAt-now)/1e3/60,(rotAt-now)/1e3/60/60)}return rotAt},RotatingFileStream.prototype.rotate=function(){function moves(){if(0===self.count||n<0)return finish();var before=self.path,after=self.path+"."+String(n);n>0&&(before+="."+String(n-1)),n-=1,fs.exists(before,function(exists){exists?(self._debug(" mv %s %s",before,after),mv(before,after,function(mvErr){mvErr?(self.emit("error",mvErr),finish()):moves()})):moves()})}function finish(){self._debug(" open %s",self.path),self.stream=fs.createWriteStream(self.path,{flags:"a",encoding:"utf8"});for(var q=self.rotQueue,len=q.length,i=0;iDate.now())return self._setRotationTimer();if(this._debug("rotate"),self.rotating)throw new TypeError("cannot start a rotation when already rotating");self.rotating=!0,self.stream.end();var n=this.count;!function(){var toDel=self.path+"."+String(n-1);0===n&&(toDel=self.path),n-=1,self._debug(" rm %s",toDel),fs.unlink(toDel,function(delErr){moves()})}()},RotatingFileStream.prototype.write=function(s){return this.rotating?(this.rotQueue.push(s),!1):this.stream.write(s)},RotatingFileStream.prototype.end=function(s){this.stream.end()},RotatingFileStream.prototype.destroy=function(s){this.stream.destroy()},RotatingFileStream.prototype.destroySoon=function(s){this.stream.destroySoon()}),util.inherits(RingBuffer,EventEmitter),RingBuffer.prototype.write=function(record){if(!this.writable)throw new Error("RingBuffer has been ended already");return this.records.push(record),this.records.length>this.limit&&this.records.shift(),!0},RingBuffer.prototype.end=function(){arguments.length>0&&this.write.apply(this,Array.prototype.slice.call(arguments)),this.writable=!1},RingBuffer.prototype.destroy=function(){this.writable=!1,this.emit("close")},RingBuffer.prototype.destroySoon=function(){this.destroy()},module.exports=Logger,module.exports.TRACE=10,module.exports.DEBUG=20,module.exports.INFO=INFO,module.exports.WARN=WARN,module.exports.ERROR=ERROR,module.exports.FATAL=60,module.exports.resolveLevel=resolveLevel,module.exports.levelFromName=levelFromName,module.exports.nameFromLevel=nameFromLevel,module.exports.VERSION="1.8.10",module.exports.LOG_VERSION=LOG_VERSION,module.exports.createLogger=function(options){return new Logger(options)},module.exports.RingBuffer=RingBuffer,module.exports.RotatingFileStream=RotatingFileStream,module.exports.safeCycles=safeCycles}).call(this,{isBuffer:require("../../is-buffer/index.js")},require("_process"))},{"../../is-buffer/index.js":42,_process:84,assert:3,events:37,fs:7,os:82,"safe-json-stringify":102,stream:125,util:134}],10:[function(require,module,exports){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}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"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)}function isError(e){return"[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)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":42}],11:[function(require,module,exports){function DeferredIterator(options){AbstractIterator.call(this,options),this._options=options,this._iterator=null,this._operations=[]}var util=require("util"),AbstractIterator=require("abstract-leveldown").AbstractIterator;util.inherits(DeferredIterator,AbstractIterator),DeferredIterator.prototype.setDb=function(db){var it=this._iterator=db.iterator(this._options);this._operations.forEach(function(op){it[op.method].apply(it,op.args)})},DeferredIterator.prototype._operation=function(method,args){if(this._iterator)return this._iterator[method].apply(this._iterator,args);this._operations.push({method:method,args:args})},"next end".split(" ").forEach(function(m){DeferredIterator.prototype["_"+m]=function(){this._operation(m,arguments)}}),module.exports=DeferredIterator},{"abstract-leveldown":16,util:134}],12:[function(require,module,exports){(function(Buffer,process){function DeferredLevelDOWN(location){AbstractLevelDOWN.call(this,"string"==typeof location?location:""),this._db=void 0,this._operations=[],this._iterators=[]}var util=require("util"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,DeferredIterator=require("./deferred-iterator");util.inherits(DeferredLevelDOWN,AbstractLevelDOWN),DeferredLevelDOWN.prototype.setDb=function(db){this._db=db,this._operations.forEach(function(op){db[op.method].apply(db,op.args)}),this._iterators.forEach(function(it){it.setDb(db)})},DeferredLevelDOWN.prototype._open=function(options,callback){return process.nextTick(callback)},DeferredLevelDOWN.prototype._operation=function(method,args){if(this._db)return this._db[method].apply(this._db,args);this._operations.push({method:method,args:args})},"put get del batch approximateSize".split(" ").forEach(function(m){DeferredLevelDOWN.prototype["_"+m]=function(){this._operation(m,arguments)}}),DeferredLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},DeferredLevelDOWN.prototype._iterator=function(options){if(this._db)return this._db.iterator.apply(this._db,arguments);var it=new DeferredIterator(options);return this._iterators.push(it),it},module.exports=DeferredLevelDOWN,module.exports.DeferredIterator=DeferredIterator}).call(this,{isBuffer:require("../is-buffer/index.js")},require("_process"))},{"../is-buffer/index.js":42,"./deferred-iterator":11,_process:84,"abstract-leveldown":16,util:134}],13:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:84}],14:[function(require,module,exports){(function(process){function AbstractIterator(db){this.db=db,this._ended=!1,this._nexting=!1}AbstractIterator.prototype.next=function(callback){var self=this;if("function"!=typeof callback)throw new Error("next() requires a callback argument");return self._ended?callback(new Error("cannot call next() after end()")):self._nexting?callback(new Error("cannot call next() before previous next() has completed")):(self._nexting=!0,"function"==typeof self._next?self._next(function(){self._nexting=!1,callback.apply(null,arguments)}):void process.nextTick(function(){self._nexting=!1,callback()}))},AbstractIterator.prototype.end=function(callback){if("function"!=typeof callback)throw new Error("end() requires a callback argument");return this._ended?callback(new Error("end() already called on iterator")):(this._ended=!0,"function"==typeof this._end?this._end(callback):void process.nextTick(callback))},module.exports=AbstractIterator}).call(this,require("_process"))},{_process:84}],15:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location,this.status="new"}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){var self=this,oldStatus=this.status;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");"object"!=typeof options&&(options={}),options.createIfMissing=0!=options.createIfMissing,options.errorIfExists=!!options.errorIfExists,"function"==typeof this._open?(this.status="opening",this._open(options,function(err){if(err)return self.status=oldStatus,callback(err);self.status="open",callback()})):(this.status="open",process.nextTick(callback))},AbstractLevelDOWN.prototype.close=function(callback){var self=this,oldStatus=this.status;if("function"!=typeof callback)throw new Error("close() requires a callback argument");"function"==typeof this._close?(this.status="closing",this._close(function(err){if(err)return self.status=oldStatus,callback(err);self.status="closed",callback()})):(this.status="closed",process.nextTick(callback))},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),options.asBuffer=0!=options.asBuffer,"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),null==value||this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"==typeof array&&(callback=array),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));options&&"object"==typeof options||(options={});for(var e,err,i=0,l=array.length;i<.,\-|]+|\\u0003/},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{separator:options.separator},options.fieldOptions[fieldName]);"[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.tokenised[fieldName]=doc.normalised[fieldName]:doc.tokenised[fieldName]=doc.normalised[fieldName].split(fieldOptions.separator)}return this.push(doc),end()}},{stream:125,util:134}],30:[function(require,module,exports){(function(process,Buffer){var stream=require("readable-stream"),eos=require("end-of-stream"),inherits=require("inherits"),shift=require("stream-shift"),SIGNAL_FLUSH=new Buffer([0]),onuncork=function(self,fn){self._corked?self.once("uncork",fn):fn() +},destroyer=function(self,end){return function(err){err?self.destroy("premature close"===err.message?null:err):end&&!self._ended&&self.end()}},end=function(ws,fn){return ws?ws._writableState&&ws._writableState.finished?fn():ws._writableState?ws.end(fn):(ws.end(),void fn()):fn()},toStreams2=function(rs){return new stream.Readable({objectMode:!0,highWaterMark:16}).wrap(rs)},Duplexify=function(writable,readable,opts){if(!(this instanceof Duplexify))return new Duplexify(writable,readable,opts);stream.Duplex.call(this,opts),this._writable=null,this._readable=null,this._readable2=null,this._forwardDestroy=!opts||!1!==opts.destroy,this._forwardEnd=!opts||!1!==opts.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,writable&&this.setWritable(writable),readable&&this.setReadable(readable)};inherits(Duplexify,stream.Duplex),Duplexify.obj=function(writable,readable,opts){return opts||(opts={}),opts.objectMode=!0,opts.highWaterMark=16,new Duplexify(writable,readable,opts)},Duplexify.prototype.cork=function(){1==++this._corked&&this.emit("cork")},Duplexify.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},Duplexify.prototype.setWritable=function(writable){if(this._unwrite&&this._unwrite(),this.destroyed)return void(writable&&writable.destroy&&writable.destroy());if(null===writable||!1===writable)return void this.end();var self=this,unend=eos(writable,{writable:!0,readable:!1},destroyer(this,this._forwardEnd)),ondrain=function(){var ondrain=self._ondrain;self._ondrain=null,ondrain&&ondrain()},clear=function(){self._writable.removeListener("drain",ondrain),unend()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=clear,this.uncork()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)return void(readable&&readable.destroy&&readable.destroy());if(null===readable||!1===readable)return this.push(null),void this.resume();var self=this,unend=eos(readable,{writable:!1,readable:!0},destroyer(this)),onreadable=function(){self._forward()},onend=function(){self.push(null)},clear=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()};this._drained=!0,this._readable=readable,this._readable2=readable._readableState?readable:toStreams2(readable),this._readable2.on("readable",onreadable),this._readable2.on("end",onend),this._unread=clear,this._forward()},Duplexify.prototype._read=function(){this._drained=!0,this._forward()},Duplexify.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){this._forwarding=!0;for(var data;this._drained&&null!==(data=shift(this._readable2));)this.destroyed||(this._drained=this.push(data));this._forwarding=!1}},Duplexify.prototype.destroy=function(err){if(!this.destroyed){this.destroyed=!0;var self=this;process.nextTick(function(){self._destroy(err)})}},Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null,ondrain?ondrain(err):this.emit("error",err)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},Duplexify.prototype._write=function(data,enc,cb){return this.destroyed?cb():this._corked?onuncork(this,this._write.bind(this,data,enc,cb)):data===SIGNAL_FLUSH?this._finish(cb):this._writable?void(!1===this._writable.write(data)?this._ondrain=cb:cb()):cb()},Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend"),onuncork(this,function(){end(self._forwardEnd&&self._writable,function(){!1===self._writableState.prefinished&&(self._writableState.prefinished=!0),self.emit("prefinish"),onuncork(self,cb)})})},Duplexify.prototype.end=function(data,enc,cb){return"function"==typeof data?this.end(null,null,data):"function"==typeof enc?this.end(data,null,enc):(this._ended=!0,data&&this.write(data),this._writableState.ending||this.write(SIGNAL_FLUSH),stream.Writable.prototype.end.call(this,cb))},module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:84,buffer:8,"end-of-stream":31,inherits:40,"readable-stream":98,"stream-shift":126}],31:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback()},onend=function(){readable=!1,writable||callback()},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback(new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:32}],32:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0})})},{wrappy:135}],33:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback.call(stream)},onend=function(){readable=!1,writable||callback.call(stream)},onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback.call(stream,new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:81}],34:[function(require,module,exports){function init(type,message,cause){prr(this,{type:type,name:type,cause:"string"!=typeof message?message:cause,message:message&&"string"!=typeof message?message.message:message},"ewr")}function CustomError(message,cause){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),init.call(this,"CustomError",message,cause)}function createError(errno,type,proto){var err=function(message,cause){init.call(this,type,message,cause),"FilesystemError"==type&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(errno.errno[this.cause.errno]?errno.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return err.prototype=proto?new proto:new CustomError,err}var prr=require("prr");CustomError.prototype=new Error,module.exports=function(errno){var ce=function(type,proto){return createError(errno,type,proto)};return{CustomError:CustomError,FilesystemError:ce("FilesystemError"),createError:ce}}},{prr:36}],35:[function(require,module,exports){var all=module.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];module.exports.errno={},module.exports.code={},all.forEach(function(error){module.exports.errno[error.errno]=error,module.exports.code[error.code]=error}),module.exports.custom=require("./custom")(module.exports),module.exports.create=module.exports.custom.createError},{"./custom":34}],36:[function(require,module,exports){!function(name,context,definition){void 0!==module&&module.exports?module.exports=definition():context.prr=definition()}(0,this,function(){var setProperty="function"==typeof Object.defineProperty?function(obj,key,options){return Object.defineProperty(obj,key,options),obj}:function(obj,key,options){return obj[key]=options.value,obj},makeOptions=function(value,options){var oo="object"==typeof options,os=!oo&&"string"==typeof options,op=function(p){return oo?!!options[p]:!!os&&options.indexOf(p[0])>-1};return{enumerable:op("enumerable"),configurable:op("configurable"),writable:op("writable"),value:value}};return function(obj,key,value,options){var k;if(options=makeOptions(value,options),"object"==typeof key){for(k in key)Object.hasOwnProperty.call(key,k)&&(options.value=key[k],setProperty(obj,k,options));return obj}return setProperty(obj,key,options)}})},{}],37:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if((er=arguments[1])instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;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)}},{}],38:[function(require,module,exports){!function(name,definition,global){"use strict";"function"==typeof define?define(definition):void 0!==module&&module.exports?module.exports=definition():global.IDBStore=definition()}(0,function(){"use strict";function mixin(target,source){var name,s;for(name in source)(s=source[name])!==empty[name]&&s!==target[name]&&(target[name]=s);return target}function hasVersionError(errorEvent){return"error"in errorEvent.target?"VersionError"==errorEvent.target.error.name:"errorCode"in errorEvent.target&&12==errorEvent.target.errorCode}var defaultErrorHandler=function(error){throw error},defaultSuccessHandler=function(){},defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:!0,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]},IDBStore=function(kwArgs,onStoreReady){void 0===onStoreReady&&"function"==typeof kwArgs&&(onStoreReady=kwArgs),"[object Object]"!=Object.prototype.toString.call(kwArgs)&&(kwArgs={});for(var key in defaults)this[key]=void 0!==kwArgs[key]?kwArgs[key]:defaults[key];this.dbName=this.storePrefix+this.storeName,this.dbVersion=parseInt(this.dbVersion,10)||1,onStoreReady&&(this.onStoreReady=onStoreReady);var env="object"==typeof window?window:self,availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0],this.idb=env[this.implementation],this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange,this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"},this.openDB()},proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion),preventSuccessCallback=!1;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent))this.onError(new Error("The version number provided is lower than the existing one."));else{var error;if(errorEvent.target.error)error=errorEvent.target.error;else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;"errorCode"in errorEvent.target&&(errorMessage+=" with error code "+errorEvent.target.errorCode),error=new Error(errorMessage)}this.onError(error)}}.bind(this),openRequest.onsuccess=function(event){if(!preventSuccessCallback){if(this.db)return void this.onStoreReady();if(this.db=event.target.result,"string"==typeof this.db.version)return void this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));if(!this.db.objectStoreNames.contains(this.storeName))return void this.onError(new Error("Object store couldn't be created."));var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName)return preventSuccessCallback=!0,void this.onError(new Error("Cannot create index: No index name given."));if(this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(preventSuccessCallback=!0,this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else preventSuccessCallback=!0,this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))},this),existingIndexes.length&&(preventSuccessCallback=!0,this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),preventSuccessCallback||this.onStoreReady()}}.bind(this),openRequest.onupgradeneeded=function(event){if(this.db=event.target.result,this.db.objectStoreNames.contains(this.storeName))this.store=event.target.transaction.objectStore(this.storeName);else{var optionalParameters={autoIncrement:this.autoIncrement};null!==this.keyPath&&(optionalParameters.keyPath=this.keyPath),this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(indexName||(preventSuccessCallback=!0,this.onError(new Error("Cannot create index: No index name given."))),this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(this.store.deleteIndex(indexName),this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})},this),existingIndexes.length&&existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess,deleteRequest.onerror=onError}else onError(new Error("Browser does not support IndexedDB deleteDatabase!"))},put:function(key,value,onSuccess,onError){null!==this.keyPath&&(onError=onSuccess,onSuccess=value,value=key),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var putRequest,hasSuccess=!1,result=null,putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);return putTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},putTransaction.onabort=onError,putTransaction.onerror=onError,null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=putTransaction.objectStore(this.storeName).put(value)):putRequest=putTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},putRequest.onerror=onError,putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getTransaction.onabort=onError,getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);return getRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getRequest.onerror=onError,getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},removeTransaction.onabort=onError,removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName).delete(key);return deleteRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},deleteRequest.onerror=onError,removeTransaction},batch:function(dataArray,onSuccess,onError){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),"[object Array]"!=Object.prototype.toString.call(dataArray))onError(new Error("dataArray argument must be of type Array."));else if(0===dataArray.length)return onSuccess(!0);var count=dataArray.length,called=!1,hasSuccess=!1,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(hasSuccess)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(){0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(operation){var type=operation.type,key=operation.key,value=operation.value,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err,type,key))};if("remove"==type){var deleteRequest=batchTransaction.objectStore(this.storeName).delete(key);deleteRequest.onsuccess=onItemSuccess,deleteRequest.onerror=onItemError}else if("put"==type){var putRequest;null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=batchTransaction.objectStore(this.storeName).put(value)):putRequest=batchTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError}},this),batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}});return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){"function"==typeof options&&(onSuccess=options,onError=onSuccess,options={}),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),options||(options={}),"[object Array]"!=Object.prototype.toString.call(dataArray)&&onError(new Error("dataArray argument must be of type Array."));var keyField=options.keyField||this.keyPath,count=dataArray.length,called=!1,hasSuccess=!1,index=0,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){hasSuccess?onSuccess(dataArray):onError(!1)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){dataArray[index++][keyField]=event.target.result,0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(record){var putRequest,key=record.key,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err))};null!==this.keyPath?(this._addIdPropertyIfNeeded(record),putRequest=batchTransaction.objectStore(this.storeName).put(record)):putRequest=batchTransaction.objectStore(this.storeName).put(record,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError},this),batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),arrayType||(arrayType="sparse"),"[object Array]"!=Object.prototype.toString.call(keyArray))onError(new Error("keyArray argument must be of type Array."));else if(0===keyArray.length)return onSuccess([]);var data=[],count=keyArray.length,called=!1,hasSuccess=!1,result=null,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){event.target.result||"dense"==arrayType?data.push(event.target.result):"sparse"==arrayType&&data.length++,0===--count&&(called=!0,hasSuccess=!0,result=data)};return keyArray.forEach(function(key){var onItemError=function(err){called=!0,result=err,onError(err),batchTransaction.abort()},getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=onItemError},this),batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY),store=getAllTransaction.objectStore(this.storeName);return store.getAll?this._getAllNative(getAllTransaction,store,onSuccess,onError):this._getAllCursor(getAllTransaction,store,onSuccess,onError),getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)}, +getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;cursor?(all.push(cursor.value),cursor.continue()):(hasSuccess=!0,result=all)},cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},clearTransaction.onabort=onError,clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();return clearRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},clearRequest.onerror=onError,clearTransaction},_addIdPropertyIfNeeded:function(dataObj){void 0===dataObj[this.keyPath]&&(dataObj[this.keyPath]=this._insertIdCount+++Date.now())},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name,indexData.unique=!!indexData.unique,indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){return["keyPath","unique","multiEntry"].every(function(key){if("multiEntry"==key&&void 0===actual[key]&&!1===expected[key])return!0;if("keyPath"==key&&"[object Array]"==Object.prototype.toString.call(expected[key])){var exp=expected.keyPath,act=actual.keyPath;if("string"==typeof act)return exp.toString()==act;if("function"!=typeof act.contains&&"function"!=typeof act.indexOf)return!1;if(act.length!==exp.length)return!1;for(var i=0,m=exp.length;i>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:1/0*(s?-1:1);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}},{}],40:[function(require,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}},{}],41:[function(require,module,exports){var Readable=require("stream").Readable;exports.getIntersectionStream=function(sortedSets){for(var s=new Readable,i=0,ii=[],k=0;ksortedSets[i+1][ii[i+1]])ii[i+1]++;else if(i+2=sortedSets[k].length&&(finished=!0);i=0}return s.push(null),s}},{stream:125}],42:[function(require,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],43:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],44:[function(require,module,exports){function isBuffer(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}var Buffer=require("buffer").Buffer;module.exports=isBuffer},{buffer:8}],45:[function(require,module,exports){function Codec(opts){this.opts=opts||{},this.encodings=encodings}var encodings=require("./lib/encodings");module.exports=Codec,Codec.prototype._encoding=function(encoding){return"string"==typeof encoding&&(encoding=encodings[encoding]),encoding||(encoding=encodings.id),encoding},Codec.prototype._keyEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&batchOpts.keyEncoding||opts&&opts.keyEncoding||this.opts.keyEncoding)},Codec.prototype._valueEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&(batchOpts.valueEncoding||batchOpts.encoding)||opts&&(opts.valueEncoding||opts.encoding)||this.opts.valueEncoding||this.opts.encoding)},Codec.prototype.encodeKey=function(key,opts,batchOpts){return this._keyEncoding(opts,batchOpts).encode(key)},Codec.prototype.encodeValue=function(value,opts,batchOpts){return this._valueEncoding(opts,batchOpts).encode(value)},Codec.prototype.decodeKey=function(key,opts){return this._keyEncoding(opts).decode(key)},Codec.prototype.decodeValue=function(value,opts){return this._valueEncoding(opts).decode(value)},Codec.prototype.encodeBatch=function(ops,opts){var self=this;return ops.map(function(_op){var op={type:_op.type,key:self.encodeKey(_op.key,opts,_op)};return self.keyAsBuffer(opts,_op)&&(op.keyEncoding="binary"),_op.prefix&&(op.prefix=_op.prefix),"value"in _op&&(op.value=self.encodeValue(_op.value,opts,_op),self.valueAsBuffer(opts,_op)&&(op.valueEncoding="binary")),op})};var ltgtKeys=["lt","gt","lte","gte","start","end"];Codec.prototype.encodeLtgt=function(ltgt){var self=this,ret={};return Object.keys(ltgt).forEach(function(key){ret[key]=ltgtKeys.indexOf(key)>-1?self.encodeKey(ltgt[key],ltgt):ltgt[key]}),ret},Codec.prototype.createStreamDecoder=function(opts){var self=this;return opts.keys&&opts.values?function(key,value){return{key:self.decodeKey(key,opts),value:self.decodeValue(value,opts)}}:opts.keys?function(key){return self.decodeKey(key,opts)}:opts.values?function(_,value){return self.decodeValue(value,opts)}:function(){}},Codec.prototype.keyAsBuffer=function(opts){return this._keyEncoding(opts).buffer},Codec.prototype.valueAsBuffer=function(opts){return this._valueEncoding(opts).buffer}},{"./lib/encodings":46}],46:[function(require,module,exports){(function(Buffer){function identity(value){return value}function isBinary(data){return void 0===data||null===data||Buffer.isBuffer(data)}exports.utf8=exports["utf-8"]={encode:function(data){return isBinary(data)?data:String(data)},decode:identity,buffer:!1,type:"utf8"},exports.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},exports.binary={encode:function(data){return isBinary(data)?data:new Buffer(data)},decode:identity,buffer:!0,type:"binary"},exports.id={encode:function(data){return data},decode:function(data){return data},buffer:!1,type:"id"},["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"].forEach(function(type){exports[type]={encode:function(data){return isBinary(data)?data:new Buffer(data,type)},decode:function(buffer){return buffer.toString(type)},buffer:!0,type:type}})}).call(this,require("buffer").Buffer)},{buffer:8}],47:[function(require,module,exports){var createError=require("errno").create,LevelUPError=createError("LevelUPError"),NotFoundError=createError("NotFoundError",LevelUPError);NotFoundError.prototype.notFound=!0,NotFoundError.prototype.status=404,module.exports={LevelUPError:LevelUPError,InitializationError:createError("InitializationError",LevelUPError),OpenError:createError("OpenError",LevelUPError),ReadError:createError("ReadError",LevelUPError),WriteError:createError("WriteError",LevelUPError),NotFoundError:NotFoundError,EncodingError:createError("EncodingError",LevelUPError)}},{errno:35}],48:[function(require,module,exports){function ReadStream(iterator,options){if(!(this instanceof ReadStream))return new ReadStream(iterator,options);Readable.call(this,extend(options,{objectMode:!0})),this._iterator=iterator,this._destroyed=!1,this._decoder=null,options&&options.decoder&&(this._decoder=options.decoder),this.on("end",this._cleanup.bind(this))}var inherits=require("inherits"),Readable=require("readable-stream").Readable,extend=require("xtend"),EncodingError=require("level-errors").EncodingError;module.exports=ReadStream,inherits(ReadStream,Readable),ReadStream.prototype._read=function(){var self=this;this._destroyed||this._iterator.next(function(err,key,value){if(!self._destroyed){if(err)return self.emit("error",err);if(void 0===key&&void 0===value)self.push(null);else{if(!self._decoder)return self.push({key:key,value:value});try{var value=self._decoder(key,value)}catch(err){return self.emit("error",new EncodingError(err)),void self.push(null)}self.push(value)}}})},ReadStream.prototype.destroy=ReadStream.prototype._cleanup=function(){var self=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(err){if(err)return self.emit("error",err);self.emit("close")}))}},{inherits:40,"level-errors":47,"readable-stream":55,xtend:136}],49:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],50:[function(require,module,exports){(function(process){function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys},util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable),function(xs,f){for(var i=0,l=xs.length;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:isNaN(n)||util.isNull(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return util.isBuffer(chunk)||util.isString(chunk)||util.isNullOrUndefined(chunk)||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,util.isNull(ret)&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),util.isNull(ret)||this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),!1===dest.write(chunk)&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i1){for(var cbs=[],c=0;c=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:8}],57:[function(require,module,exports){(function(Buffer){function Level(location){if(!(this instanceof Level))return new Level(location);if(!location)throw new Error("constructor requires at least a location argument");this.IDBOptions={},this.location=location}module.exports=Level;var IDB=require("idb-wrapper"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,util=require("util"),Iterator=require("./iterator"),isBuffer=require("isbuffer"),xtend=require("xtend"),toBuffer=require("typedarray-to-buffer");util.inherits(Level,AbstractLevelDOWN),Level.prototype._open=function(options,callback){var self=this,idbOpts={storeName:this.location,autoIncrement:!1,keyPath:null,onStoreReady:function(){callback&&callback(null,self.idb)},onError:function(err){callback&&callback(err)}};xtend(idbOpts,options),this.IDBOptions=idbOpts,this.idb=new IDB(idbOpts)},Level.prototype._get=function(key,options,callback){this.idb.get(key,function(value){if(void 0===value)return callback(new Error("NotFound"));var asBuffer=!0;return!1===options.asBuffer&&(asBuffer=!1),options.raw&&(asBuffer=!1),asBuffer&&(value=value instanceof Uint8Array?toBuffer(value):new Buffer(String(value))),callback(null,value,key)},callback)},Level.prototype._del=function(id,options,callback){this.idb.remove(id,callback,callback)},Level.prototype._put=function(key,value,options,callback){value instanceof ArrayBuffer&&(value=toBuffer(new Uint8Array(value)));var obj=this.convertEncoding(key,value,options);Buffer.isBuffer(obj.value)&&("function"==typeof value.toArrayBuffer?obj.value=new Uint8Array(value.toArrayBuffer()):obj.value=new Uint8Array(value)),this.idb.put(obj.key,obj.value,function(){callback()},callback)},Level.prototype.convertEncoding=function(key,value,options){if(options.raw)return{key:key,value:value};if(value){var stringed=value.toString();"NaN"===stringed&&(value="NaN")}var valEnc=options.valueEncoding,obj={key:key,value:value};return!value||valEnc&&"binary"===valEnc||"object"!=typeof obj.value&&(obj.value=stringed),obj},Level.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),new Iterator(this.idb,options)},Level.prototype._batch=function(array,options,callback){var i,k,copiedOp,currentOp,modified=[];if(0===array.length)return setTimeout(callback,0);for(i=0;i0&&this._count++>=this._limit&&(shouldCall=!1),shouldCall&&this.callback(!1,cursor.key,cursor.value),cursor&&cursor.continue()},Iterator.prototype._next=function(callback){return callback?this._keyRangeError?callback():(this._started||(this.createIterator(),this._started=!0),void(this.callback=callback)):new Error("next() requires a callback argument")}},{"abstract-leveldown":61,ltgt:79,util:134}],59:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;if(err=this._db._checkKeyValue(value,"value",this._db._isBuffer))throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:84}],60:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{_process:84,dup:14}],61:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");if("object"!=typeof options&&(options={}),"function"==typeof this._open)return this._open(options,callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.close=function(callback){if("function"!=typeof callback)throw new Error("close() requires a callback argument");if("function"==typeof this._close)return this._close(callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(err=this._checkKeyValue(value,"value",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));"object"!=typeof options&&(options={});for(var e,err,i=0,l=array.length;i2?arguments[2]:null;if(l===+l)for(i=0;i=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],66:[function(require,module,exports){!function(){"use strict";var keysShim,has=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,forEach=require("./foreach"),isArgs=require("./isArguments"),hasDontEnumBug=!{toString:null}.propertyIsEnumerable("toString"),hasProtoEnumBug=function(){}.propertyIsEnumerable("prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];keysShim=function(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toString.call(object),isArguments=isArgs(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");if(isArguments)forEach(object,function(value){theKeys.push(value)});else{var name,skipProto=hasProtoEnumBug&&isFunction;for(name in object)skipProto&&"prototype"===name||!has.call(object,name)||theKeys.push(name)}if(hasDontEnumBug){var ctor=object.constructor,skipConstructor=ctor&&ctor.prototype===object;forEach(dontEnums,function(dontEnum){skipConstructor&&"constructor"===dontEnum||!has.call(object,dontEnum)||theKeys.push(dontEnum)})}return theKeys},module.exports=keysShim}()},{"./foreach":63,"./isArguments":65}],67:[function(require,module,exports){function hasKeys(source){return null!==source&&("object"==typeof source||"function"==typeof source)}module.exports=hasKeys},{}],68:[function(require,module,exports){function extend(){for(var target={},i=0;i-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 getMapData(map,key){var data=map.__data__;return isKeyable(key)?data["string"==typeof key?"string":"hash"]:data.map}function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function toSource(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+""}catch(e){}}return""}function eq(value,other){return value===other||value!==value&&other!==other}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 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 difference=function(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}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=120&&array.length>=120)?new SetCache(othIndex&&array):void 0}array=arrays[0];var index=-1,seen=caches[0];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}var HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,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.*?")+"$"),splice=arrayProto.splice,nativeMax=Math.max,nativeMin=Math.min,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 intersection=function(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}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;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&COMPARE_UNORDERED_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 null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function stubArray(){return[]}function stubFalse(){return!1}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",asyncTag="[object AsyncFunction]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",nullTag="[object Null]",objectTag="[object Object]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",undefinedTag="[object Undefined]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,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["[object WeakMap]"]=!1;var 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&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),nativeObjectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Buffer=moduleExports?root.Buffer:void 0,Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),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;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 getSymbols=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray,getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&"[object Promise]"!=getTag(Promise.resolve())||Set&&getTag(new Set)!=setTag||WeakMap&&"[object WeakMap]"!=getTag(new WeakMap))&&(getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return"[object Promise]";case setCtorString:return setTag;case weakMapCtorString:return"[object WeakMap]"}return result});var isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isBuffer=nativeIsBuffer||stubFalse,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray;module.exports=isEqual}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],75:[function(require,module,exports){function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if("number"==typeof value&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){for(;low>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?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=length?array:baseSlice(array,start,end)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=void 0===start?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}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))===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 FUNC_ERROR_TEXT="Expected a function",INFINITY=1/0,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString,nativeMax=Math.max;module.exports=spread},{}],77:[function(require,module,exports){(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 baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=!0,result=[],seen=result;if(comparator)isCommon=!1,includes=arrayIncludesWith;else if(length>=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__",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]==1/0?function(values){return new Set(values)}:noop,union=function(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}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){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexb?1:0};var lowerBoundKey=exports.lowerBoundKey=function(range){return hasKey(range,"gt")||hasKey(range,"gte")||hasKey(range,"min")||(range.reverse?hasKey(range,"end"):hasKey(range,"start"))||void 0},lowerBound=exports.lowerBound=function(range,def){var k=lowerBoundKey(range);return k?range[k]:def},lowerBoundInclusive=exports.lowerBoundInclusive=function(range){return!has(range,"gt")},upperBoundInclusive=exports.upperBoundInclusive=function(range){return!has(range,"lt")},lowerBoundExclusive=exports.lowerBoundExclusive=function(range){return!lowerBoundInclusive(range)},upperBoundExclusive=exports.upperBoundExclusive=function(range){return!upperBoundInclusive(range)},upperBoundKey=exports.upperBoundKey=function(range){return hasKey(range,"lt")||hasKey(range,"lte")||hasKey(range,"max")||(range.reverse?hasKey(range,"start"):hasKey(range,"end"))||void 0},upperBound=exports.upperBound=function(range,def){var k=upperBoundKey(range);return k?range[k]:def};exports.start=function(range,def){return range.reverse?upperBound(range,def):lowerBound(range,def)},exports.end=function(range,def){return range.reverse?lowerBound(range,def):upperBound(range,def)},exports.startInclusive=function(range){return range.reverse?upperBoundInclusive(range):lowerBoundInclusive(range)},exports.endInclusive=function(range){return range.reverse?lowerBoundInclusive(range):upperBoundInclusive(range)},exports.toLtgt=function(range,_range,map,lower,upper){_range=_range||{},map=map||id;var defaults=arguments.length>3,lb=exports.lowerBoundKey(range),ub=exports.upperBoundKey(range);return lb?"gt"===lb?_range.gt=map(range.gt,!1):_range.gte=map(range[lb],!1):defaults&&(_range.gte=map(lower,!1)),ub?"lt"===ub?_range.lt=map(range.lt,!0):_range.lte=map(range[ub],!0):defaults&&(_range.lte=map(upper,!0)),null!=range.reverse&&(_range.reverse=!!range.reverse),has(_range,"max")&&delete _range.max,has(_range,"min")&&delete _range.min,has(_range,"start")&&delete _range.start,has(_range,"end")&&delete _range.end,_range},exports.contains=function(range,key,compare){compare=compare||exports.compare;var lb=lowerBound(range);if(isDef(lb)){var cmp=compare(key,lb);if(cmp<0||0===cmp&&lowerBoundExclusive(range))return!1}var ub=upperBound(range);if(isDef(ub)){var cmp=compare(key,ub);if(cmp>0||0===cmp&&upperBoundExclusive(range))return!1}return!0},exports.filter=function(range,compare){return function(key){return exports.contains(range,key,compare)}}}).call(this,{isBuffer:require("../is-buffer/index.js")})},{"../is-buffer/index.js":42}],80:[function(require,module,exports){const getNGramsOfMultipleLengths=function(inputArray,nGramLengths){var outputArray=[];return nGramLengths.forEach(function(len){outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,len))}),outputArray},getNGramsOfRangeOfLengths=function(inputArray,nGramLengths){for(var outputArray=[],i=nGramLengths.gte;i<=nGramLengths.lte;i++)outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,i));return outputArray},getNGramsOfSingleLength=function(inputArray,nGramLength){return inputArray.slice(nGramLength-1).map(function(item,i){return inputArray.slice(i,i+nGramLength)})};exports.ngram=function(inputArray,nGramLength){switch(nGramLength.constructor){case Array: +return getNGramsOfMultipleLengths(inputArray,nGramLength);case Number:return getNGramsOfSingleLength(inputArray,nGramLength);case Object:return getNGramsOfRangeOfLengths(inputArray,nGramLength)}}},{}],81:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:135}],82:[function(require,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],83:[function(require,module,exports){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i1)for(var i=1;i0,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)};module.exports=pump},{"end-of-stream":33,fs:6,once:81}],87:[function(require,module,exports){var pump=require("pump"),inherits=require("inherits"),Duplexify=require("duplexify"),toArray=function(args){return args.length?Array.isArray(args[0])?args[0]:Array.prototype.slice.call(args):[]},define=function(opts){var Pumpify=function(){var streams=toArray(arguments);if(!(this instanceof Pumpify))return new Pumpify(streams);Duplexify.call(this,null,null,opts),streams.length&&this.setPipeline(streams)};return inherits(Pumpify,Duplexify),Pumpify.prototype.setPipeline=function(){var streams=toArray(arguments),self=this,ended=!1,w=streams[0],r=streams[streams.length-1];r=r.readable?r:null,w=w.writable?w:null;var onclose=function(){streams[0].emit("error",new Error("stream was destroyed"))};if(this.on("close",onclose),this.on("prefinish",function(){ended||self.cork()}),pump(streams,function(err){if(self.removeListener("close",onclose),err)return self.destroy(err);ended=!0,self.uncork()}),this.destroyed)return onclose();this.setWritable(w),this.setReadable(r)},Pumpify};module.exports=define({destroy:!1}),module.exports.obj=define({destroy:!1,objectMode:!0,highWaterMark:16})},{duplexify:30,inherits:40,pump:86}],88:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":89}],89:[function(require,module,exports){"use strict";function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var processNextTick=require("process-nextick-args"),objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v0?("string"==typeof chunk||Object.getPrototypeOf(chunk)===Buffer.prototype||state.objectMode||(chunk=_uint8ArrayToBuffer(chunk)),addToFront?state.endEmitted?stream.emit("error",new Error("stream.unshift() after end event")):addChunk(stream,state,chunk,!0):state.ended?stream.emit("error",new Error("stream.push() after EOF")):(state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1))):addToFront||(state.reading=!1)}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0===(n-=nb)){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0===(n-=nb)){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1,!1!==dest.write(chunk)||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=_isUint8Array(chunk)&&!state.objectMode;return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){this.end(),cb(err)}}).call(this,require("_process"))},{"./_stream_duplex":89,"./internal/streams/destroy":95,"./internal/streams/stream":96,_process:84,"core-util-is":10,inherits:40,"process-nextick-args":83,"safe-buffer":101,"util-deprecate":131}],94:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function copyBuffer(src,target,offset){src.copy(target,offset)}var Buffer=require("safe-buffer").Buffer;module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return Buffer.alloc(0);if(1===this.length)return this.head.data;for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret},BufferList}()},{"safe-buffer":101}],95:[function(require,module,exports){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed)return void(cb?cb(err):!err||this._writableState&&this._writableState.errorEmitted||processNextTick(emitErrorNT,this,err));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?(processNextTick(emitErrorNT,_this,err),_this._writableState&&(_this._writableState.errorEmitted=!0)):cb&&cb(err)})}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":83}],96:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:37}],97:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":98}],98:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":89,"./lib/_stream_passthrough.js":90,"./lib/_stream_readable.js":91,"./lib/_stream_transform.js":92,"./lib/_stream_writable.js":93}],99:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":98}],100:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":93}],101:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:8}],102:[function(require,module,exports){function throwsMessage(err){return"[Throws: "+(err?err.message:"?")+"]"}function safeGetValueFromPropertyOnObject(obj,property){if(hasProp.call(obj,property))try{return obj[property]}catch(err){return throwsMessage(err)}return obj[property]}function ensureProperties(obj){function visit(obj){if(null===obj||"object"!=typeof obj)return obj;if(-1!==seen.indexOf(obj))return"[Circular]";if(seen.push(obj),"function"==typeof obj.toJSON)try{return visit(obj.toJSON())}catch(err){return throwsMessage(err)}return Array.isArray(obj)?obj.map(visit):Object.keys(obj).reduce(function(result,prop){return result[prop]=visit(safeGetValueFromPropertyOnObject(obj,prop)),result},{})}var seen=[];return visit(obj)}var hasProp=Object.prototype.hasOwnProperty;module.exports=function(data){return JSON.stringify(ensureProperties(data))},module.exports.ensureProperties=ensureProperties},{}],103:[function(require,module,exports){const DBEntries=require("./lib/delete.js").DBEntries,DBWriteCleanStream=require("./lib/replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./lib/replicate.js").DBWriteMergeStream,DocVector=require("./lib/delete.js").DocVector,IndexBatch=require("./lib/add.js").IndexBatch,Readable=require("stream").Readable,RecalibrateDB=require("./lib/delete.js").RecalibrateDB,bunyan=require("bunyan"),del=require("./lib/delete.js"),docProc=require("docproc"),levelup=require("levelup"),pumpify=require("pumpify"),async=require("async");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){var Indexer={};Indexer.options=options;var q=async.queue(function(batch,done){var s;"add"===batch.operation?(s=new Readable({objectMode:!0}),batch.batch.forEach(function(doc){s.push(doc)}),s.push(null),s.pipe(Indexer.defaultPipeline(batch.batchOps)).pipe(Indexer.add()).on("finish",function(){return done()}).on("error",function(err){return done(err)})):"delete"===batch.operation&&(s=new Readable,batch.docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)}))},1);return Indexer.add=function(){return pumpify.obj(new IndexBatch(Indexer),new DBWriteMergeStream(options))},Indexer.concurrentAdd=function(batchOps,batch,done){q.push({batch:batch,batchOps:batchOps,operation:"add"},function(err){done(err)})},Indexer.concurrentDel=function(docIds,done){q.push({docIds:docIds,operation:"delete"},function(err){done(err)})},Indexer.close=function(callback){options.indexes.close(function(err){for(;!options.indexes.isClosed();)options.log.debug("closing...");options.indexes.isClosed()&&(options.log.debug("closed..."),callback(err))})},Indexer.dbWriteStream=function(streamOps){return streamOps=Object.assign({},{merge:!0},streamOps),streamOps.merge?new DBWriteMergeStream(options):new DBWriteCleanStream(options)},Indexer.defaultPipeline=function(batchOptions){return batchOptions=Object.assign({},options,batchOptions),docProc.pipeline(batchOptions)},Indexer.deleteStream=function(options){return pumpify.obj(new DocVector(options),new DBEntries(options),new RecalibrateDB(options))},Indexer.deleter=function(docIds,done){const s=new Readable;docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)})},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{deletable:!0,batchSize:1e3,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0},options),options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)done(null,options);else{const leveldown=require("leveldown");levelup(options.indexPath||"si",{valueEncoding:"json",db:leveldown},function(err,db){options.indexes=db,done(err,options)})}}},{"./lib/add.js":104,"./lib/delete.js":105,"./lib/replicate.js":106,async:4,bunyan:9,docproc:18,leveldown:57,levelup:70,pumpify:87,stream:125}],104:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),emitIndexKeys=function(s){for(var key in s.deltaIndex)s.push({key:key,value:s.deltaIndex[key]});s.deltaIndex={}},IndexBatch=function(indexer){this.indexer=indexer,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.indexer.options.keySeparator;var that=this;this.indexer.deleter([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.indexer.options.log.info("processing doc "+ingestedDoc.id),that.deltaIndex["DOCUMENT"+sep+ingestedDoc.id+sep]=ingestedDoc.stored;for(var fieldName in ingestedDoc.vector){that.deltaIndex["FIELD"+sep+fieldName]=fieldName;for(var token in ingestedDoc.vector[fieldName]){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token,dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id]),that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.deltaIndex["DOCUMENT-VECTOR"+sep+ingestedDoc.id+sep+fieldName+sep]=ingestedDoc.vector[fieldName]}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.indexer.options.batchSize&&(that.push({totalKeys:totalKeys}),that.indexer.options.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:125,util:134}],105:[function(require,module,exports){const util=require("util"),Transform=require("stream").Transform;exports.flush=function(options,callback){const sep=options.keySeparator;var deleteOps=[];options.indexes.createKeyStream({gte:"0",lte:sep}).on("data",function(data){deleteOps.push({type:"del",key:data})}).on("error",function(err){return options.log.error(err," failed to empty index"),callback(err)}).on("end",function(){options.indexes.batch(deleteOps,callback)})};const DocVector=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DocVector=DocVector,util.inherits(DocVector,Transform),DocVector.prototype._transform=function(docId,encoding,end){docId=JSON.parse(docId);const sep=this.options.keySeparator;var that=this;this.options.indexes.createReadStream({gte:"DOCUMENT-VECTOR"+sep+docId+sep,lte:"DOCUMENT-VECTOR"+sep+docId+sep+sep}).on("data",function(data){that.push(data)}).on("close",function(){return end()})};const DBEntries=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBEntries=DBEntries,util.inherits(DBEntries,Transform),DBEntries.prototype._transform=function(vector,encoding,end){const sep=this.options.keySeparator;var docId;for(var k in vector.value){docId=vector.key.split(sep)[1];var field=vector.key.split(sep)[2];this.push({key:"TF"+sep+field+sep+k,value:docId}),this.push({key:"DF"+sep+field+sep+k,value:docId})}return this.push({key:vector.key}),this.push({key:"DOCUMENT"+sep+docId+sep}),end()};const RecalibrateDB=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.RecalibrateDB=RecalibrateDB,util.inherits(RecalibrateDB,Transform),RecalibrateDB.prototype._transform=function(dbEntry,encoding,end){const sep=this.options.keySeparator;var that=this;this.options.indexes.get(dbEntry.key,function(err,value){err&&that.options.log.info(err),value||(value=[]);var docId=dbEntry.value,dbInstruction={};dbInstruction.key=dbEntry.key,dbEntry.key.substring(0,3)==="TF"+sep?(dbInstruction.value=value.filter(function(item){return item[1]!==docId}),0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,3)==="DF"+sep?(value.splice(value.indexOf(docId),1),dbInstruction.value=value,0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,9)==="DOCUMENT"+sep?dbInstruction.type="del":dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep&&(dbInstruction.type="del"),that.options.indexes.batch([dbInstruction],function(err){return end()})})}},{stream:125,util:134}],106:[function(require,module,exports){const Transform=require("stream").Transform,Writable=require("stream").Writable,util=require("util"),DBWriteMergeStream=function(options){this.options=options,Writable.call(this,{objectMode:!0})};exports.DBWriteMergeStream=DBWriteMergeStream,util.inherits(DBWriteMergeStream,Writable),DBWriteMergeStream.prototype._write=function(data,encoding,end){if(data.totalKeys)return end();const sep=this.options.keySeparator;var that=this;this.options.indexes.get(data.key,function(err,val){var newVal;newVal=data.key.substring(0,3)==="TF"+sep?data.value.concat(val||[]).sort(function(a,b){return a[0]b[0]?-1:a[1]b[1]?-1:0}):data.key.substring(0,3)==="DF"+sep?data.value.concat(val||[]).sort():"DOCUMENT-COUNT"===data.key?+val+(+data.value||0):data.value,that.options.indexes.put(data.key,newVal,function(err){end()})})};const DBWriteCleanStream=function(options){this.currentBatch=[],this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(DBWriteCleanStream,Transform),DBWriteCleanStream.prototype._transform=function(data,encoding,end){var that=this;this.currentBatch.push(data),this.currentBatch.length%this.options.batchSize==0?this.options.indexes.batch(this.currentBatch,function(err){that.push("indexing batch"),that.currentBatch=[],end()}):end()},DBWriteCleanStream.prototype._flush=function(end){var that=this;this.options.indexes.batch(this.currentBatch,function(err){that.push("remaining data indexed"),end()})},exports.DBWriteCleanStream=DBWriteCleanStream},{stream:125,util:134}],107:[function(require,module,exports){const AvailableFields=require("./lib/AvailableFields.js").AvailableFields,CalculateBuckets=require("./lib/CalculateBuckets.js").CalculateBuckets,CalculateCategories=require("./lib/CalculateCategories.js").CalculateCategories,CalculateEntireResultSet=require("./lib/CalculateEntireResultSet.js").CalculateEntireResultSet,CalculateResultSetPerClause=require("./lib/CalculateResultSetPerClause.js").CalculateResultSetPerClause,CalculateTopScoringDocs=require("./lib/CalculateTopScoringDocs.js").CalculateTopScoringDocs,CalculateTotalHits=require("./lib/CalculateTotalHits.js").CalculateTotalHits,Classify=require("./lib/Classify.js").Classify,FetchDocsFromDB=require("./lib/FetchDocsFromDB.js").FetchDocsFromDB,FetchStoredDoc=require("./lib/FetchStoredDoc.js").FetchStoredDoc,GetIntersectionStream=require("./lib/GetIntersectionStream.js").GetIntersectionStream,MergeOrConditions=require("./lib/MergeOrConditions.js").MergeOrConditions,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,SortTopScoringDocs=require("./lib/SortTopScoringDocs.js").SortTopScoringDocs,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),initModule=function(err,Searcher,moduleReady){return Searcher.bucketStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateBuckets(Searcher.options,q.filter||{},q.buckets))},Searcher.categoryStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateCategories(Searcher.options,q))},Searcher.classify=function(ops){return new Classify(Searcher,ops)},Searcher.close=function(callback){Searcher.options.indexes.close(function(err){for(;!Searcher.options.indexes.isClosed();)Searcher.options.log.debug("closing...");Searcher.options.indexes.isClosed()&&(Searcher.options.log.debug("closed..."),callback(err))})},Searcher.availableFields=function(){const sep=Searcher.options.keySeparator;return Searcher.options.indexes.createReadStream({gte:"FIELD"+sep,lte:"FIELD"+sep+sep}).pipe(new AvailableFields(Searcher.options))},Searcher.get=function(docIDs){var s=new Readable({objectMode:!0});return docIDs.forEach(function(id){s.push(id)}),s.push(null),s.pipe(new FetchDocsFromDB(Searcher.options))},Searcher.fieldNames=function(){return Searcher.options.indexes.createReadStream({gte:"FIELD",lte:"FIELD"})},Searcher.match=function(q){return matcher.match(q,Searcher.options)},Searcher.dbReadStream=function(){return Searcher.options.indexes.createReadStream()},Searcher.search=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),q.sort?s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options)):s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreTopScoringDocsTFIDF(Searcher.options)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options))},Searcher.scan=function(q){q=siUtil.getQueryDefaults(q);var s=new Readable({objectMode:!0});return s.push("init"),s.push(null),s.pipe(new GetIntersectionStream(Searcher.options,siUtil.getKeySet(q.query[0].AND,Searcher.options.keySeparator))).pipe(new FetchDocsFromDB(Searcher.options))},Searcher.totalHits=function(q,callback){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateTotalHits(Searcher.options)).on("data",function(totalHits){return callback(null,totalHits)})},moduleReady(err,Searcher)},getOptions=function(options,done){var Searcher={};if(Searcher.options=Object.assign({},{deletable:!0,fieldedSearch:!0,store:!0,indexPath:"si",keySeparator:"○",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:[]},options),Searcher.options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)return done(null,Searcher);levelup(Searcher.options.indexPath||"si",{valueEncoding:"json"},function(err,db){return Searcher.options.indexes=db,done(err,Searcher)})};module.exports=function(givenOptions,moduleReady){getOptions(givenOptions,function(err,Searcher){initModule(err,Searcher,moduleReady)})}},{"./lib/AvailableFields.js":108,"./lib/CalculateBuckets.js":109,"./lib/CalculateCategories.js":110,"./lib/CalculateEntireResultSet.js":111,"./lib/CalculateResultSetPerClause.js":112,"./lib/CalculateTopScoringDocs.js":113,"./lib/CalculateTotalHits.js":114,"./lib/Classify.js":115,"./lib/FetchDocsFromDB.js":116,"./lib/FetchStoredDoc.js":117,"./lib/GetIntersectionStream.js":118,"./lib/MergeOrConditions.js":119,"./lib/ScoreDocsOnField.js":120,"./lib/ScoreTopScoringDocsTFIDF.js":121,"./lib/SortTopScoringDocs.js":122,"./lib/matcher.js":123,"./lib/siUtil.js":124,bunyan:9,levelup:70,stream:125}],108:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),AvailableFields=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.AvailableFields=AvailableFields,util.inherits(AvailableFields,Transform),AvailableFields.prototype._transform=function(field,encoding,end){return this.push(field.key.split(this.options.keySeparator)[1]),end()}},{stream:125,util:134}],109:[function(require,module,exports){const _intersection=require("lodash.intersection"),_uniq=require("lodash.uniq"),Transform=require("stream").Transform,util=require("util"),CalculateBuckets=function(options,filter,requestedBuckets){this.buckets=requestedBuckets||[],this.filter=filter,this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateBuckets=CalculateBuckets,util.inherits(CalculateBuckets,Transform),CalculateBuckets.prototype._transform=function(mergedQueryClauses,encoding,end){const that=this,sep=this.options.keySeparator;var bucketsProcessed=0;that.buckets.forEach(function(bucket){const gte="DF"+sep+bucket.field+sep+bucket.gte,lte="DF"+sep+bucket.field+sep+bucket.lte+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){var IDSet=_intersection(data.value,mergedQueryClauses.set);IDSet.length>0&&(bucket.value=bucket.value||[],bucket.value=_uniq(bucket.value.concat(IDSet).sort()))}).on("close",function(){if(bucket.set||(bucket.value=bucket.value.length),that.push(bucket),++bucketsProcessed===that.buckets.length)return end()})})}},{"lodash.intersection":73,"lodash.uniq":78,stream:125,util:134}],110:[function(require,module,exports){const _intersection=require("lodash.intersection"),Transform=require("stream").Transform,util=require("util"),CalculateCategories=function(options,q){var category=q.category||[];category.values=[],this.offset=+q.offset,this.pageSize=+q.pageSize,this.category=category,this.options=options,this.query=q.query,Transform.call(this,{objectMode:!0})};exports.CalculateCategories=CalculateCategories,util.inherits(CalculateCategories,Transform),CalculateCategories.prototype._transform=function(mergedQueryClauses,encoding,end){if(!this.category.field)return end(new Error("you need to specify a category"));const sep=this.options.keySeparator,that=this,gte="DF"+sep+this.category.field+sep,lte="DF"+sep+this.category.field+sep+sep;this.category.values=this.category.values||[];var i=this.offset+this.pageSize,j=0;const rs=that.options.indexes.createReadStream({gte:gte,lte:lte});rs.on("data",function(data){if(!(that.offset>j++)){var IDSet=_intersection(data.value,mergedQueryClauses.set);if(IDSet.length>0){var key=data.key.split(sep)[2],value=IDSet.length;that.category.set&&(value=IDSet);var result={key:key,value:value};if(1===that.query.length)try{that.query[0].AND[that.category.field].indexOf(key)>-1&&(result.filter=!0)}catch(e){}i-- >that.offset?that.push(result):rs.destroy()}}}).on("close",function(){return end()})}},{"lodash.intersection":73,stream:125,util:134}],111:[function(require,module,exports){const Transform=require("stream").Transform,_union=require("lodash.union"),util=require("util"),CalculateEntireResultSet=function(options){this.options=options,this.setSoFar=[],Transform.call(this,{objectMode:!0})};exports.CalculateEntireResultSet=CalculateEntireResultSet,util.inherits(CalculateEntireResultSet,Transform),CalculateEntireResultSet.prototype._transform=function(queryClause,encoding,end){return this.setSoFar=_union(queryClause.set,this.setSoFar),end()},CalculateEntireResultSet.prototype._flush=function(end){return this.push({set:this.setSoFar}),end()}},{"lodash.union":77,stream:125,util:134}],112:[function(require,module,exports){const Transform=require("stream").Transform,_difference=require("lodash.difference"),_intersection=require("lodash.intersection"),_spread=require("lodash.spread"),siUtil=require("./siUtil.js"),util=require("util"),CalculateResultSetPerClause=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateResultSetPerClause=CalculateResultSetPerClause,util.inherits(CalculateResultSetPerClause,Transform),CalculateResultSetPerClause.prototype._transform=function(queryClause,encoding,end){const sep=this.options.keySeparator,that=this,frequencies=[];var NOT=function(includeResults){const bigIntersect=_spread(_intersection);var include=bigIntersect(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,termFrequencies:frequencies,BOOST:queryClause.BOOST||0}),end();var i=0,excludeResults=[];siUtil.getKeySet(queryClause.NOT,sep).forEach(function(item){var excludeSet={};that.options.indexes.createReadStream({gte:item[0],lte:item[1]+sep}).on("data",function(data){for(var i=0;ib.id?-1:0}).reduce(function(merged,cur){var lastDoc=merged[merged.length-1];return 0===merged.length||cur.id!==lastDoc.id?merged.push(cur):cur.id===lastDoc.id&&(lastDoc.scoringCriteria=lastDoc.scoringCriteria.concat(cur.scoringCriteria)),merged},[]);return mergedResultSet.map(function(item){return item.scoringCriteria&&(item.score=item.scoringCriteria.reduce(function(acc,val){return{score:+acc.score+ +val.score}},{score:0}).score,item.score=item.score/item.scoringCriteria.length),item}),mergedResultSet.forEach(function(item){that.push(item)}),end()}},{stream:125,util:134}],120:[function(require,module,exports){const Transform=require("stream").Transform,_sortedIndexOf=require("lodash.sortedindexof"),util=require("util"),ScoreDocsOnField=function(options,seekLimit,sort){this.options=options,this.seekLimit=seekLimit,this.sort=sort,Transform.call(this,{objectMode:!0})};exports.ScoreDocsOnField=ScoreDocsOnField,util.inherits(ScoreDocsOnField,Transform),ScoreDocsOnField.prototype._transform=function(clauseSet,encoding,end){const sep=this.options.keySeparator,that=this,gte="TF"+sep+this.sort.field+sep,lte="TF"+sep+this.sort.field+sep+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){for(var i=0;ib.score?-2:a.idb.id?-1:0}):this.resultSet=this.resultSet.sort(function(a,b){return a.score>b.score?2:a.scoreb.id?-1:0}),this.resultSet=this.resultSet.slice(this.q.offset,this.q.offset+this.q.pageSize),this.resultSet.forEach(function(hit){that.push(hit)}),end()}},{stream:125,util:134}],123:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatcherStream=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatcherStream,Transform),MatcherStream.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var results=[];this.options.indexes.createReadStream({start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep}).on("data",function(data){results.push(data)}).on("error",function(err){that.options.log.error("Oh my!",err)}).on("end",function(){return results.sort(function(a,b){return b.value.length-a.value.length}).slice(0,q.limit).forEach(function(item){var m={};switch(q.type){case"ID":m={token:item.key.split(sep)[2],documents:item.value};break;case"count":m={token:item.key.split(sep)[2],documentCount:item.value.length};break;default:m=item.key.split(sep)[2]}that.push(m)}),end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple"},q),q.beginsWith.length>5==6?2:byte>>4==14?3:byte>>3==30?4:-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=0?(nb>0&&(self.lastNeed=nb-1),nb):--j=0?(nb>0&&(self.lastNeed=nb-2),nb):--j=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"�".repeat(p);if(self.lastNeed>1&&buf.length>1){if(128!=(192&buf[1]))return self.lastNeed=1,"�".repeat(p+1);if(self.lastNeed>2&&buf.length>2&&128!=(192&buf[2]))return self.lastNeed=2,"�".repeat(p+2)}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�".repeat(this.lastTotal-this.lastNeed):r}function utf16Text(buf,i){if((buf.length-i)%2==0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch((encoding=""+encoding)&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(void 0===(r=this.fillLast(buf)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return itokens.length)return[];for(var ngrams=[],i=0;i<=tokens.length-nGramLength;i++)ngrams.push(tokens.slice(i,i+nGramLength));if(ngrams=ngrams.sort(),1===ngrams.length)return[[ngrams[0],1]];for(var counter=1,lastToken=ngrams[0],vector=[],j=1;j=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];ii;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return y>x?-1:x>y?1:0}function isBuffer(b){return global.Buffer&&"function"==typeof global.Buffer.isBuffer?global.Buffer.isBuffer(b):!(null==b||!b._isBuffer)}function pToString(obj){return Object.prototype.toString.call(obj)}function isView(arrbuf){return isBuffer(arrbuf)?!1:"function"!=typeof global.ArrayBuffer?!1:"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(arrbuf):arrbuf?arrbuf instanceof DataView?!0:arrbuf.buffer&&arrbuf.buffer instanceof ArrayBuffer?!0:!1:!1}function getName(func){if(util.isFunction(func)){if(functionsHaveNames)return func.name;var str=func.toString(),match=str.match(regex);return match&&match[1]}}function truncate(s,n){return"string"==typeof s?s.length=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return Error.isPrototypeOf(expected)?!1:expected.call({},actual)===!0}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert["throws"]=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":131}],4:[function(require,module,exports){(function(process,global){!function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory(global.async=global.async||{})}(this,function(exports){"use strict";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 overRest$1(func,start,transform){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&&MAX_SAFE_INTEGER>=value}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function noop(){}function once(fn){return function(){if(null!==fn){var callFn=fn;fn=null,callFn.apply(this,arguments)}}}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index-1&&value%1==0&&length>value}function baseIsTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]}function baseUnary(func){return function(value){return func(value)}}function arrayLikeKeys(value,inherited){var isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value)!inherited&&!hasOwnProperty$1.call(value,key)||skipIndexes&&("length"==key||isBuff&&("offset"==key||"parent"==key)||isType&&("buffer"==key||"byteLength"==key||"byteOffset"==key)||isIndex(key,length))||result.push(key);return result}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto$5;return value===proto}function overArg(func,transform){return function(arg){return func(transform(arg))}}function baseKeys(object){if(!isPrototype(object))return nativeKeys(object);var result=[];for(var key in Object(object))hasOwnProperty$3.call(object,key)&&"constructor"!=key&&result.push(key);return result}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function createArrayIterator(coll){var i=-1,len=coll.length;return function(){return++ii?{value:obj[key],key:key}:null}}function iterator(coll){if(isArrayLike(coll))return createArrayIterator(coll);var iterator=getIterator(coll);return iterator?createES2015Iterator(iterator):createObjectIterator(coll)}function onlyOnce(fn){return function(){if(null===fn)throw new Error("Callback was already called.");var callFn=fn;fn=null,callFn.apply(this,arguments)}}function _eachOfLimit(limit){return function(obj,iteratee,callback){function iterateeCallback(err,value){if(running-=1,err)done=!0,callback(err);else{if(value===breakLoop||done&&0>=running)return done=!0,callback(null);replenish()}}function replenish(){for(;limit>running&&!done;){var elem=nextElem();if(null===elem)return done=!0,void(0>=running&&callback(null));running+=1,iteratee(elem.value,elem.key,onlyOnce(iterateeCallback))}}if(callback=once(callback||noop),0>=limit||!obj)return callback(null);var nextElem=iterator(obj),done=!1,running=0;replenish()}}function eachOfLimit(coll,limit,iteratee,callback){_eachOfLimit(limit)(coll,wrapAsync$1(iteratee),callback)}function doLimit(fn,limit){return function(iterable,iteratee,callback){return fn(iterable,limit,iteratee,callback)}}function eachOfArrayLike(coll,iteratee,callback){function iteratorCallback(err,value){err?callback(err):(++completed===length||value===breakLoop)&&callback(null)}callback=once(callback||noop);var index=0,completed=0,length=coll.length;for(0===length&&callback(null);length>index;index++)iteratee(coll[index],index,onlyOnce(iteratorCallback))}function doParallel(fn){return function(obj,iteratee,callback){return fn(eachOf,obj,wrapAsync$1(iteratee),callback)}}function _asyncMap(eachfn,arr,iteratee,callback){callback=callback||noop,arr=arr||[];var results=[],counter=0,_iteratee=wrapAsync$1(iteratee);eachfn(arr,function(value,_,callback){var index=counter++;_iteratee(value,function(err,v){results[index]=v,callback(err)})},function(err){callback(err,results)})}function doParallelLimit(fn){return function(obj,limit,iteratee,callback){return fn(_eachOfLimit(limit),obj,wrapAsync$1(iteratee),callback)}}function arrayEach(array,iteratee){for(var index=-1,length=null==array?0:array.length;++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function charsStartIndex(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index-1;);return index}function asciiToArray(string){return string.split("")}function hasUnicode(string){return reHasUnicode.test(string)}function unicodeToArray(string){return string.match(reUnicode)||[]}function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string)}function toString(value){return null==value?"":baseToString(value)}function trim(string,chars,guard){if(string=toString(string),string&&(guard||void 0===chars))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function parseParams(func){return func=func.toString().replace(STRIP_COMMENTS,""),func=func.match(FN_ARGS)[2].replace(" ",""),func=func?func.split(FN_ARG_SPLIT):[],func=func.map(function(arg){return trim(arg.replace(FN_ARG,""))})}function autoInject(tasks,callback){var newTasks={};baseForOwn(tasks,function(taskFn,key){function newTask(results,taskCb){var newArgs=arrayMap(params,function(name){return results[name]});newArgs.push(taskCb),wrapAsync$1(taskFn).apply(null,newArgs)}var params,fnIsAsync=isAsync(taskFn),hasNoDeps=!fnIsAsync&&1===taskFn.length||fnIsAsync&&0===taskFn.length;if(isArray(taskFn))params=taskFn.slice(0,-1),taskFn=taskFn[taskFn.length-1],newTasks[key]=params.concat(params.length>0?newTask:taskFn);else if(hasNoDeps)newTasks[key]=taskFn;else{if(params=parseParams(taskFn),0===taskFn.length&&!fnIsAsync&&0===params.length)throw new Error("autoInject task functions require explicit parameters.");fnIsAsync||params.pop(),newTasks[key]=params.concat(newTask)}}),auto(newTasks,callback)}function fallback(fn){setTimeout(fn,0)}function wrap(defer){return rest(function(fn,args){defer(function(){fn.apply(null,args)})})}function DLL(){this.head=this.tail=null,this.length=0}function setInitial(dll,node){dll.length=1,dll.head=dll.tail=node}function queue(worker,concurrency,payload){function _insert(data,insertAtFront,callback){if(null!=callback&&"function"!=typeof callback)throw new Error("task callback must be a function");if(q.started=!0,isArray(data)||(data=[data]),0===data.length&&q.idle())return setImmediate$1(function(){q.drain()});for(var i=0,l=data.length;l>i;i++){var item={data:data[i],callback:callback||noop};insertAtFront?q._tasks.unshift(item):q._tasks.push(item)}setImmediate$1(q.process)}function _next(tasks){return rest(function(args){numRunning-=1;for(var i=0,l=tasks.length;l>i;i++){var task=tasks[i],index=baseIndexOf(workersList,task,0);index>=0&&workersList.splice(index),task.callback.apply(task,args),null!=args[0]&&q.error(args[0],task.data)}numRunning<=q.concurrency-q.buffer&&q.unsaturated(),q.idle()&&q.drain(),q.process()})}if(null==concurrency)concurrency=1;else if(0===concurrency)throw new Error("Concurrency must not be zero");var _worker=wrapAsync$1(worker),numRunning=0,workersList=[],isProcessing=!1,q={_tasks:new DLL,concurrency:concurrency,payload:payload,saturated:noop,unsaturated:noop,buffer:concurrency/4,empty:noop,drain:noop,error:noop,started:!1,paused:!1,push:function(data,callback){_insert(data,!1,callback)},kill:function(){q.drain=noop,q._tasks.empty()},unshift:function(data,callback){_insert(data,!0,callback)},process:function(){if(!isProcessing){for(isProcessing=!0;!q.paused&&numRunningi;i++){var node=q._tasks.shift();tasks.push(node),data.push(node.data)}0===q._tasks.length&&q.empty(),numRunning+=1,workersList.push(tasks[0]),numRunning===q.concurrency&&q.saturated();var cb=onlyOnce(_next(tasks));_worker(data,cb)}isProcessing=!1}},length:function(){return q._tasks.length},running:function(){return numRunning},workersList:function(){return workersList},idle:function(){return q._tasks.length+numRunning===0},pause:function(){q.paused=!0},resume:function(){q.paused!==!1&&(q.paused=!1,setImmediate$1(q.process))}};return q}function cargo(worker,payload){return queue(worker,1,payload)}function reduce(coll,memo,iteratee,callback){callback=once(callback||noop);var _iteratee=wrapAsync$1(iteratee);eachOfSeries(coll,function(x,i,callback){_iteratee(memo,x,function(err,v){memo=v,callback(err)})},function(err){callback(err,memo)})}function concat$1(eachfn,arr,fn,callback){var result=[];eachfn(arr,function(x,index,cb){fn(x,function(err,y){result=result.concat(y||[]),cb(err)})},function(err){callback(err,result)})}function doSeries(fn){return function(obj,iteratee,callback){return fn(eachOfSeries,obj,wrapAsync$1(iteratee),callback)}}function _createTester(check,getResult){return function(eachfn,arr,iteratee,cb){cb=cb||noop;var testResult,testPassed=!1;eachfn(arr,function(value,_,callback){iteratee(value,function(err,result){err?callback(err):check(result)&&!testResult?(testPassed=!0,testResult=getResult(!0,value),callback(null,breakLoop)):callback()})},function(err){err?cb(err):cb(null,testPassed?testResult:getResult(!1))})}}function _findGetResult(v,x){return x}function consoleFunc(name){return rest(function(fn,args){wrapAsync$1(fn).apply(null,args.concat(rest(function(err,args){"object"==typeof console&&(err?console.error&&console.error(err):console[name]&&arrayEach(args,function(x){console[name](x)}))})))})}function doDuring(fn,test,callback){function check(err,truth){return err?callback(err):truth?void _fn(next):callback(null)}callback=onlyOnce(callback||noop);var _fn=wrapAsync$1(fn),_test=wrapAsync$1(test),next=rest(function(err,args){return err?callback(err):(args.push(check),void _test.apply(this,args))});check(null,!0)}function doWhilst(iteratee,test,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync$1(iteratee),next=rest(function(err,args){return err?callback(err):test.apply(this,args)?_iteratee(next):void callback.apply(null,[null].concat(args))});_iteratee(next)}function doUntil(iteratee,test,callback){doWhilst(iteratee,function(){return!test.apply(this,arguments)},callback)}function during(test,fn,callback){function next(err){return err?callback(err):void _test(check)}function check(err,truth){return err?callback(err):truth?void _fn(next):callback(null)}callback=onlyOnce(callback||noop);var _fn=wrapAsync$1(fn),_test=wrapAsync$1(test);_test(check)}function _withoutIndex(iteratee){return function(value,index,callback){return iteratee(value,callback)}}function eachLimit(coll,iteratee,callback){eachOf(coll,_withoutIndex(wrapAsync$1(iteratee)),callback)}function eachLimit$1(coll,limit,iteratee,callback){_eachOfLimit(limit)(coll,_withoutIndex(wrapAsync$1(iteratee)),callback)}function ensureAsync(fn){return isAsync(fn)?fn:initialParams(function(args,callback){var sync=!0;args.push(function(){var innerArgs=arguments;sync?setImmediate$1(function(){callback.apply(null,innerArgs)}):callback.apply(null,innerArgs)}),fn.apply(this,args),sync=!1})}function notId(v){return!v}function baseProperty(key){return function(object){return null==object?void 0:object[key]}}function filterArray(eachfn,arr,iteratee,callback){var truthValues=new Array(arr.length);eachfn(arr,function(x,index,callback){iteratee(x,function(err,v){truthValues[index]=!!v,callback(err)})},function(err){if(err)return callback(err);for(var results=[],i=0;ii;i++)q[i].apply(null,args)}))))});return memoized.memo=memo,memoized.unmemoized=fn,memoized}function _parallel(eachfn,tasks,callback){callback=callback||noop;var results=isArrayLike(tasks)?[]:{};eachfn(tasks,function(task,key,callback){wrapAsync$1(task)(rest(function(err,args){args.length<=1&&(args=args[0]),results[key]=args,callback(err)}))},function(err){callback(err,results)})}function parallelLimit(tasks,callback){_parallel(eachOf,tasks,callback)}function parallelLimit$1(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)}function race(tasks,callback){if(callback=once(callback||noop),!isArray(tasks))return callback(new TypeError("First argument to race must be an array of functions"));if(!tasks.length)return callback();for(var i=0,l=tasks.length;l>i;i++)wrapAsync$1(tasks[i])(callback)}function reduceRight(array,memo,iteratee,callback){var reversed=slice.call(array).reverse();reduce(reversed,memo,iteratee,callback)}function reflect(fn){var _fn=wrapAsync$1(fn);return initialParams(function(args,reflectCallback){return args.push(rest(function(err,cbArgs){if(err)reflectCallback(null,{error:err});else{var value=null;1===cbArgs.length?value=cbArgs[0]:cbArgs.length>1&&(value=cbArgs),reflectCallback(null,{value:value})}})),_fn.apply(this,args)})}function reject$1(eachfn,arr,iteratee,callback){_filter(eachfn,arr,function(value,cb){iteratee(value,function(err,v){cb(err,!v)})},callback)}function reflectAll(tasks){var results;return isArray(tasks)?results=arrayMap(tasks,reflect):(results={},baseForOwn(tasks,function(task,key){results[key]=reflect.call(this,task)})),results}function constant$1(value){return function(){return value}}function retry(opts,task,callback){function parseTimes(acc,t){if("object"==typeof t)acc.times=+t.times||DEFAULT_TIMES,acc.intervalFunc="function"==typeof t.interval?t.interval:constant$1(+t.interval||DEFAULT_INTERVAL),acc.errorFilter=t.errorFilter;else{if("number"!=typeof t&&"string"!=typeof t)throw new Error("Invalid arguments for async.retry");acc.times=+t||DEFAULT_TIMES}}function retryAttempt(){_task(function(err){err&&attempt++a?-1:a>b?1:0}var _iteratee=wrapAsync$1(iteratee);map(coll,function(x,callback){_iteratee(x,function(err,criteria){return err?callback(err):void callback(null,{value:x,criteria:criteria})})},function(err,results){return err?callback(err):void callback(null,arrayMap(results.sort(comparator),baseProperty("value")))})}function timeout(asyncFn,milliseconds,info){function injectedCallback(){timedOut||(originalCallback.apply(null,arguments),clearTimeout(timer))}function timeoutCallback(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,originalCallback(error)}var originalCallback,timer,timedOut=!1,fn=wrapAsync$1(asyncFn);return initialParams(function(args,origCallback){originalCallback=origCallback,timer=setTimeout(timeoutCallback,milliseconds),fn.apply(null,args.concat(injectedCallback))})}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax$1(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function timeLimit(count,limit,iteratee,callback){var _iteratee=wrapAsync$1(iteratee);mapLimit(baseRange(0,count,1),limit,_iteratee,callback)}function transform(coll,accumulator,iteratee,callback){arguments.length<=3&&(callback=iteratee,iteratee=accumulator,accumulator=isArray(coll)?[]:{}),callback=once(callback||noop);var _iteratee=wrapAsync$1(iteratee);eachOf(coll,function(v,k,cb){_iteratee(accumulator,v,k,cb)},function(err){callback(err,accumulator)})}function unmemoize(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}}function whilst(test,iteratee,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync$1(iteratee);if(!test())return callback(null);var next=rest(function(err,args){return err?callback(err):test()?_iteratee(next):void callback.apply(null,[null].concat(args))});_iteratee(next)}function until(test,iteratee,callback){whilst(function(){return!test.apply(this,arguments)},iteratee,callback)}var nativeMax=Math.max,initialParams=function(fn){return rest(function(args){var callback=args.pop();fn.call(this,args,callback)})},supportsSymbol="function"==typeof Symbol,wrapAsync$1=supportsAsync()?wrapAsync:identity,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol$1=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag$1=Symbol$1?Symbol$1.toStringTag:void 0,objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString,nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$1?Symbol$1.toStringTag:void 0,asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]",MAX_SAFE_INTEGER=9007199254740991,breakLoop={},iteratorSymbol="function"==typeof Symbol&&Symbol.iterator,getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()},argsTag="[object Arguments]",objectProto$3=Object.prototype,hasOwnProperty$2=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$2.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,MAX_SAFE_INTEGER$1=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/,argsTag$1="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag$1="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",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]",typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag$1]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,objectProto$2=Object.prototype,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=overArg(Object.keys,Object),objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty,eachOfGeneric=doLimit(eachOfLimit,1/0),eachOf=function(coll,iteratee,callback){var eachOfImplementation=isArrayLike(coll)?eachOfArrayLike:eachOfGeneric;eachOfImplementation(coll,wrapAsync$1(iteratee),callback)},map=doParallel(_asyncMap),applyEach=applyEach$1(map),mapLimit=doParallelLimit(_asyncMap),mapSeries=doLimit(mapLimit,1),applyEachSeries=applyEach$1(mapSeries),apply$2=rest(function(fn,args){return rest(function(callArgs){return fn.apply(null,args.concat(callArgs))})}),baseFor=createBaseFor(),auto=function(tasks,concurrency,callback){function enqueueTask(key,task){readyTasks.push(function(){runTask(key,task)})}function processQueue(){if(0===readyTasks.length&&0===runningTasks)return callback(null,results);for(;readyTasks.length&&concurrency>runningTasks;){var run=readyTasks.shift();run()}}function addListener(taskName,fn){var taskListeners=listeners[taskName];taskListeners||(taskListeners=listeners[taskName]=[]),taskListeners.push(fn)}function taskComplete(taskName){var taskListeners=listeners[taskName]||[];arrayEach(taskListeners,function(fn){fn()}),processQueue()}function runTask(key,task){if(!hasError){var taskCallback=onlyOnce(rest(function(err,args){if(runningTasks--,args.length<=1&&(args=args[0]),err){var safeResults={};baseForOwn(results,function(val,rkey){safeResults[rkey]=val}),safeResults[key]=args,hasError=!0,listeners=Object.create(null),callback(err,safeResults)}else results[key]=args,taskComplete(key)}));runningTasks++;var taskFn=wrapAsync$1(task[task.length-1]);task.length>1?taskFn(results,taskCallback):taskFn(taskCallback)}}function checkForDeadlocks(){for(var currentTask,counter=0;readyToCheck.length;)currentTask=readyToCheck.pop(),counter++,arrayEach(getDependents(currentTask),function(dependent){0===--uncheckedDependencies[dependent]&&readyToCheck.push(dependent)});if(counter!==numTasks)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function getDependents(taskName){var result=[];return baseForOwn(tasks,function(task,key){isArray(task)&&baseIndexOf(task,taskName,0)>=0&&result.push(key)}),result}"function"==typeof concurrency&&(callback=concurrency,concurrency=null),callback=once(callback||noop);var keys$$1=keys(tasks),numTasks=keys$$1.length;if(!numTasks)return callback(null);concurrency||(concurrency=numTasks);var results={},runningTasks=0,hasError=!1,listeners=Object.create(null),readyTasks=[],readyToCheck=[],uncheckedDependencies={};baseForOwn(tasks,function(task,key){if(!isArray(task))return enqueueTask(key,[task]),void readyToCheck.push(key);var dependencies=task.slice(0,task.length-1),remainingDependencies=dependencies.length;return 0===remainingDependencies?(enqueueTask(key,task),void readyToCheck.push(key)):(uncheckedDependencies[key]=remainingDependencies,void arrayEach(dependencies,function(dependencyName){if(!tasks[dependencyName])throw new Error("async.auto task `"+key+"` has a non-existent dependency `"+dependencyName+"` in "+dependencies.join(", "));addListener(dependencyName,function(){remainingDependencies--,0===remainingDependencies&&enqueueTask(key,task)})}))}),checkForDeadlocks(),processQueue()},symbolTag="[object Symbol]",INFINITY=1/0,symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange="\\u20d0-\\u20f0",rsVarRange="\\ufe0e\\ufe0f",rsZWJ="\\u200d",reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboMarksRange+rsComboSymbolsRange+rsVarRange+"]"),rsAstralRange$1="\\ud800-\\udfff",rsComboMarksRange$1="\\u0300-\\u036f\\ufe20-\\ufe23",rsComboSymbolsRange$1="\\u20d0-\\u20f0",rsVarRange$1="\\ufe0e\\ufe0f",rsAstral="["+rsAstralRange$1+"]",rsCombo="["+rsComboMarksRange$1+rsComboSymbolsRange$1+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange$1+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsZWJ$1="\\u200d",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange$1+"]?",rsOptJoin="(?:"+rsZWJ$1+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reTrim=/^\s+|\s+$/g,FN_ARGS=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,FN_ARG_SPLIT=/,/,FN_ARG=/(=.+)?(\s*)$/,STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,hasSetImmediate="function"==typeof setImmediate&&setImmediate,hasNextTick="object"==typeof process&&"function"==typeof process.nextTick,_defer;_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback;var setImmediate$1=wrap(_defer);DLL.prototype.removeLink=function(node){return node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev,node.prev=node.next=null,this.length-=1,node},DLL.prototype.empty=DLL,DLL.prototype.insertAfter=function(node,newNode){newNode.prev=node,newNode.next=node.next,node.next?node.next.prev=newNode:this.tail=newNode,node.next=newNode,this.length+=1},DLL.prototype.insertBefore=function(node,newNode){newNode.prev=node.prev,newNode.next=node,node.prev?node.prev.next=newNode:this.head=newNode,node.prev=newNode,this.length+=1},DLL.prototype.unshift=function(node){this.head?this.insertBefore(this.head,node):setInitial(this,node)},DLL.prototype.push=function(node){this.tail?this.insertAfter(this.tail,node):setInitial(this,node)},DLL.prototype.shift=function(){return this.head&&this.removeLink(this.head)},DLL.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)};var eachOfSeries=doLimit(eachOfLimit,1),seq$1=rest(function(functions){var _functions=arrayMap(functions,wrapAsync$1);return rest(function(args){var that=this,cb=args[args.length-1];"function"==typeof cb?args.pop():cb=noop,reduce(_functions,args,function(newargs,fn,cb){fn.apply(that,newargs.concat(rest(function(err,nextargs){cb(err,nextargs)})))},function(err,results){cb.apply(that,[err].concat(results))})})}),compose=rest(function(args){return seq$1.apply(null,args.reverse())}),concat=doParallel(concat$1),concatSeries=doSeries(concat$1),constant=rest(function(values){var args=[null].concat(values);return initialParams(function(ignoredArgs,callback){return callback.apply(this,args)})}),detect=doParallel(_createTester(identity,_findGetResult)),detectLimit=doParallelLimit(_createTester(identity,_findGetResult)),detectSeries=doLimit(detectLimit,1),dir=consoleFunc("dir"),eachSeries=doLimit(eachLimit$1,1),every=doParallel(_createTester(notId,notId)),everyLimit=doParallelLimit(_createTester(notId,notId)),everySeries=doLimit(everyLimit,1),filter=doParallel(_filter),filterLimit=doParallelLimit(_filter),filterSeries=doLimit(filterLimit,1),groupByLimit=function(coll,limit,iteratee,callback){callback=callback||noop;var _iteratee=wrapAsync$1(iteratee);mapLimit(coll,limit,function(val,callback){_iteratee(val,function(err,key){return err?callback(err):callback(null,{key:key,val:val})})},function(err,mapResults){for(var result={},hasOwnProperty=Object.prototype.hasOwnProperty,i=0;i=nextNode.priority;)nextNode=nextNode.next;for(var i=0,l=data.length;l>i;i++){var item={data:data[i],priority:priority,callback:callback};nextNode?q._tasks.insertBefore(nextNode,item):q._tasks.push(item)}setImmediate$1(q.process)},delete q.unshift,q},slice=Array.prototype.slice,reject=doParallel(reject$1),rejectLimit=doParallelLimit(reject$1),rejectSeries=doLimit(rejectLimit,1),retryable=function(opts,task){task||(task=opts,opts=null);var _task=wrapAsync$1(task);return initialParams(function(args,callback){function taskFn(cb){_task.apply(null,args.concat(cb))}opts?retry(opts,taskFn,callback):retry(taskFn,callback)})},some=doParallel(_createTester(Boolean,identity)),someLimit=doParallelLimit(_createTester(Boolean,identity)),someSeries=doLimit(someLimit,1),nativeCeil=Math.ceil,nativeMax$1=Math.max,times=doLimit(timeLimit,1/0),timesSeries=doLimit(timeLimit,1),waterfall=function(tasks,callback){function nextTask(args){if(taskIndex===tasks.length)return callback.apply(null,[null].concat(args));var taskCallback=onlyOnce(rest(function(err,args){return err?callback.apply(null,[err].concat(args)):void nextTask(args)}));args.push(taskCallback);var task=wrapAsync$1(tasks[taskIndex++]);task.apply(null,args)}if(callback=once(callback||noop),!isArray(tasks))return callback(new Error("First argument to waterfall must be an array of functions"));if(!tasks.length)return callback();var taskIndex=0;nextTask([])},index={applyEach:applyEach,applyEachSeries:applyEachSeries,apply:apply$2,asyncify:asyncify,auto:auto,autoInject:autoInject,cargo:cargo,compose:compose,concat:concat,concatSeries:concatSeries,constant:constant,detect:detect,detectLimit:detectLimit,detectSeries:detectSeries,dir:dir,doDuring:doDuring,doUntil:doUntil,doWhilst:doWhilst,during:during,each:eachLimit,eachLimit:eachLimit$1,eachOf:eachOf,eachOfLimit:eachOfLimit,eachOfSeries:eachOfSeries,eachSeries:eachSeries,ensureAsync:ensureAsync,every:every,everyLimit:everyLimit,everySeries:everySeries,filter:filter,filterLimit:filterLimit,filterSeries:filterSeries,forever:forever,groupBy:groupBy,groupByLimit:groupByLimit,groupBySeries:groupBySeries,log:log,map:map,mapLimit:mapLimit,mapSeries:mapSeries,mapValues:mapValues,mapValuesLimit:mapValuesLimit,mapValuesSeries:mapValuesSeries,memoize:memoize,nextTick:nextTick,parallel:parallelLimit,parallelLimit:parallelLimit$1,priorityQueue:priorityQueue,queue:queue$1,race:race,reduce:reduce,reduceRight:reduceRight,reflect:reflect,reflectAll:reflectAll,reject:reject,rejectLimit:rejectLimit,rejectSeries:rejectSeries,retry:retry,retryable:retryable,seq:seq$1,series:series,setImmediate:setImmediate$1,some:some,someLimit:someLimit,someSeries:someSeries,sortBy:sortBy,timeout:timeout,times:times,timesLimit:timeLimit,timesSeries:timesSeries,transform:transform,unmemoize:unmemoize,until:until,waterfall:waterfall,whilst:whilst,all:every,any:some,forEach:eachLimit,forEachSeries:eachSeries,forEachLimit:eachLimit$1,forEachOf:eachOf,forEachOfSeries:eachOfSeries,forEachOfLimit:eachOfLimit,inject:reduce,foldl:reduce,foldr:reduceRight,select:filter,selectLimit:filterLimit,selectSeries:filterSeries,wrapSync:asyncify};exports["default"]=index,exports.applyEach=applyEach,exports.applyEachSeries=applyEachSeries,exports.apply=apply$2,exports.asyncify=asyncify,exports.auto=auto,exports.autoInject=autoInject,exports.cargo=cargo,exports.compose=compose,exports.concat=concat,exports.concatSeries=concatSeries,exports.constant=constant,exports.detect=detect,exports.detectLimit=detectLimit,exports.detectSeries=detectSeries,exports.dir=dir,exports.doDuring=doDuring,exports.doUntil=doUntil,exports.doWhilst=doWhilst,exports.during=during,exports.each=eachLimit,exports.eachLimit=eachLimit$1,exports.eachOf=eachOf,exports.eachOfLimit=eachOfLimit,exports.eachOfSeries=eachOfSeries,exports.eachSeries=eachSeries,exports.ensureAsync=ensureAsync,exports.every=every,exports.everyLimit=everyLimit,exports.everySeries=everySeries,exports.filter=filter,exports.filterLimit=filterLimit,exports.filterSeries=filterSeries,exports.forever=forever,exports.groupBy=groupBy,exports.groupByLimit=groupByLimit,exports.groupBySeries=groupBySeries,exports.log=log,exports.map=map,exports.mapLimit=mapLimit,exports.mapSeries=mapSeries,exports.mapValues=mapValues,exports.mapValuesLimit=mapValuesLimit,exports.mapValuesSeries=mapValuesSeries,exports.memoize=memoize,exports.nextTick=nextTick,exports.parallel=parallelLimit,exports.parallelLimit=parallelLimit$1,exports.priorityQueue=priorityQueue,exports.queue=queue$1,exports.race=race,exports.reduce=reduce,exports.reduceRight=reduceRight,exports.reflect=reflect,exports.reflectAll=reflectAll,exports.reject=reject,exports.rejectLimit=rejectLimit,exports.rejectSeries=rejectSeries,exports.retry=retry,exports.retryable=retryable,exports.seq=seq$1,exports.series=series,exports.setImmediate=setImmediate$1,exports.some=some,exports.someLimit=someLimit,exports.someSeries=someSeries,exports.sortBy=sortBy,exports.timeout=timeout,exports.times=times,exports.timesLimit=timeLimit,exports.timesSeries=timesSeries,exports.transform=transform,exports.unmemoize=unmemoize,exports.until=until,exports.waterfall=waterfall,exports.whilst=whilst,exports.all=every,exports.allLimit=everyLimit,exports.allSeries=everySeries,exports.any=some,exports.anyLimit=someLimit,exports.anySeries=someSeries,exports.find=detect,exports.findLimit=detectLimit,exports.findSeries=detectSeries,exports.forEach=eachLimit,exports.forEachSeries=eachSeries,exports.forEachLimit=eachLimit$1,exports.forEachOf=eachOf,exports.forEachOfSeries=eachOfSeries,exports.forEachOfLimit=eachOfLimit,exports.inject=reduce,exports.foldl=reduce,exports.foldr=reduceRight,exports.select=filter,exports.selectLimit=filterLimit,exports.selectSeries=filterSeries,exports.wrapSync=asyncify,Object.defineProperty(exports,"__esModule",{value:!0})})}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:85}],5:[function(require,module,exports){"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;l>i;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&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;end>i;i+=3)tmp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2],output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,output="",parts=[],maxChunkLength=16383,i=0,len2=len-extraBytes;len2>i;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?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;len>i;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63},{}],6:[function(){},{}],7:[function(require,module,exports){arguments[4][6][0].apply(exports,arguments)},{dup:6}],8:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer"),Buffer=buffer.Buffer,SlowBuffer=buffer.SlowBuffer,MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function(size,fill,encoding){if("function"==typeof Buffer.alloc)return Buffer.alloc(size,fill,encoding);if("number"==typeof encoding)throw new TypeError("encoding must not be number");if("number"!=typeof size)throw new TypeError("size must be a number");if(size>MAX_LEN)throw new RangeError("size is too large");var enc=encoding,_fill=fill;void 0===_fill&&(enc=void 0,_fill=0);var buf=new Buffer(size);if("string"==typeof _fill)for(var fillBuf=new Buffer(_fill,enc),flen=fillBuf.length,i=-1;++iMAX_LEN)throw new RangeError("size is too large");return new Buffer(size)},exports.from=function(value,encodingOrOffset,length){if("function"==typeof Buffer.from&&(!global.Uint8Array||Uint8Array.from!==Buffer.from))return Buffer.from(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError('"value" argument must not be a number');if("string"==typeof value)return new Buffer(value,encodingOrOffset);if("undefined"!=typeof ArrayBuffer&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(1===arguments.length)return new Buffer(value);"undefined"==typeof offset&&(offset=0);var len=length;if("undefined"==typeof len&&(len=value.byteLength-offset),offset>=value.byteLength)throw new RangeError("'offset' is out of bounds");if(len>value.byteLength-offset)throw new RangeError("'length' is out of bounds");return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);return value.copy(out,0,0,value.length),out}if(value){if(Array.isArray(value)||"undefined"!=typeof ArrayBuffer&&value.buffer instanceof ArrayBuffer||"length"in value)return new Buffer(value);if("Buffer"===value.type&&Array.isArray(value.data))return new Buffer(value.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},exports.allocUnsafeSlow=function(size){if("function"==typeof Buffer.allocUnsafeSlow)return Buffer.allocUnsafeSlow(size);if("number"!=typeof size)throw new TypeError("size must be a number");if(size>=MAX_LEN)throw new RangeError("size is too large");return new SlowBuffer(size)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{buffer:9}],9:[function(require,module,exports){(function(global){"use strict";function typedArraySupport(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()size)throw new RangeError('"size" argument must not be negative')}function alloc(that,size,fill,encoding){return assertSize(size),0>=size?createBuffer(that,size):void 0!==fill?"string"==typeof encoding?createBuffer(that,size).fill(fill,encoding):createBuffer(that,size).fill(fill):createBuffer(that,size)}function allocUnsafe(that,size){if(assertSize(size),that=createBuffer(that,0>size?0:0|checked(size)),!Buffer.TYPED_ARRAY_SUPPORT)for(var i=0;size>i;++i)that[i]=0;return that}function fromString(that,string,encoding){if(("string"!=typeof encoding||""===encoding)&&(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError('"encoding" must be a valid string encoding');var length=0|byteLength(string,encoding);that=createBuffer(that,length);var actual=that.write(string,encoding);return actual!==length&&(that=that.slice(0,actual)),that}function fromArrayLike(that,array){var length=array.length<0?0:0|checked(array.length);that=createBuffer(that,length);for(var i=0;length>i;i+=1)that[i]=255&array[i];return that}function fromArrayBuffer(that,array,byteOffset,length){if(array.byteLength,0>byteOffset||array.byteLength=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||0>start)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),0>=end)return"";if(end>>>=0,start>>>=0,start>=end)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:-2147483648>byteOffset&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),0>byteOffset&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(0>byteOffset){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&val,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;arrLength>i;i++)if(read(arr,i)===read(val,-1===foundIndex?0:i-foundIndex)){if(-1===foundIndex&&(foundIndex=i),i-foundIndex+1===valLength)return foundIndex*indexSize}else-1!==foundIndex&&(i-=i-foundIndex),foundIndex=-1}else for(byteOffset+valLength>arrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;valLength>j;j++)if(read(arr,i+j)!==read(val,j)){found=!1;break}if(found)return i}return-1}function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;length?(length=Number(length),length>remaining&&(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;length>i;++i){var parsed=parseInt(string.substr(2*i,2),16);if(isNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}function base64Slice(buf,start,end){return base64.fromByteArray(0===start&&end===buf.length?buf:buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);for(var res=[],i=start;end>i;){var firstByte=buf[i],codePoint=null,bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(end>=i+bytesPerSequence){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:128>firstByte&&(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&&(55296>tempCodePoint||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&&1114112>tempCodePoint&&(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(MAX_ARGUMENTS_LENGTH>=len)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;len>i;)res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH));return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;end>i;++i)ret+=String.fromCharCode(127&buf[i]);return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;end>i;++i)ret+=String.fromCharCode(buf[i]);return ret}function hexSlice(buf,start,end){var len=buf.length;(!start||0>start)&&(start=0),(!end||0>end||end>len)&&(end=len);for(var out="",i=start;end>i;++i)out+=toHex(buf[i]);return out}function utf16leSlice(buf,start,end){for(var bytes=buf.slice(start,end),res="",i=0;ioffset)throw new RangeError("offset is not uint");if(offset+ext>length)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||min>value)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){0>value&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);j>i;++i)buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){0>value&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);j>i;++i)buf[offset+i]=value>>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(0>offset)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 16>n?"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;length>i;++i){if(codePoint=string.charCodeAt(i),codePoint>55295&&57344>codePoint){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(56320>codePoint){(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,128>codePoint){if((units-=1)<0)break;bytes.push(codePoint)}else if(2048>codePoint){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(65536>codePoint){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(1114112>codePoint))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;length>i&&!(i+offset>=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");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);len>i;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return y>x?-1:x>y?1:0},Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Buffer.concat=function(list,length){if(!isArray(list))throw new TypeError('"list" argument must be an Array of Buffers');if(0===list.length)return Buffer.alloc(0);var i;if(void 0===length)for(length=0,i=0;ii;i+=2)swap(this,i,i+1);return this},Buffer.prototype.swap32=function(){var len=this.length;if(len%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var i=0;len>i;i+=4)swap(this,i,i+3),swap(this,i+1,i+2);return this},Buffer.prototype.swap64=function(){var len=this.length;if(len%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var i=0;len>i;i+=8)swap(this,i,i+7),swap(this,i+1,i+6),swap(this,i+2,i+5),swap(this,i+3,i+4);return this},Buffer.prototype.toString=function(){var length=0|this.length;return 0===length?"":0===arguments.length?utf8Slice(this,0,length):slowToString.apply(this,arguments)},Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return this===b?!0:0===Buffer.compare(this,b)},Buffer.prototype.inspect=function(){var str="",max=exports.INSPECT_MAX_BYTES;return this.length>0&&(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),0>start||end>target.length||0>thisStart||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;len>i;++i)if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i],y=targetCopy[i];break}return y>x?-1:x>y?1:0},Buffer.prototype.includes=function(val,byteOffset,encoding){return-1!==this.indexOf(val,byteOffset,encoding)},Buffer.prototype.indexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!0)},Buffer.prototype.lastIndexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!1)},Buffer.prototype.write=function(string,offset,length,encoding){if(void 0===offset)encoding="utf8",length=this.length,offset=0;else if(void 0===length&&"string"==typeof offset)encoding=offset,length=this.length,offset=0;else{if(!isFinite(offset))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");offset=0|offset,isFinite(length)?(length=0|length,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0)}var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),string.length>0&&(0>length||0>offset)||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,0>start?(start+=len,0>start&&(start=0)):start>len&&(start=len),0>end?(end+=len,0>end&&(end=0)):end>len&&(end=len),start>end&&(end=start);var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT)newBuf=this.subarray(start,end),newBuf.__proto__=Buffer.prototype;else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,void 0);for(var i=0;sliceLen>i;++i)newBuf[i]=this[i+start]}return newBuf},Buffer.prototype.readUIntLE=function(offset,byteLength,noAssert){offset=0|offset,byteLength=0|byteLength,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i0&&(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|offset,byteLength=0|byteLength,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|offset,byteLength=0|byteLength,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]?-1*(255-this[offset]+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|offset,byteLength=0|byteLength,!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,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|offset,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|offset,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|offset,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|offset,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|offset,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|offset,!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;++ivalue&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset=0|offset,!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);)0>value&&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|offset,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),0>value&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset=0|offset,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|offset,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|offset,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|offset,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),0>value&&(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&&start>end&&(end=start),end===start)return 0;if(0===target.length||0===this.length)return 0;if(0>targetStart)throw new RangeError("targetStart out of bounds");if(0>start||start>=this.length)throw new RangeError("sourceStart out of bounds");if(0>end)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStartstart&&end>targetStart)for(i=len-1;i>=0;--i)target[i+targetStart]=this[i+start];else if(1e3>len||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;len>i;++i)target[i+targetStart]=this[i+start];else Uint8Array.prototype.set.call(target,this.subarray(start,start+len),targetStart);return len},Buffer.prototype.fill=function(val,start,end,encoding){if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=this.length):"string"==typeof end&&(encoding=end,end=this.length),1===val.length){var code=val.charCodeAt(0);256>code&&(val=code)}if(void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding)}else"number"==typeof val&&(val=255&val);if(0>start||this.length=end)return this;start>>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;end>i;++i)this[i]=val;else{var bytes=Buffer.isBuffer(val)?val:utf8ToBytes(new Buffer(val,encoding).toString()),len=bytes.length;for(i=0;end-start>i;++i)this[i+start]=bytes[i%len]}return this};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":5,ieee754:40,isarray:44}],10:[function(require,module){(function(Buffer,process){function objCopy(obj){if(null==obj)return obj;if(Array.isArray(obj))return obj.slice();if("object"==typeof obj){var copy={};return Object.keys(obj).forEach(function(k){copy[k]=obj[k]}),copy}return obj}function getCaller3Info(){if(void 0!==this){var obj={},saveLimit=Error.stackTraceLimit,savePrepare=Error.prepareStackTrace;return Error.stackTraceLimit=3,Error.prepareStackTrace=function(_,stack){var caller=stack[2];sourceMapSupport&&(caller=sourceMapSupport.wrapCallSite(caller)),obj.file=caller.getFileName(),obj.line=caller.getLineNumber();var func=caller.getFunctionName();func&&(obj.func=func)},Error.captureStackTrace(this,getCaller3Info),this.stack,Error.stackTraceLimit=saveLimit,Error.prepareStackTrace=savePrepare,obj}}function _indent(s,indent){indent||(indent=" ");var lines=s.split(/\r?\n/g);return indent+lines.join("\n"+indent)}function _warn(msg,dedupKey){if(assert.ok(msg),dedupKey){if(_warned[dedupKey])return;_warned[dedupKey]=!0}process.stderr.write(msg+"\n")}function _haveWarned(dedupKey){return _warned[dedupKey]}function ConsoleRawStream(){}function resolveLevel(nameOrNum){var level,type=typeof nameOrNum;if("string"===type){if(level=levelFromName[nameOrNum.toLowerCase()],!level)throw new Error(format('unknown level name: "%s"',nameOrNum))}else{if("number"!==type)throw new TypeError(format("cannot resolve level: invalid arg (%s):",type,nameOrNum));if(0>nameOrNum||Math.floor(nameOrNum)!==nameOrNum)throw new TypeError(format("level is not a positive integer: %s",nameOrNum));level=nameOrNum}return level}function isWritable(obj){return obj instanceof stream.Writable?!0:"function"==typeof obj.write}function Logger(options,_childOptions,_childSimple){if(xxx("Logger start:",options),!(this instanceof Logger))return new Logger(options,_childOptions);var parent;if(void 0!==_childOptions&&(parent=options,options=_childOptions,!(parent instanceof Logger)))throw new TypeError("invalid Logger creation: do not pass a second arg");if(!options)throw new TypeError("options (object) is required");if(parent){if(options.name)throw new TypeError("invalid options.name: child cannot set logger name")}else if(!options.name)throw new TypeError("options.name (string) is required");if(options.stream&&options.streams)throw new TypeError('cannot mix "streams" and "stream" options');if(options.streams&&!Array.isArray(options.streams))throw new TypeError("invalid options.streams: must be an array");if(options.serializers&&("object"!=typeof options.serializers||Array.isArray(options.serializers)))throw new TypeError("invalid options.serializers: must be an object");if(EventEmitter.call(this),parent&&_childSimple){this._isSimpleChild=!0,this._level=parent._level,this.streams=parent.streams,this.serializers=parent.serializers,this.src=parent.src;for(var fields=this.fields={},parentFieldNames=Object.keys(parent.fields),i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":return fastAndSafeJsonStringify(args[i++]);case"%%":return"%";default:return x}}),x=args[i];len>i;x=args[++i])str+=null===x||"object"!=typeof x?" "+x:" "+inspect(x);return str}}var _warned={};ConsoleRawStream.prototype.write=function(rec){rec.leveli;i++)this.streams[i].level=newLevel;this._level=newLevel},Logger.prototype.levels=function(name,value){if(void 0===name)return assert.equal(value,void 0),this.streams.map(function(s){return s.level});var stream;if("number"==typeof name){if(stream=this.streams[name],void 0===stream)throw new Error("invalid stream index: "+name)}else{for(var len=this.streams.length,i=0;len>i;i++){var s=this.streams[i];if(s.name===name){stream=s;break}}if(!stream)throw new Error(format('no stream with name "%s"',name))}if(void 0===value)return stream.level;var newLevel=resolveLevel(value);stream.level=newLevel,newLevel=0,format('rotating-file stream "count" is not >= 0: %j in %j',this.count,this)),options.period){var period={hourly:"1h",daily:"1d",weekly:"1w",monthly:"1m",yearly:"1y"}[options.period]||options.period,m=/^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);if(!m)throw new Error(format('invalid period: "%s"',options.period));this.periodNum=Number(m[1]),this.periodScope=m[2]}else this.periodNum=1,this.periodScope="d";var lastModified=null;try{var fileInfo=fs.statSync(this.path);lastModified=fileInfo.mtime.getTime()}catch(err){}var rotateAfterOpen=!1;if(lastModified){var lastRotTime=this._calcRotTime(0);lastRotTime>lastModified&&(rotateAfterOpen=!0)}this.stream=fs.createWriteStream(this.path,{flags:"a",encoding:"utf8"}),this.rotQueue=[],this.rotating=!1,rotateAfterOpen?(this._debug("rotateAfterOpen -> call rotate()"),this.rotate()):this._setupNextRot()},util.inherits(RotatingFileStream,EventEmitter),RotatingFileStream.prototype._debug=function(){return!1},RotatingFileStream.prototype._setupNextRot=function(){this.rotAt=this._calcRotTime(1),this._setRotationTimer()},RotatingFileStream.prototype._setRotationTimer=function(){var self=this,delay=this.rotAt-Date.now(),TIMEOUT_MAX=2147483647;delay>TIMEOUT_MAX&&(delay=TIMEOUT_MAX),this.timeout=setTimeout(function(){self._debug("_setRotationTimer timeout -> call rotate()"),self.rotate()},delay),"function"==typeof this.timeout.unref&&this.timeout.unref()},RotatingFileStream.prototype._calcRotTime=function(periodOffset){this._debug("_calcRotTime: %s%s",this.periodNum,this.periodScope);var d=new Date;this._debug(" now local: %s",d),this._debug(" now utc: %s",d.toISOString());var rotAt;switch(this.periodScope){case"ms":rotAt=this.rotAt?this.rotAt+this.periodNum*periodOffset:Date.now()+this.periodNum*periodOffset;break;case"h":rotAt=this.rotAt?this.rotAt+60*this.periodNum*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours()+periodOffset);break;case"d":rotAt=this.rotAt?this.rotAt+24*this.periodNum*60*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+periodOffset);break;case"w":if(this.rotAt)rotAt=this.rotAt+7*this.periodNum*24*60*60*1e3*periodOffset;else{var dayOffset=7-d.getUTCDay();1>periodOffset&&(dayOffset=-d.getUTCDay()),(periodOffset>1||-1>periodOffset)&&(dayOffset+=7*periodOffset),rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+dayOffset)}break;case"m":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+this.periodNum*periodOffset,1):Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+periodOffset,1);break;case"y":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear()+this.periodNum*periodOffset,0,1):Date.UTC(d.getUTCFullYear()+periodOffset,0,1);break;default:assert.fail(format('invalid period scope: "%s"',this.periodScope))}if(this._debug()){this._debug(" **rotAt**: %s (utc: %s)",rotAt,new Date(rotAt).toUTCString());var now=Date.now();this._debug(" now: %s (%sms == %smin == %sh to go)",now,rotAt-now,(rotAt-now)/1e3/60,(rotAt-now)/1e3/60/60)}return rotAt},RotatingFileStream.prototype.rotate=function(){function del(){var toDel=self.path+"."+String(n-1);0===n&&(toDel=self.path),n-=1,self._debug(" rm %s",toDel),fs.unlink(toDel,function(){moves()})}function moves(){if(0===self.count||0>n)return finish();var before=self.path,after=self.path+"."+String(n);n>0&&(before+="."+String(n-1)),n-=1,fs.exists(before,function(exists){exists?(self._debug(" mv %s %s",before,after),mv(before,after,function(mvErr){mvErr?(self.emit("error",mvErr),finish()):moves()})):moves()})}function finish(){self._debug(" open %s",self.path),self.stream=fs.createWriteStream(self.path,{flags:"a",encoding:"utf8"});for(var q=self.rotQueue,len=q.length,i=0;len>i;i++)self.stream.write(q[i]);self.rotQueue=[],self.rotating=!1,self.emit("drain"),self._setupNextRot()}var self=this;if(self.rotAt&&self.rotAt>Date.now())return self._setRotationTimer();if(this._debug("rotate"),self.rotating)throw new TypeError("cannot start a rotation when already rotating");self.rotating=!0,self.stream.end();var n=this.count;del()},RotatingFileStream.prototype.write=function(s){return this.rotating?(this.rotQueue.push(s),!1):this.stream.write(s)},RotatingFileStream.prototype.end=function(){this.stream.end()},RotatingFileStream.prototype.destroy=function(){this.stream.destroy()},RotatingFileStream.prototype.destroySoon=function(){this.stream.destroySoon()}),util.inherits(RingBuffer,EventEmitter),RingBuffer.prototype.write=function(record){if(!this.writable)throw new Error("RingBuffer has been ended already");return this.records.push(record),this.records.length>this.limit&&this.records.shift(),!0},RingBuffer.prototype.end=function(){arguments.length>0&&this.write.apply(this,Array.prototype.slice.call(arguments)),this.writable=!1},RingBuffer.prototype.destroy=function(){this.writable=!1,this.emit("close")},RingBuffer.prototype.destroySoon=function(){this.destroy()},module.exports=Logger,module.exports.TRACE=TRACE,module.exports.DEBUG=DEBUG,module.exports.INFO=INFO,module.exports.WARN=WARN,module.exports.ERROR=ERROR,module.exports.FATAL=FATAL,module.exports.resolveLevel=resolveLevel,module.exports.levelFromName=levelFromName,module.exports.nameFromLevel=nameFromLevel,module.exports.VERSION=VERSION,module.exports.LOG_VERSION=LOG_VERSION,module.exports.createLogger=function(options){return new Logger(options)},module.exports.RingBuffer=RingBuffer,module.exports.RotatingFileStream=RotatingFileStream,module.exports.safeCycles=safeCycles}).call(this,{isBuffer:require("../../is-buffer/index.js")},require("_process"))},{"../../is-buffer/index.js":43,_process:85,assert:3,events:38,fs:7,os:83,"safe-json-stringify":100,stream:122,util:131}],11:[function(require,module,exports){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}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"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)}function isError(e){return"[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||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":43}],12:[function(require,module){function DeferredIterator(options){AbstractIterator.call(this,options),this._options=options,this._iterator=null,this._operations=[]}var util=require("util"),AbstractIterator=require("abstract-leveldown").AbstractIterator;util.inherits(DeferredIterator,AbstractIterator),DeferredIterator.prototype.setDb=function(db){var it=this._iterator=db.iterator(this._options);this._operations.forEach(function(op){it[op.method].apply(it,op.args)})},DeferredIterator.prototype._operation=function(method,args){return this._iterator?this._iterator[method].apply(this._iterator,args):void this._operations.push({method:method,args:args})},"next end".split(" ").forEach(function(m){DeferredIterator.prototype["_"+m]=function(){this._operation(m,arguments)}}),module.exports=DeferredIterator},{"abstract-leveldown":17,util:131}],13:[function(require,module){(function(Buffer,process){function DeferredLevelDOWN(location){AbstractLevelDOWN.call(this,"string"==typeof location?location:""),this._db=void 0,this._operations=[],this._iterators=[]}var util=require("util"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,DeferredIterator=require("./deferred-iterator");util.inherits(DeferredLevelDOWN,AbstractLevelDOWN),DeferredLevelDOWN.prototype.setDb=function(db){this._db=db,this._operations.forEach(function(op){db[op.method].apply(db,op.args)}),this._iterators.forEach(function(it){it.setDb(db)})},DeferredLevelDOWN.prototype._open=function(options,callback){return process.nextTick(callback)},DeferredLevelDOWN.prototype._operation=function(method,args){return this._db?this._db[method].apply(this._db,args):void this._operations.push({method:method,args:args})},"put get del batch approximateSize".split(" ").forEach(function(m){DeferredLevelDOWN.prototype["_"+m]=function(){this._operation(m,arguments)}}),DeferredLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},DeferredLevelDOWN.prototype._iterator=function(options){if(this._db)return this._db.iterator.apply(this._db,arguments);var it=new DeferredIterator(options);return this._iterators.push(it),it},module.exports=DeferredLevelDOWN,module.exports.DeferredIterator=DeferredIterator}).call(this,{isBuffer:require("../is-buffer/index.js")},require("_process"))},{"../is-buffer/index.js":43,"./deferred-iterator":12,_process:85,"abstract-leveldown":17,util:131}],14:[function(require,module){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:85}],15:[function(require,module){(function(process){function AbstractIterator(db){this.db=db,this._ended=!1,this._nexting=!1}AbstractIterator.prototype.next=function(callback){var self=this;if("function"!=typeof callback)throw new Error("next() requires a callback argument");return self._ended?callback(new Error("cannot call next() after end()")):self._nexting?callback(new Error("cannot call next() before previous next() has completed")):(self._nexting=!0,"function"==typeof self._next?self._next(function(){self._nexting=!1,callback.apply(null,arguments)}):void process.nextTick(function(){self._nexting=!1,callback()}))},AbstractIterator.prototype.end=function(callback){if("function"!=typeof callback)throw new Error("end() requires a callback argument");return this._ended?callback(new Error("end() already called on iterator")):(this._ended=!0,"function"==typeof this._end?this._end(callback):void process.nextTick(callback))},module.exports=AbstractIterator}).call(this,require("_process"))},{_process:85}],16:[function(require,module){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location,this.status="new"}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){var self=this,oldStatus=this.status;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");"object"!=typeof options&&(options={}),options.createIfMissing=0!=options.createIfMissing,options.errorIfExists=!!options.errorIfExists,"function"==typeof this._open?(this.status="opening",this._open(options,function(err){return err?(self.status=oldStatus,callback(err)):(self.status="open",void callback())})):(this.status="open",process.nextTick(callback))},AbstractLevelDOWN.prototype.close=function(callback){var self=this,oldStatus=this.status;if("function"!=typeof callback)throw new Error("close() requires a callback argument");"function"==typeof this._close?(this.status="closing",this._close(function(err){return err?(self.status=oldStatus,callback(err)):(self.status="closed",void callback())})):(this.status="closed",process.nextTick(callback))},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),options.asBuffer=0!=options.asBuffer,"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),null==value||this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"==typeof array&&(callback=array),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));options&&"object"==typeof options||(options={});for(var e,err,i=0,l=array.length;l>i;i++)if(e=array[i],"object"==typeof e){if(err=this._checkKey(e.type,"type",this._isBuffer))return callback(err);if(err=this._checkKey(e.key,"key",this._isBuffer))return callback(err)}return"function"==typeof this._batch?this._batch(array,options,callback):void process.nextTick(callback)},AbstractLevelDOWN.prototype.approximateSize=function(start,end,callback){if(null==start||null==end||"function"==typeof start||"function"==typeof end)throw new Error("approximateSize() requires valid `start`, `end` and `callback` arguments");if("function"!=typeof callback)throw new Error("approximateSize() requires a callback argument");return this._isBuffer(start)||(start=String(start)),this._isBuffer(end)||(end=String(end)),"function"==typeof this._approximateSize?this._approximateSize(start,end,callback):void process.nextTick(function(){callback(null,0)})},AbstractLevelDOWN.prototype._setupIteratorOptions=function(options){var self=this;return options=xtend(options),["start","end","gt","gte","lt","lte"].forEach(function(o){options[o]&&self._isBuffer(options[o])&&0===options[o].length&&delete options[o]}),options.reverse=!!options.reverse,options.keys=0!=options.keys,options.values=0!=options.values,options.limit="limit"in options?options.limit:-1,options.keyAsBuffer=0!=options.keyAsBuffer,options.valueAsBuffer=0!=options.valueAsBuffer,options},AbstractLevelDOWN.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),options=this._setupIteratorOptions(options),"function"==typeof this._iterator?this._iterator(options):new AbstractIterator(this)},AbstractLevelDOWN.prototype._chainedBatch=function(){return new AbstractChainedBatch(this)},AbstractLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},AbstractLevelDOWN.prototype._checkKey=function(obj,type){if(null===obj||void 0===obj)return new Error(type+" cannot be `null` or `undefined`");if(this._isBuffer(obj)){if(0===obj.length)return new Error(type+" cannot be an empty Buffer")}else if(""===String(obj))return new Error(type+" cannot be an empty String")},module.exports=AbstractLevelDOWN}).call(this,{isBuffer:require("../../../is-buffer/index.js")},require("_process"))},{"../../../is-buffer/index.js":43,"./abstract-chained-batch":14,"./abstract-iterator":15,_process:85,xtend:133}],17:[function(require,module,exports){exports.AbstractLevelDOWN=require("./abstract-leveldown"),exports.AbstractIterator=require("./abstract-iterator"),exports.AbstractChainedBatch=require("./abstract-chained-batch"),exports.isLevelDOWN=require("./is-leveldown")},{"./abstract-chained-batch":14,"./abstract-iterator":15,"./abstract-leveldown":16,"./is-leveldown":18}],18:[function(require,module){function isLevelDOWN(db){return db&&"object"==typeof db?Object.keys(AbstractLevelDOWN.prototype).filter(function(name){return"_"!=name[0]&&"approximateSize"!=name}).every(function(name){return"function"==typeof db[name]}):!1}var AbstractLevelDOWN=require("./abstract-leveldown");module.exports=isLevelDOWN},{"./abstract-leveldown":16}],19:[function(require,module,exports){const pumpify=require("pumpify"),stopwords=[],CalculateTermFrequency=exports.CalculateTermFrequency=require("./pipeline/CalculateTermFrequency.js"),CreateCompositeVector=exports.CreateCompositeVector=require("./pipeline/CreateCompositeVector.js"),CreateSortVectors=exports.CreateSortVectors=require("./pipeline/CreateSortVectors.js"),CreateStoredDocument=exports.CreateStoredDocument=require("./pipeline/CreateStoredDocument.js"),FieldedSearch=exports.FieldedSearch=require("./pipeline/FieldedSearch.js"),IngestDoc=exports.IngestDoc=require("./pipeline/IngestDoc.js"),LowCase=exports.LowCase=require("./pipeline/LowCase.js"),NormaliseFields=exports.NormaliseFields=require("./pipeline/NormaliseFields.js"),RemoveStopWords=exports.RemoveStopWords=require("./pipeline/RemoveStopWords.js"),Tokeniser=(exports.Spy=require("./pipeline/Spy.js"),exports.Tokeniser=require("./pipeline/Tokeniser.js"));exports.pipeline=function(options){options=Object.assign({},{separator:/[|' .,\-|(\\\n)]+/,searchable:!0,stopwords:stopwords,nGramLength:1,fieldedSearch:!0},options);var pl=[new IngestDoc(options),new CreateStoredDocument,new NormaliseFields,new LowCase,new Tokeniser,new RemoveStopWords,new CalculateTermFrequency,new CreateCompositeVector,new CreateSortVectors,new FieldedSearch];return pumpify.obj.apply(this,pl)},exports.customPipeline=function(pl){return pumpify.obj.apply(this,pl)}},{"./pipeline/CalculateTermFrequency.js":20,"./pipeline/CreateCompositeVector.js":21,"./pipeline/CreateSortVectors.js":22,"./pipeline/CreateStoredDocument.js":23,"./pipeline/FieldedSearch.js":24,"./pipeline/IngestDoc.js":25,"./pipeline/LowCase.js":26,"./pipeline/NormaliseFields.js":27,"./pipeline/RemoveStopWords.js":28,"./pipeline/Spy.js":29,"./pipeline/Tokeniser.js":30,pumpify:88}],20:[function(require,module){const tv=require("term-vector"),tf=require("term-frequency"),Transform=require("stream").Transform,util=require("util"),objectify=function(result,item){return result[item[0].join(" ")]=item[1],result},CalculateTermFrequency=function(){Transform.call(this,{objectMode:!0})};module.exports=CalculateTermFrequency,util.inherits(CalculateTermFrequency,Transform),CalculateTermFrequency.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},nGramLength:1,searchable:!0,weight:0},doc.options||{});for(var fieldName in doc.tokenised){var fieldOptions=Object.assign({},{nGramLength:options.nGramLength,searchable:options.searchable,weight:options.weight},options.fieldOptions[fieldName]),field=doc.tokenised[fieldName];fieldOptions.searchable&&(doc.vector[fieldName]=tf.getTermFrequency(tv.getVector(field,fieldOptions.nGramLength),{scheme:tf.doubleNormalization0point5,weight:fieldOptions.weight}).reduce(objectify,{}),doc.vector[fieldName]["*"]=1)}return this.push(doc),end()}},{stream:122,"term-frequency":125,"term-vector":126,util:131}],21:[function(require,module){const Transform=require("stream").Transform,util=require("util"),CreateCompositeVector=function(){Transform.call(this,{objectMode:!0})};module.exports=CreateCompositeVector,util.inherits(CreateCompositeVector,Transform),CreateCompositeVector.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},searchable:!0},doc.options||{});doc.vector["*"]={};for(var fieldName in doc.vector){var fieldOptions=Object.assign({},{searchable:options.searchable},options.fieldOptions[fieldName]);if(fieldOptions.searchable){var vec=doc.vector[fieldName];for(var token in vec)doc.vector["*"][token]=doc.vector["*"][token]||vec[token],doc.vector["*"][token]=(doc.vector["*"][token]+vec[token])/2}}return this.push(doc),end()}},{stream:122,util:131}],22:[function(require,module){const tf=require("term-frequency"),tv=require("term-vector"),Transform=require("stream").Transform,util=require("util"),objectify=function(result,item){return result[item[0]]=item[1],result},CreateSortVectors=function(){Transform.call(this,{objectMode:!0})};module.exports=CreateSortVectors,util.inherits(CreateSortVectors,Transform),CreateSortVectors.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},sortable:!1},doc.options||{});for(var fieldName in doc.vector){var fieldOptions=Object.assign({},{sortable:options.sortable},options.fieldOptions[fieldName]);fieldOptions.sortable&&(doc.vector[fieldName]=tf.getTermFrequency(tv.getVector(doc.tokenised[fieldName]),{scheme:tf.selfString}).reduce(objectify,{}))}return this.push(doc),end()}},{stream:122,"term-frequency":125,"term-vector":126,util:131}],23:[function(require,module){const Transform=require("stream").Transform,util=require("util"),CreateStoredDocument=function(){Transform.call(this,{objectMode:!0})};module.exports=CreateStoredDocument,util.inherits(CreateStoredDocument,Transform),CreateStoredDocument.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},storeable:!0},doc.options||{});for(var fieldName in doc.raw){var fieldOptions=Object.assign({},{storeable:options.storeable},options.fieldOptions[fieldName]);"id"===fieldName&&(fieldOptions.storeable=!0),fieldOptions.storeable&&(doc.stored[fieldName]=JSON.parse(JSON.stringify(doc.raw[fieldName])))}return this.push(doc),end()}},{stream:122,util:131}],24:[function(require,module){const Transform=require("stream").Transform,util=require("util"),FieldedSearch=function(){Transform.call(this,{objectMode:!0})};module.exports=FieldedSearch,util.inherits(FieldedSearch,Transform),FieldedSearch.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},fieldedSearch:!0},doc.options||{});for(var fieldName in doc.vector){var fieldOptions=Object.assign({},{fieldedSearch:options.fieldedSearch},options.fieldOptions[fieldName]);fieldOptions.fieldedSearch||"*"===fieldName||delete doc.vector[fieldName]}return options.log&&options.log.info(doc),this.push(doc),end()}},{stream:122,util:131}],25:[function(require,module){const util=require("util"),Transform=require("stream").Transform,IngestDoc=function(options){this.options=options,this.i=0,Transform.call(this,{objectMode:!0})};module.exports=IngestDoc,util.inherits(IngestDoc,Transform),IngestDoc.prototype._transform=function(doc,encoding,end){var that=this,ingestedDoc={ -normalised:{},options:that.options,raw:JSON.parse(JSON.stringify(doc)),stored:{},tokenised:{},vector:{}};return ingestedDoc.id=doc.id?String(doc.id):Date.now()+"-"+ ++this.i,this.push(ingestedDoc),end()}},{stream:122,util:131}],26:[function(require,module){const Transform=require("stream").Transform,util=require("util"),LowCase=function(){Transform.call(this,{objectMode:!0})};module.exports=LowCase,util.inherits(LowCase,Transform),LowCase.prototype._transform=function(doc,encoding,end){var options=this.options=Object.assign({},{fieldOptions:{},preserveCase:!1},doc.options||{});for(var fieldName in doc.normalised)if("id"!==fieldName){var fieldOptions=Object.assign({},{preserveCase:options.preserveCase},options.fieldOptions[fieldName]);fieldOptions.preserveCase||("[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.normalised[fieldName].map(function(token){return token.toLowerCase()}):doc.normalised[fieldName]=doc.normalised[fieldName].toLowerCase())}return this.push(doc),end()}},{stream:122,util:131}],27:[function(require,module){const util=require("util"),Transform=require("stream").Transform,NormaliseFields=function(){Transform.call(this,{objectMode:!0})};module.exports=NormaliseFields,util.inherits(NormaliseFields,Transform),NormaliseFields.prototype._transform=function(doc,encoding,end){for(var fieldName in doc.raw)doc.normalised[fieldName]="[object Array]"===Object.prototype.toString.call(doc.raw[fieldName])?doc.raw[fieldName].map(function(item){return JSON.stringify(item).split(/[[\],{}:"]+/).join(" ").trim()}):"[object String]"!==Object.prototype.toString.call(doc.raw[fieldName])?JSON.stringify(doc.raw[fieldName]).split(/[[\],{}:"]+/).join(" ").trim():doc.raw[fieldName].trim();return this.push(doc),end()}},{stream:122,util:131}],28:[function(require,module){const Transform=require("stream").Transform,util=require("util"),RemoveStopWords=function(){Transform.call(this,{objectMode:!0})};module.exports=RemoveStopWords,util.inherits(RemoveStopWords,Transform),RemoveStopWords.prototype._transform=function(doc,encoding,end){var options=Object.assign({},{fieldOptions:{},stopwords:[]},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{stopwords:options.stopwords},options.fieldOptions[fieldName]);doc.tokenised[fieldName]=doc.tokenised[fieldName].filter(function(item){return-1===fieldOptions.stopwords.indexOf(item)}).filter(function(i){return i})}return this.push(doc),end()}},{stream:122,util:131}],29:[function(require,module){const Transform=require("stream").Transform,util=require("util"),Spy=function(){Transform.call(this,{objectMode:!0})};module.exports=Spy,util.inherits(Spy,Transform),Spy.prototype._transform=function(doc,encoding,end){return console.log(JSON.stringify(doc,null,2)),this.push(doc),end()}},{stream:122,util:131}],30:[function(require,module){const Transform=require("stream").Transform,util=require("util"),Tokeniser=function(){Transform.call(this,{objectMode:!0})};module.exports=Tokeniser,util.inherits(Tokeniser,Transform),Tokeniser.prototype._transform=function(doc,encoding,end){var options=this.options=Object.assign({},{fieldOptions:{},separator:/\\n|[|' ><.,\-|]+|\\u0003/},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{separator:options.separator},options.fieldOptions[fieldName]);doc.tokenised[fieldName]="[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.normalised[fieldName]:doc.normalised[fieldName].split(fieldOptions.separator)}return this.push(doc),end()}},{stream:122,util:131}],31:[function(require,module){(function(process,Buffer){var stream=require("readable-stream"),eos=require("end-of-stream"),inherits=require("inherits"),shift=require("stream-shift"),SIGNAL_FLUSH=new Buffer([0]),onuncork=function(self,fn){self._corked?self.once("uncork",fn):fn()},destroyer=function(self,end){return function(err){err?self.destroy("premature close"===err.message?null:err):end&&!self._ended&&self.end()}},end=function(ws,fn){return ws?ws._writableState&&ws._writableState.finished?fn():ws._writableState?ws.end(fn):(ws.end(),void fn()):fn()},toStreams2=function(rs){return new stream.Readable({objectMode:!0,highWaterMark:16}).wrap(rs)},Duplexify=function(writable,readable,opts){return this instanceof Duplexify?(stream.Duplex.call(this,opts),this._writable=null,this._readable=null,this._readable2=null,this._forwardDestroy=!opts||opts.destroy!==!1,this._forwardEnd=!opts||opts.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,writable&&this.setWritable(writable),void(readable&&this.setReadable(readable))):new Duplexify(writable,readable,opts)};inherits(Duplexify,stream.Duplex),Duplexify.obj=function(writable,readable,opts){return opts||(opts={}),opts.objectMode=!0,opts.highWaterMark=16,new Duplexify(writable,readable,opts)},Duplexify.prototype.cork=function(){1===++this._corked&&this.emit("cork")},Duplexify.prototype.uncork=function(){this._corked&&0===--this._corked&&this.emit("uncork")},Duplexify.prototype.setWritable=function(writable){if(this._unwrite&&this._unwrite(),this.destroyed)return void(writable&&writable.destroy&&writable.destroy());if(null===writable||writable===!1)return void this.end();var self=this,unend=eos(writable,{writable:!0,readable:!1},destroyer(this,this._forwardEnd)),ondrain=function(){var ondrain=self._ondrain;self._ondrain=null,ondrain&&ondrain()},clear=function(){self._writable.removeListener("drain",ondrain),unend()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=clear,this.uncork()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)return void(readable&&readable.destroy&&readable.destroy());if(null===readable||readable===!1)return this.push(null),void this.resume();var self=this,unend=eos(readable,{writable:!1,readable:!0},destroyer(this)),onreadable=function(){self._forward()},onend=function(){self.push(null)},clear=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()};this._drained=!0,this._readable=readable,this._readable2=readable._readableState?readable:toStreams2(readable),this._readable2.on("readable",onreadable),this._readable2.on("end",onend),this._unread=clear,this._forward()},Duplexify.prototype._read=function(){this._drained=!0,this._forward()},Duplexify.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){this._forwarding=!0;for(var data;this._drained&&null!==(data=shift(this._readable2));)this.destroyed||(this._drained=this.push(data));this._forwarding=!1}},Duplexify.prototype.destroy=function(err){if(!this.destroyed){this.destroyed=!0;var self=this;process.nextTick(function(){self._destroy(err)})}},Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null,ondrain?ondrain(err):this.emit("error",err)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},Duplexify.prototype._write=function(data,enc,cb){return this.destroyed?cb():this._corked?onuncork(this,this._write.bind(this,data,enc,cb)):data===SIGNAL_FLUSH?this._finish(cb):this._writable?void(this._writable.write(data)===!1?this._ondrain=cb:cb()):cb()},Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend"),onuncork(this,function(){end(self._forwardEnd&&self._writable,function(){self._writableState.prefinished===!1&&(self._writableState.prefinished=!0),self.emit("prefinish"),onuncork(self,cb)})})},Duplexify.prototype.end=function(data,enc,cb){return"function"==typeof data?this.end(null,null,data):"function"==typeof enc?this.end(data,null,enc):(this._ended=!0,data&&this.write(data),this._writableState.ending||this.write(SIGNAL_FLUSH),stream.Writable.prototype.end.call(this,cb))},module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:85,buffer:9,"end-of-stream":32,inherits:41,"readable-stream":97,"stream-shift":123}],32:[function(require,module){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||opts.readable!==!1&&stream.readable,writable=opts.writable||opts.writable!==!1&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback()},onend=function(){readable=!1,writable||callback()},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback(new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),opts.error!==!1&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:33}],33:[function(require,module){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0})})},{wrappy:132}],34:[function(require,module){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||opts.readable!==!1&&stream.readable,writable=opts.writable||opts.writable!==!1&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback.call(stream)},onend=function(){readable=!1,writable||callback.call(stream)},onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback.call(stream,new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),opts.error!==!1&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:82}],35:[function(require,module){function init(type,message,cause){prr(this,{type:type,name:type,cause:"string"!=typeof message?message:cause,message:message&&"string"!=typeof message?message.message:message},"ewr")}function CustomError(message,cause){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),init.call(this,"CustomError",message,cause)}function createError(errno,type,proto){var err=function(message,cause){init.call(this,type,message,cause),"FilesystemError"==type&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(errno.errno[this.cause.errno]?errno.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return err.prototype=proto?new proto:new CustomError,err}var prr=require("prr");CustomError.prototype=new Error,module.exports=function(errno){var ce=function(type,proto){return createError(errno,type,proto)};return{CustomError:CustomError,FilesystemError:ce("FilesystemError"),createError:ce}}},{prr:37}],36:[function(require,module){var all=module.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];module.exports.errno={},module.exports.code={},all.forEach(function(error){module.exports.errno[error.errno]=error,module.exports.code[error.code]=error}),module.exports.custom=require("./custom")(module.exports),module.exports.create=module.exports.custom.createError},{"./custom":35}],37:[function(require,module){!function(name,context,definition){"undefined"!=typeof module&&module.exports?module.exports=definition():context[name]=definition()}("prr",this,function(){var setProperty="function"==typeof Object.defineProperty?function(obj,key,options){return Object.defineProperty(obj,key,options),obj}:function(obj,key,options){return obj[key]=options.value,obj},makeOptions=function(value,options){var oo="object"==typeof options,os=!oo&&"string"==typeof options,op=function(p){return oo?!!options[p]:os?options.indexOf(p[0])>-1:!1};return{enumerable:op("enumerable"),configurable:op("configurable"),writable:op("writable"),value:value}},prr=function(obj,key,value,options){var k;if(options=makeOptions(value,options),"object"==typeof key){for(k in key)Object.hasOwnProperty.call(key,k)&&(options.value=key[k],setProperty(obj,k,options));return obj}return setProperty(obj,key,options)};return prr})},{}],38:[function(require,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args);return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned&&(m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&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(0>position)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){var ret;return ret=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)}},{}],39:[function(require,module){!function(name,definition,global){"use strict";"function"==typeof define?define(definition):"undefined"!=typeof module&&module.exports?module.exports=definition():global[name]=definition()}("IDBStore",function(){"use strict";function mixin(target,source){var name,s;for(name in source)s=source[name],s!==empty[name]&&s!==target[name]&&(target[name]=s);return target}function hasVersionError(errorEvent){return"error"in errorEvent.target?"VersionError"==errorEvent.target.error.name:"errorCode"in errorEvent.target?12==errorEvent.target.errorCode:!1}var defaultErrorHandler=function(error){throw error},defaultSuccessHandler=function(){},defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:!0,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]},IDBStore=function(kwArgs,onStoreReady){"undefined"==typeof onStoreReady&&"function"==typeof kwArgs&&(onStoreReady=kwArgs),"[object Object]"!=Object.prototype.toString.call(kwArgs)&&(kwArgs={});for(var key in defaults)this[key]="undefined"!=typeof kwArgs[key]?kwArgs[key]:defaults[key];this.dbName=this.storePrefix+this.storeName,this.dbVersion=parseInt(this.dbVersion,10)||1,onStoreReady&&(this.onStoreReady=onStoreReady);var env="object"==typeof window?window:self,availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0],this.idb=env[this.implementation],this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange,this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"},this.openDB()},proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion),preventSuccessCallback=!1;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent))this.onError(new Error("The version number provided is lower than the existing one."));else{var error;if(errorEvent.target.error)error=errorEvent.target.error;else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;"errorCode"in errorEvent.target&&(errorMessage+=" with error code "+errorEvent.target.errorCode),error=new Error(errorMessage)}this.onError(error)}}.bind(this),openRequest.onsuccess=function(event){if(!preventSuccessCallback){if(this.db)return void this.onStoreReady();if(this.db=event.target.result,"string"==typeof this.db.version)return void this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));if(!this.db.objectStoreNames.contains(this.storeName))return void this.onError(new Error("Object store couldn't be created."));var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName)return preventSuccessCallback=!0,void this.onError(new Error("Cannot create index: No index name given."));if(this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName),complies=this.indexComplies(actualIndex,indexData);complies||(preventSuccessCallback=!0,this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else preventSuccessCallback=!0,this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))},this),existingIndexes.length&&(preventSuccessCallback=!0,this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),preventSuccessCallback||this.onStoreReady()}}.bind(this),openRequest.onupgradeneeded=function(event){if(this.db=event.target.result,this.db.objectStoreNames.contains(this.storeName))this.store=event.target.transaction.objectStore(this.storeName);else{var optionalParameters={autoIncrement:this.autoIncrement};null!==this.keyPath&&(optionalParameters.keyPath=this.keyPath),this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(indexName||(preventSuccessCallback=!0,this.onError(new Error("Cannot create index: No index name given."))),this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName),complies=this.indexComplies(actualIndex,indexData);complies||(this.store.deleteIndex(indexName),this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})},this),existingIndexes.length&&existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess,deleteRequest.onerror=onError}else onError(new Error("Browser does not support IndexedDB deleteDatabase!"))},put:function(key,value,onSuccess,onError){null!==this.keyPath&&(onError=onSuccess,onSuccess=value,value=key),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var putRequest,hasSuccess=!1,result=null,putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);return putTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},putTransaction.onabort=onError,putTransaction.onerror=onError,null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=putTransaction.objectStore(this.storeName).put(value)):putRequest=putTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},putRequest.onerror=onError,putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},getTransaction.onabort=onError,getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);return getRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getRequest.onerror=onError,getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},removeTransaction.onabort=onError,removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName)["delete"](key);return deleteRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},deleteRequest.onerror=onError,removeTransaction},batch:function(dataArray,onSuccess,onError){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),"[object Array]"!=Object.prototype.toString.call(dataArray))onError(new Error("dataArray argument must be of type Array."));else if(0===dataArray.length)return onSuccess(!0);var count=dataArray.length,called=!1,hasSuccess=!1,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(hasSuccess)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(){count--,0!==count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(operation){var type=operation.type,key=operation.key,value=operation.value,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err,type,key))};if("remove"==type){var deleteRequest=batchTransaction.objectStore(this.storeName)["delete"](key);deleteRequest.onsuccess=onItemSuccess,deleteRequest.onerror=onItemError}else if("put"==type){ -var putRequest;null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=batchTransaction.objectStore(this.storeName).put(value)):putRequest=batchTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError}},this),batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}});return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){"function"==typeof options&&(onSuccess=options,onError=onSuccess,options={}),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),options||(options={}),"[object Array]"!=Object.prototype.toString.call(dataArray)&&onError(new Error("dataArray argument must be of type Array."));var keyField=options.keyField||this.keyPath,count=dataArray.length,called=!1,hasSuccess=!1,index=0,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){hasSuccess?onSuccess(dataArray):onError(!1)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){var record=dataArray[index++];record[keyField]=event.target.result,count--,0!==count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(record){var putRequest,key=record.key,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err))};null!==this.keyPath?(this._addIdPropertyIfNeeded(record),putRequest=batchTransaction.objectStore(this.storeName).put(record)):putRequest=batchTransaction.objectStore(this.storeName).put(record,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError},this),batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),arrayType||(arrayType="sparse"),"[object Array]"!=Object.prototype.toString.call(keyArray))onError(new Error("keyArray argument must be of type Array."));else if(0===keyArray.length)return onSuccess([]);var data=[],count=keyArray.length,called=!1,hasSuccess=!1,result=null,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){event.target.result||"dense"==arrayType?data.push(event.target.result):"sparse"==arrayType&&data.length++,count--,0===count&&(called=!0,hasSuccess=!0,result=data)};return keyArray.forEach(function(key){var onItemError=function(err){called=!0,result=err,onError(err),batchTransaction.abort()},getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=onItemError},this),batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY),store=getAllTransaction.objectStore(this.storeName);return store.getAll?this._getAllNative(getAllTransaction,store,onSuccess,onError):this._getAllCursor(getAllTransaction,store,onSuccess,onError),getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;cursor?(all.push(cursor.value),cursor["continue"]()):(hasSuccess=!0,result=all)},cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){var callback=hasSuccess?onSuccess:onError;callback(result)},clearTransaction.onabort=onError,clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();return clearRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},clearRequest.onerror=onError,clearTransaction},_addIdPropertyIfNeeded:function(dataObj){"undefined"==typeof dataObj[this.keyPath]&&(dataObj[this.keyPath]=this._insertIdCount++ +Date.now())},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name,indexData.unique=!!indexData.unique,indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){var complies=["keyPath","unique","multiEntry"].every(function(key){if("multiEntry"==key&&void 0===actual[key]&&expected[key]===!1)return!0;if("keyPath"==key&&"[object Array]"==Object.prototype.toString.call(expected[key])){var exp=expected.keyPath,act=actual.keyPath;if("string"==typeof act)return exp.toString()==act;if("function"!=typeof act.contains&&"function"!=typeof act.indexOf)return!1;if(act.length!==exp.length)return!1;for(var i=0,m=exp.length;m>i;i++)if(!(act.contains&&act.contains(exp[i])||act.indexOf(-1!==exp[i])))return!1;return!0}return expected[key]==actual[key]});return complies},iterate:function(onItem,options){options=mixin({index:null,order:"ASC",autoContinue:!0,filterDuplicates:!1,keyRange:null,writeAccess:!1,onEnd:null,onError:defaultErrorHandler,limit:1/0,offset:0,allowItemRejection:!1},options||{});var directionType="desc"==options.order.toLowerCase()?"PREV":"NEXT";options.filterDuplicates&&(directionType+="_NO_DUPLICATE");var hasSuccess=!1,cursorTransaction=this.db.transaction([this.storeName],this.consts[options.writeAccess?"READ_WRITE":"READ_ONLY"]),cursorTarget=cursorTransaction.objectStore(this.storeName);options.index&&(cursorTarget=cursorTarget.index(options.index));var recordCount=0;cursorTransaction.oncomplete=function(){return hasSuccess?void(options.onEnd?options.onEnd():onItem(null)):void options.onError(null)},cursorTransaction.onabort=options.onError,cursorTransaction.onerror=options.onError;var cursorRequest=cursorTarget.openCursor(options.keyRange,this.consts[directionType]);return cursorRequest.onerror=options.onError,cursorRequest.onsuccess=function(event){var cursor=event.target.result;if(cursor)if(options.offset)cursor.advance(options.offset),options.offset=0;else{var onItemReturn=onItem(cursor.value,cursor,cursorTransaction);options.allowItemRejection&&onItemReturn===!1||recordCount++,options.autoContinue&&(recordCount+options.offset>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?0/0:(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=0>value||0===value&&0>1/value?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}},{}],41:[function(require,module){module.exports="function"==typeof Object.create?function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],42:[function(require,module,exports){var Readable=require("stream").Readable;exports.getIntersectionStream=function(sortedSets){for(var s=new Readable,i=0,ii=[],k=0;ksortedSets[i+1][ii[i+1]])ii[i+1]++;else if(i+2=sortedSets[k].length&&(finished=!0);i=0}return s.push(null),s}},{stream:122}],43:[function(require,module){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],44:[function(require,module){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],45:[function(require,module){function isBuffer(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}var Buffer=require("buffer").Buffer;module.exports=isBuffer},{buffer:9}],46:[function(require,module){function Codec(opts){this.opts=opts||{},this.encodings=encodings}var encodings=require("./lib/encodings");module.exports=Codec,Codec.prototype._encoding=function(encoding){return"string"==typeof encoding&&(encoding=encodings[encoding]),encoding||(encoding=encodings.id),encoding},Codec.prototype._keyEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&batchOpts.keyEncoding||opts&&opts.keyEncoding||this.opts.keyEncoding)},Codec.prototype._valueEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&(batchOpts.valueEncoding||batchOpts.encoding)||opts&&(opts.valueEncoding||opts.encoding)||this.opts.valueEncoding||this.opts.encoding)},Codec.prototype.encodeKey=function(key,opts,batchOpts){return this._keyEncoding(opts,batchOpts).encode(key)},Codec.prototype.encodeValue=function(value,opts,batchOpts){return this._valueEncoding(opts,batchOpts).encode(value)},Codec.prototype.decodeKey=function(key,opts){return this._keyEncoding(opts).decode(key)},Codec.prototype.decodeValue=function(value,opts){return this._valueEncoding(opts).decode(value)},Codec.prototype.encodeBatch=function(ops,opts){var self=this;return ops.map(function(_op){var op={type:_op.type,key:self.encodeKey(_op.key,opts,_op)};return self.keyAsBuffer(opts,_op)&&(op.keyEncoding="binary"),_op.prefix&&(op.prefix=_op.prefix),"value"in _op&&(op.value=self.encodeValue(_op.value,opts,_op),self.valueAsBuffer(opts,_op)&&(op.valueEncoding="binary")),op})};var ltgtKeys=["lt","gt","lte","gte","start","end"];Codec.prototype.encodeLtgt=function(ltgt){var self=this,ret={};return Object.keys(ltgt).forEach(function(key){ret[key]=ltgtKeys.indexOf(key)>-1?self.encodeKey(ltgt[key],ltgt):ltgt[key]}),ret},Codec.prototype.createStreamDecoder=function(opts){var self=this;return opts.keys&&opts.values?function(key,value){return{key:self.decodeKey(key,opts),value:self.decodeValue(value,opts)}}:opts.keys?function(key){return self.decodeKey(key,opts)}:opts.values?function(_,value){return self.decodeValue(value,opts)}:function(){}},Codec.prototype.keyAsBuffer=function(opts){return this._keyEncoding(opts).buffer},Codec.prototype.valueAsBuffer=function(opts){return this._valueEncoding(opts).buffer}},{"./lib/encodings":47}],47:[function(require,module,exports){(function(Buffer){function identity(value){return value}function isBinary(data){return void 0===data||null===data||Buffer.isBuffer(data)}exports.utf8=exports["utf-8"]={encode:function(data){return isBinary(data)?data:String(data)},decode:identity,buffer:!1,type:"utf8"},exports.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},exports.binary={encode:function(data){return isBinary(data)?data:new Buffer(data)},decode:identity,buffer:!0,type:"binary"},exports.id={encode:function(data){return data},decode:function(data){return data},buffer:!1,type:"id"};var bufferEncodings=["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"];bufferEncodings.forEach(function(type){exports[type]={encode:function(data){return isBinary(data)?data:new Buffer(data,type)},decode:function(buffer){return buffer.toString(type)},buffer:!0,type:type}})}).call(this,require("buffer").Buffer)},{buffer:9}],48:[function(require,module){var createError=require("errno").create,LevelUPError=createError("LevelUPError"),NotFoundError=createError("NotFoundError",LevelUPError);NotFoundError.prototype.notFound=!0,NotFoundError.prototype.status=404,module.exports={LevelUPError:LevelUPError,InitializationError:createError("InitializationError",LevelUPError),OpenError:createError("OpenError",LevelUPError),ReadError:createError("ReadError",LevelUPError),WriteError:createError("WriteError",LevelUPError),NotFoundError:NotFoundError,EncodingError:createError("EncodingError",LevelUPError)}},{errno:36}],49:[function(require,module){function ReadStream(iterator,options){return this instanceof ReadStream?(Readable.call(this,extend(options,{objectMode:!0})),this._iterator=iterator,this._destroyed=!1,this._decoder=null,options&&options.decoder&&(this._decoder=options.decoder),void this.on("end",this._cleanup.bind(this))):new ReadStream(iterator,options)}var inherits=require("inherits"),Readable=require("readable-stream").Readable,extend=require("xtend"),EncodingError=require("level-errors").EncodingError;module.exports=ReadStream,inherits(ReadStream,Readable),ReadStream.prototype._read=function(){var self=this;this._destroyed||this._iterator.next(function(err,key,value){if(!self._destroyed){if(err)return self.emit("error",err);if(void 0===key&&void 0===value)self.push(null);else{if(!self._decoder)return self.push({key:key,value:value});try{var value=self._decoder(key,value)}catch(err){return self.emit("error",new EncodingError(err)),void self.push(null)}self.push(value)}}})},ReadStream.prototype.destroy=ReadStream.prototype._cleanup=function(){var self=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(err){return err?self.emit("error",err):void self.emit("close")}))}},{inherits:41,"level-errors":48,"readable-stream":56,xtend:133}],50:[function(require,module){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],51:[function(require,module){(function(process){function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;l>i;i++)f(xs[i],i)}module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys},util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable),forEach(objectKeys(Writable.prototype),function(method){Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method])})}).call(this,require("_process"))},{"./_stream_readable":53,"./_stream_writable":55,_process:85,"core-util-is":11,inherits:41}],52:[function(require,module){function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=require("./_stream_transform"),util=require("core-util-is");util.inherits=require("inherits"),util.inherits(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":54,"core-util-is":11,inherits:41}],53:[function(require,module){(function(process){function ReadableState(options,stream){var Duplex=require("./_stream_duplex");options=options||{};var hwm=options.highWaterMark,defaultHwm=options.objectMode?16:16384;this.highWaterMark=hwm||0===hwm?hwm:defaultHwm,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.objectMode=!!options.objectMode,stream instanceof Duplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.defaultEncoding=options.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){require("./_stream_duplex");return this instanceof Readable?(this._readableState=new ReadableState(options,this),this.readable=!0,void Stream.call(this)):new Readable(options)}function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er)stream.emit("error",er);else if(util.isNullOrUndefined(chunk))state.reading=!1,state.ended||onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;32>p;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:isNaN(n)||util.isNull(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:0>=n?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return util.isBuffer(chunk)||util.isString(chunk)||util.isNullOrUndefined(chunk)||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(ni&&n>c;i++){var buf=list[0],cpy=Math.min(n-c,buf.length);stringMode?ret+=buf.slice(0,cpy):buf.copy(ret,c,0,cpy),cpy0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;l>i;i++)f(xs[i],i)}function indexOf(xs,x){for(var i=0,l=xs.length;l>i;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var isArray=require("isarray"),Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;EE.listenerCount||(EE.listenerCount=function(emitter,type){return emitter.listeners(type).length});var Stream=require("stream"),util=require("core-util-is");util.inherits=require("inherits");var StringDecoder,debug=require("util");debug=debug&&debug.debuglog?debug.debuglog("stream"):function(){},util.inherits(Readable,Stream),Readable.prototype.push=function(chunk,encoding){var state=this._readableState;return util.isString(chunk)&&!state.objectMode&&(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=new Buffer(chunk,encoding),encoding="")),readableAddChunk(this,state,chunk,encoding,!1)},Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",!0)},Readable.prototype.setEncoding=function(enc){return StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this._readableState.decoder=new StringDecoder(enc),this._readableState.encoding=enc,this};var MAX_HWM=8388608;Readable.prototype.read=function(n){debug("read",n);var state=this._readableState,nOrig=n;if((!util.isNumber(n)||n>0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,util.isNull(ret)&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),util.isNull(ret)||this.emit("data",ret),ret},Readable.prototype._read=function(){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);!1===ret&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;len>i;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);return-1===i?this:(state.pipes.splice(i,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if("data"===ev&&!1!==this._readableState.flowing&&this.resume(),"readable"===ev&&this.readable){var state=this._readableState;if(!state.readableListening)if(state.readableListening=!0,state.emittedReadable=!1,state.needReadable=!0,state.reading)state.length&&emitReadable(this,state);else{var self=this;process.nextTick(function(){debug("readable nexttick read 0"),self.read(0)})}}return res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!0,state.reading||(debug("resume read 0"),this.read(0)),resume(this,state)),this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Readable.prototype.wrap=function(stream){var state=this._readableState,paused=!1,self=this;stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&self.push(chunk)}self.push(null)}),stream.on("data",function(chunk){if(debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),chunk&&(state.objectMode||chunk.length)){var ret=self.push(chunk);ret||(paused=!0,stream.pause())}});for(var i in stream)util.isFunction(stream[i])&&util.isUndefined(this[i])&&(this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i));var events=["error","close","destroy","pause","resume"];return forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))}),self._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},self},Readable._fromList=fromList}).call(this,require("_process"))},{"./_stream_duplex":51,_process:85,buffer:9,"core-util-is":11,events:38,inherits:41,isarray:50,stream:122,"string_decoder/":57,util:6}],54:[function(require,module){function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)},this.needTransform=!1, -this.transforming=!1,this.writecb=null,this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=!1;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null,ts.writecb=null,util.isNullOrUndefined(data)||stream.push(data),cb&&cb(er);var rs=stream._readableState;rs.reading=!1,(rs.needReadable||rs.length1){for(var cbs=[],c=0;c=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&56319>=charCode)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&56319>=charCode){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(2>=i&&c>>4==14){this.charLength=3;break}if(3>=i&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:9}],58:[function(require,module){(function(Buffer){function Level(location){if(!(this instanceof Level))return new Level(location);if(!location)throw new Error("constructor requires at least a location argument");this.IDBOptions={},this.location=location}module.exports=Level;var IDB=require("idb-wrapper"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,util=require("util"),Iterator=require("./iterator"),isBuffer=require("isbuffer"),xtend=require("xtend"),toBuffer=require("typedarray-to-buffer");util.inherits(Level,AbstractLevelDOWN),Level.prototype._open=function(options,callback){var self=this,idbOpts={storeName:this.location,autoIncrement:!1,keyPath:null,onStoreReady:function(){callback&&callback(null,self.idb)},onError:function(err){callback&&callback(err)}};xtend(idbOpts,options),this.IDBOptions=idbOpts,this.idb=new IDB(idbOpts)},Level.prototype._get=function(key,options,callback){this.idb.get(key,function(value){if(void 0===value)return callback(new Error("NotFound"));var asBuffer=!0;return options.asBuffer===!1&&(asBuffer=!1),options.raw&&(asBuffer=!1),asBuffer&&(value=value instanceof Uint8Array?toBuffer(value):new Buffer(String(value))),callback(null,value,key)},callback)},Level.prototype._del=function(id,options,callback){this.idb.remove(id,callback,callback)},Level.prototype._put=function(key,value,options,callback){value instanceof ArrayBuffer&&(value=toBuffer(new Uint8Array(value)));var obj=this.convertEncoding(key,value,options);Buffer.isBuffer(obj.value)&&(obj.value=new Uint8Array("function"==typeof value.toArrayBuffer?value.toArrayBuffer():value)),this.idb.put(obj.key,obj.value,function(){callback()},callback)},Level.prototype.convertEncoding=function(key,value,options){if(options.raw)return{key:key,value:value};if(value){var stringed=value.toString();"NaN"===stringed&&(value="NaN")}var valEnc=options.valueEncoding,obj={key:key,value:value};return!value||valEnc&&"binary"===valEnc||"object"!=typeof obj.value&&(obj.value=stringed),obj},Level.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),new Iterator(this.idb,options)},Level.prototype._batch=function(array,options,callback){var i,k,copiedOp,currentOp,modified=[];if(0===array.length)return setTimeout(callback,0);for(i=0;i0&&this._count++>=this._limit&&(shouldCall=!1),shouldCall&&this.callback(!1,cursor.key,cursor.value),cursor&&cursor["continue"]()},Iterator.prototype._next=function(callback){return callback?this._keyRangeError?callback():(this._started||(this.createIterator(),this._started=!0),void(this.callback=callback)):new Error("next() requires a callback argument")}},{"abstract-leveldown":62,ltgt:81,util:131}],60:[function(require,module){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;if(err=this._db._checkKeyValue(value,"value",this._db._isBuffer))throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:85}],61:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{_process:85,dup:15}],62:[function(require,module){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");return"object"!=typeof options&&(options={}),"function"==typeof this._open?this._open(options,callback):void process.nextTick(callback)},AbstractLevelDOWN.prototype.close=function(callback){if("function"!=typeof callback)throw new Error("close() requires a callback argument");return"function"==typeof this._close?this._close(callback):void process.nextTick(callback)},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(err=this._checkKeyValue(value,"value",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));"object"!=typeof options&&(options={});for(var e,err,i=0,l=array.length;l>i;i++)if(e=array[i],"object"==typeof e){if(err=this._checkKeyValue(e.type,"type",this._isBuffer))return callback(err);if(err=this._checkKeyValue(e.key,"key",this._isBuffer))return callback(err);if("put"==e.type&&(err=this._checkKeyValue(e.value,"value",this._isBuffer)))return callback(err)}return"function"==typeof this._batch?this._batch(array,options,callback):void process.nextTick(callback)},AbstractLevelDOWN.prototype.approximateSize=function(start,end,callback){if(null==start||null==end||"function"==typeof start||"function"==typeof end)throw new Error("approximateSize() requires valid `start`, `end` and `callback` arguments");if("function"!=typeof callback)throw new Error("approximateSize() requires a callback argument");return this._isBuffer(start)||(start=String(start)),this._isBuffer(end)||(end=String(end)),"function"==typeof this._approximateSize?this._approximateSize(start,end,callback):void process.nextTick(function(){callback(null,0)})},AbstractLevelDOWN.prototype._setupIteratorOptions=function(options){var self=this;return options=xtend(options),["start","end","gt","gte","lt","lte"].forEach(function(o){options[o]&&self._isBuffer(options[o])&&0===options[o].length&&delete options[o]}),options.reverse=!!options.reverse,options.reverse&&options.lt&&(options.start=options.lt),options.reverse&&options.lte&&(options.start=options.lte),!options.reverse&&options.gt&&(options.start=options.gt),!options.reverse&&options.gte&&(options.start=options.gte),(options.reverse&&options.lt&&!options.lte||!options.reverse&&options.gt&&!options.gte)&&(options.exclusiveStart=!0),options},AbstractLevelDOWN.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),options=this._setupIteratorOptions(options),"function"==typeof this._iterator?this._iterator(options):new AbstractIterator(this)},AbstractLevelDOWN.prototype._chainedBatch=function(){return new AbstractChainedBatch(this)},AbstractLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},AbstractLevelDOWN.prototype._checkKeyValue=function(obj,type){if(null===obj||void 0===obj)return new Error(type+" cannot be `null` or `undefined`");if(this._isBuffer(obj)){if(0===obj.length)return new Error(type+" cannot be an empty Buffer")}else if(""===String(obj))return new Error(type+" cannot be an empty String")},module.exports.AbstractLevelDOWN=AbstractLevelDOWN,module.exports.AbstractIterator=AbstractIterator,module.exports.AbstractChainedBatch=AbstractChainedBatch}).call(this,{isBuffer:require("../../../is-buffer/index.js")},require("_process"))},{"../../../is-buffer/index.js":43,"./abstract-chained-batch":60,"./abstract-iterator":61,_process:85,xtend:63}],63:[function(require,module){function extend(){for(var target={},i=0;i2?arguments[2]:null;if(l===+l)for(i=0;l>i;i++)null===context?fn(isString?obj.charAt(i):obj[i],i,obj):fn.call(context,isString?obj.charAt(i):obj[i],i,obj);else for(k in obj)hasOwn.call(obj,k)&&(null===context?fn(obj[k],k,obj):fn.call(context,obj[k],k,obj))}},{}],65:[function(require,module){module.exports=Object.keys||require("./shim")},{"./shim":67}],66:[function(require,module){var toString=Object.prototype.toString;module.exports=function isArguments(value){var str=toString.call(value),isArguments="[object Arguments]"===str;return isArguments||(isArguments="[object Array]"!==str&&null!==value&&"object"==typeof value&&"number"==typeof value.length&&value.length>=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],67:[function(require,module){!function(){"use strict";var keysShim,has=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,forEach=require("./foreach"),isArgs=require("./isArguments"),hasDontEnumBug=!{toString:null}.propertyIsEnumerable("toString"),hasProtoEnumBug=function(){}.propertyIsEnumerable("prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];keysShim=function(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toString.call(object),isArguments=isArgs(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");if(isArguments)forEach(object,function(value){theKeys.push(value)});else{var name,skipProto=hasProtoEnumBug&&isFunction;for(name in object)skipProto&&"prototype"===name||!has.call(object,name)||theKeys.push(name)}if(hasDontEnumBug){var ctor=object.constructor,skipConstructor=ctor&&ctor.prototype===object;forEach(dontEnums,function(dontEnum){skipConstructor&&"constructor"===dontEnum||!has.call(object,dontEnum)||theKeys.push(dontEnum)})}return theKeys},module.exports=keysShim}()},{"./foreach":64,"./isArguments":66}],68:[function(require,module){function hasKeys(source){return null!==source&&("object"==typeof source||"function"==typeof source)}module.exports=hasKeys},{}],69:[function(require,module){function extend(){for(var target={},i=0;i=1.3.5 <2.0.0",type:"range"},"/Users/fergusmcdowall/node/search-index"]],_from:"levelup@>=1.3.5 <2.0.0",_id:"levelup@1.3.5",_inCache:!0,_installable:!0,_location:"/levelup",_nodeVersion:"7.4.0",_npmOperationalInternal:{host:"packages-18-east.internal.npmjs.com",tmp:"tmp/levelup-1.3.5.tgz_1488477248468_0.036320413229987025"},_npmUser:{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},_npmVersion:"4.0.5",_phantomChildren:{},_requested:{raw:"levelup@^1.3.5",scope:null,escapedName:"levelup",name:"levelup",rawSpec:"^1.3.5",spec:">=1.3.5 <2.0.0",type:"range"},_requiredBy:["/","/search-index-adder","/search-index-searcher"],_resolved:"https://registry.npmjs.org/levelup/-/levelup-1.3.5.tgz",_shasum:"fa80a972b74011f2537c8b65678bd8b5188e4e66",_shrinkwrap:null,_spec:"levelup@^1.3.5",_where:"/Users/fergusmcdowall/node/search-index",browser:{leveldown:!1,"leveldown/package":!1,semver:!1},bugs:{url:"https://github.com/level/levelup/issues"},contributors:[{name:"Rod Vagg",email:"r@va.gg",url:"https://github.com/rvagg"},{name:"John Chesley",email:"john@chesl.es",url:"https://github.com/chesles/"},{name:"Jake Verbaten",email:"raynos2@gmail.com",url:"https://github.com/raynos"},{name:"Dominic Tarr",email:"dominic.tarr@gmail.com",url:"https://github.com/dominictarr"},{name:"Max Ogden",email:"max@maxogden.com",url:"https://github.com/maxogden"},{name:"Lars-Magnus Skog",email:"ralphtheninja@riseup.net",url:"https://github.com/ralphtheninja"},{name:"David Björklund",email:"david.bjorklund@gmail.com",url:"https://github.com/kesla"},{name:"Julian Gruber",email:"julian@juliangruber.com",url:"https://github.com/juliangruber"},{name:"Paolo Fragomeni",email:"paolo@async.ly",url:"https://github.com/0x00a"},{name:"Anton Whalley",email:"anton.whalley@nearform.com",url:"https://github.com/No9"},{name:"Matteo Collina",email:"matteo.collina@gmail.com",url:"https://github.com/mcollina"},{name:"Pedro Teixeira",email:"pedro.teixeira@gmail.com",url:"https://github.com/pgte"},{name:"James Halliday",email:"mail@substack.net",url:"https://github.com/substack"},{name:"Jarrett Cruger",email:"jcrugzz@gmail.com",url:"https://github.com/jcrugzz"}],dependencies:{"deferred-leveldown":"~1.2.1","level-codec":"~6.1.0","level-errors":"~1.0.3","level-iterator-stream":"~1.3.0",prr:"~1.0.1",semver:"~5.1.0",xtend:"~4.0.0"},description:"Fast & simple storage - a Node.js-style LevelDB wrapper",devDependencies:{async:"~1.5.0",bustermove:"~1.0.0",delayed:"~1.0.1",faucet:"~0.0.1",leveldown:"^1.1.0",memdown:"~1.1.0","msgpack-js":"~0.3.0",referee:"~1.2.0",rimraf:"~2.4.3","slow-stream":"0.0.4",tap:"~2.3.1",tape:"~4.2.1"},directories:{},dist:{shasum:"fa80a972b74011f2537c8b65678bd8b5188e4e66",tarball:"https://registry.npmjs.org/levelup/-/levelup-1.3.5.tgz"},gitHead:"ed5a54202085839784f1189f1266e9c379d64081",homepage:"https://github.com/level/levelup",keywords:["leveldb","stream","database","db","store","storage","json"],license:"MIT",main:"lib/levelup.js",maintainers:[{name:"rvagg",email:"rod@vagg.org"},{name:"ralphtheninja",email:"ralphtheninja@riseup.net"},{name:"juliangruber",email:"julian@juliangruber.com"}],name:"levelup",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/level/levelup.git"},scripts:{test:"tape test/*-test.js | faucet"},version:"1.3.5"}},{}],74:[function(require,module){(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){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++indexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?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){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor;return pattern.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&&MAX_SAFE_INTEGER>=value}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 difference=baseRest(function(array,values){return isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,!0)):[]}),isArray=Array.isArray;module.exports=difference}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],75:[function(require,module){(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){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++indexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=120&&array.length>=120)?new SetCache(othIndex&&array):void 0}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++index-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,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.*?")+"$"),splice=arrayProto.splice,nativeMax=Math.max,nativeMin=Math.min,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 intersection=baseRest(function(arrays){var mapped=arrayMap(arrays,castArrayLikeObject);return mapped.length&&mapped[0]===arrays[0]?baseIntersection(mapped):[]});module.exports=intersection}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],76:[function(require,module,exports){(function(global){function arrayFilter(array,predicate){for(var index=-1,length=null==array?0:array.length,resIndex=0,result=[];++indexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;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&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&length>value}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function isPrototype(value){var Ctor=value&&value.constructor,proto="function"==typeof Ctor&&Ctor.prototype||objectProto;return value===proto}function objectToString(value){return nativeObjectToString.call(value)}function toSource(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+""}catch(e){}}return""}function eq(value,other){return value===other||value!==value&&other!==other}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isEqual(value,other){return baseIsEqual(value,other)}function isFunction(value){if(!isObject(value))return!1;var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&MAX_SAFE_INTEGER>=value}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function stubArray(){return[]}function stubFalse(){return!1}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",asyncTag="[object AsyncFunction]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",nullTag="[object Null]",objectTag="[object Object]",promiseTag="[object Promise]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",undefinedTag="[object Undefined]",weakMapTag="[object WeakMap]",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]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!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 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&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),nativeObjectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Buffer=moduleExports?root.Buffer:void 0,Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,nativeKeys=overArg(Object.keys,Object),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;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 getSymbols=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray,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=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag}return result});var isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isBuffer=nativeIsBuffer||stubFalse,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module.exports=isEqual}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],77:[function(require,module){function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if("number"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return baseSortedIndexBy(array,value,identity,retHighest)}function baseSortedIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsNull=null===value,valIsSymbol=isSymbol(value),valIsUndefined=void 0===value;high>low;){var mid=nativeFloor((low+high)/2),computed=iteratee(array[mid]),othIsDefined=void 0!==computed,othIsNull=null===computed,othIsReflexive=computed===computed,othIsSymbol=isSymbol(computed);if(valIsNaN)var setLow=retHighest||othIsReflexive;else setLow=valIsUndefined?othIsReflexive&&(retHighest||othIsDefined):valIsNull?othIsReflexive&&othIsDefined&&(retHighest||!othIsNull):valIsSymbol?othIsReflexive&&othIsDefined&&!othIsNull&&(retHighest||!othIsSymbol):othIsNull||othIsSymbol?!1:retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function sortedIndexOf(array,value){var length=array?array.length:0;if(length){var index=baseSortedIndex(array,value);if(length>index&&eq(array[index],value))return index}return-1}function eq(value,other){return value===other||value!==value&&other!==other}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function identity(value){return value}var MAX_ARRAY_LENGTH=4294967295,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,symbolTag="[object Symbol]",objectProto=Object.prototype,objectToString=objectProto.toString,nativeFloor=Math.floor,nativeMin=Math.min;module.exports=sortedIndexOf},{}],78:[function(require,module){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 arrayPush(array,values){for(var index=-1,length=values.length,offset=array.length;++indexstart&&(start=-start>length?0:length+start),end=end>length?length:end,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=void 0===start?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}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){var sign=0>value?-1:1;return sign*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 FUNC_ERROR_TEXT="Expected a function",INFINITY=1/0,MAX_INTEGER=1.7976931348623157e308,NAN=0/0,symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString,nativeMax=Math.max;module.exports=spread},{}],79:[function(require,module){(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){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++indexindex)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?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){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor;return pattern.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&&MAX_SAFE_INTEGER>=value}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,union=baseRest(function(arrays){return baseUniq(baseFlatten(arrays,1,isArrayLikeObject,!0))}),isArray=Array.isArray;module.exports=union}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],80:[function(require,module){(function(global){function arrayIncludes(array,value){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++indexindex)return!1;var lastIndex=data.length-1; - -return index==lastIndex?data.pop():splice.call(data,index,1),!0}function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?void 0:data[index][1]}function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return 0>index?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){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexi;i++){var cmp=a[i]-b[i];if(cmp)return cmp}return a.length-b.length}return b>a?-1:a>b?1:0};var lowerBoundKey=exports.lowerBoundKey=function(range){return hasKey(range,"gt")||hasKey(range,"gte")||hasKey(range,"min")||(range.reverse?hasKey(range,"end"):hasKey(range,"start"))||void 0},lowerBound=exports.lowerBound=function(range){var k=lowerBoundKey(range);return k&&range[k]},lowerBoundInclusive=exports.lowerBoundInclusive=function(range){return has(range,"gt")?!1:!0},upperBoundInclusive=exports.upperBoundInclusive=function(range){return has(range,"lt")?!1:!0},lowerBoundExclusive=exports.lowerBoundExclusive=function(range){return!lowerBoundInclusive(range)},upperBoundExclusive=exports.upperBoundExclusive=function(range){return!upperBoundInclusive(range)},upperBoundKey=exports.upperBoundKey=function(range){return hasKey(range,"lt")||hasKey(range,"lte")||hasKey(range,"max")||(range.reverse?hasKey(range,"start"):hasKey(range,"end"))||void 0},upperBound=exports.upperBound=function(range){var k=upperBoundKey(range);return k&&range[k]};exports.toLtgt=function(range,_range,map,lower,upper){_range=_range||{},map=map||id;var defaults=arguments.length>3,lb=exports.lowerBoundKey(range),ub=exports.upperBoundKey(range);return lb?"gt"===lb?_range.gt=map(range.gt,!1):_range.gte=map(range[lb],!1):defaults&&(_range.gte=map(lower,!1)),ub?"lt"===ub?_range.lt=map(range.lt,!0):_range.lte=map(range[ub],!0):defaults&&(_range.lte=map(upper,!0)),null!=range.reverse&&(_range.reverse=!!range.reverse),has(_range,"max")&&delete _range.max,has(_range,"min")&&delete _range.min,has(_range,"start")&&delete _range.start,has(_range,"end")&&delete _range.end,_range},exports.contains=function(range,key,compare){compare=compare||exports.compare;var lb=lowerBound(range);if(isDef(lb)){var cmp=compare(key,lb);if(0>cmp||0===cmp&&lowerBoundExclusive(range))return!1}var ub=upperBound(range);if(isDef(ub)){var cmp=compare(key,ub);if(cmp>0||0===cmp&&upperBoundExclusive(range))return!1}return!0},exports.filter=function(range,compare){return function(key){return exports.contains(range,key,compare)}}}).call(this,{isBuffer:require("../is-buffer/index.js")})},{"../is-buffer/index.js":43}],82:[function(require,module){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:132}],83:[function(require,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],84:[function(require,module){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i1)for(var i=1;i0;return destroyer(stream,reading,writing,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)};module.exports=pump},{"end-of-stream":34,fs:6,once:82}],88:[function(require,module){var pump=require("pump"),inherits=require("inherits"),Duplexify=require("duplexify"),toArray=function(args){return args.length?Array.isArray(args[0])?args[0]:Array.prototype.slice.call(args):[]},define=function(opts){var Pumpify=function(){var streams=toArray(arguments);return this instanceof Pumpify?(Duplexify.call(this,null,null,opts),void(streams.length&&this.setPipeline(streams))):new Pumpify(streams)};return inherits(Pumpify,Duplexify),Pumpify.prototype.setPipeline=function(){var streams=toArray(arguments),self=this,ended=!1,w=streams[0],r=streams[streams.length-1];r=r.readable?r:null,w=w.writable?w:null;var onclose=function(){streams[0].emit("error",new Error("stream was destroyed"))};return this.on("close",onclose),this.on("prefinish",function(){ended||self.cork()}),pump(streams,function(err){return self.removeListener("close",onclose),err?self.destroy(err):(ended=!0,void self.uncork())}),this.destroyed?onclose():(this.setWritable(w),void this.setReadable(r))},Pumpify};module.exports=define({destroy:!1}),module.exports.obj=define({destroy:!1,objectMode:!0,highWaterMark:16})},{duplexify:31,inherits:41,pump:87}],89:[function(require,module){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":90}],90:[function(require,module){"use strict";function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var processNextTick=require("process-nextick-args"),util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,list.head=p.next?p.next:list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,list.head=p.next?p.next:list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;l>i;i++)f(xs[i],i)}function indexOf(xs,x){for(var i=0,l=xs.length;l>i;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var Duplex,processNextTick=require("process-nextick-args"),isArray=require("isarray");Readable.ReadableState=ReadableState;var Stream,EElistenerCount=(require("events").EventEmitter,function(emitter,type){return emitter.listeners(type).length});!function(){try{Stream=require("stream")}catch(_){}finally{Stream||(Stream=require("events").EventEmitter)}}();var Buffer=require("buffer").Buffer,bufferShim=require("buffer-shims"),util=require("core-util-is");util.inherits=require("inherits");var debugUtil=require("util"),debug=void 0;debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function(){};var StringDecoder,BufferList=require("./internal/streams/BufferList");util.inherits(Readable,Stream),Readable.prototype.push=function(chunk,encoding){var state=this._readableState;return state.objectMode||"string"!=typeof chunk||(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=bufferShim.from(chunk,encoding),encoding="")),readableAddChunk(this,state,chunk,encoding,!1)},Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",!0)},Readable.prototype.isPaused=function(){return this._readableState.flowing===!1},Readable.prototype.setEncoding=function(enc){return StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this._readableState.decoder=new StringDecoder(enc),this._readableState.encoding=enc,this};var MAX_HWM=8388608;Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1;var ret=dest.write(chunk);!1!==ret||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;len>i;i++)dests[i].emit("unpipe",this);return this}var index=indexOf(state.pipes,dest);return-1===index?this:(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if("data"===ev)this._readableState.flowing!==!1&&this.resume();else if("readable"===ev){var state=this._readableState;state.endEmitted||state.readableListening||(state.readableListening=state.needReadable=!0,state.emittedReadable=!1,state.reading?state.length&&emitReadable(this,state):processNextTick(nReadingNextTick,this))}return res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!0,resume(this,state)),this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Readable.prototype.wrap=function(stream){var state=this._readableState,paused=!1,self=this;stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&self.push(chunk)}self.push(null)}),stream.on("data",function(chunk){if(debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),(!state.objectMode||null!==chunk&&void 0!==chunk)&&(state.objectMode||chunk&&chunk.length)){var ret=self.push(chunk);ret||(paused=!0,stream.pause())}});for(var i in stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i));var events=["error","close","destroy","pause","resume"];return forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))}),self._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},self},Readable._fromList=fromList}).call(this,require("_process"))},{"./_stream_duplex":90,"./internal/streams/BufferList":95,_process:85,buffer:9,"buffer-shims":8,"core-util-is":11,events:38,inherits:41,isarray:44,"process-nextick-args":84,"string_decoder/":124,util:6}],93:[function(require,module){"use strict";function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=!1;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null,ts.writecb=null,null!==data&&void 0!==data&&stream.push(data),cb(er); - -var rs=stream._readableState;rs.reading=!1,(rs.needReadable||rs.length-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream,internalUtil={deprecate:require("util-deprecate")};!function(){try{Stream=require("stream")}catch(_){}finally{Stream||(Stream=require("events").EventEmitter)}}();var Buffer=require("buffer").Buffer,bufferShim=require("buffer-shims");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return realHasInstance.call(this,object)?!0:object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=Buffer.isBuffer(chunk);return"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(this,require("_process"))},{"./_stream_duplex":90,_process:85,buffer:9,"buffer-shims":8,"core-util-is":11,events:38,inherits:41,"process-nextick-args":84,"util-deprecate":128}],95:[function(require,module){"use strict";function BufferList(){this.head=null,this.tail=null,this.length=0}var bufferShim=(require("buffer").Buffer,require("buffer-shims"));module.exports=BufferList,BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return bufferShim.alloc(0);if(1===this.length)return this.head.data;for(var ret=bufferShim.allocUnsafe(n>>>0),p=this.head,i=0;p;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},{buffer:9,"buffer-shims":8}],96:[function(require,module){module.exports=require("./readable").PassThrough},{"./readable":97}],97:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":90,"./lib/_stream_passthrough.js":91,"./lib/_stream_readable.js":92,"./lib/_stream_transform.js":93,"./lib/_stream_writable.js":94}],98:[function(require,module){module.exports=require("./readable").Transform},{"./readable":97}],99:[function(require,module){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":94}],100:[function(require,module){function throwsMessage(err){return"[Throws: "+(err?err.message:"?")+"]"}function safeGetValueFromPropertyOnObject(obj,property){if(hasProp.call(obj,property))try{return obj[property]}catch(err){return throwsMessage(err)}return obj[property]}function ensureProperties(obj){function visit(obj){if(null===obj||"object"!=typeof obj)return obj;if(-1!==seen.indexOf(obj))return"[Circular]";if(seen.push(obj),"function"==typeof obj.toJSON)try{return visit(obj.toJSON())}catch(err){return throwsMessage(err)}return Array.isArray(obj)?obj.map(visit):Object.keys(obj).reduce(function(result,prop){return result[prop]=visit(safeGetValueFromPropertyOnObject(obj,prop)),result},{})}var seen=[];return visit(obj)}var hasProp=Object.prototype.hasOwnProperty;module.exports=function(data){return JSON.stringify(ensureProperties(data))},module.exports.ensureProperties=ensureProperties},{}],101:[function(require,module){const DBEntries=require("./lib/delete.js").DBEntries,DBWriteCleanStream=require("./lib/replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./lib/replicate.js").DBWriteMergeStream,DocVector=require("./lib/delete.js").DocVector,IndexBatch=require("./lib/add.js").IndexBatch,Readable=require("stream").Readable,RecalibrateDB=require("./lib/delete.js").RecalibrateDB,bunyan=require("bunyan"),del=require("./lib/delete.js"),docProc=require("docproc"),leveldown=require("leveldown"),levelup=require("levelup"),pumpify=require("pumpify"),async=require("async");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){var Indexer={};Indexer.options=options;var q=async.queue(function(batch,callback){const s=new Readable({objectMode:!0});batch.batch.forEach(function(doc){s.push(doc)}),s.push(null),s.pipe(Indexer.defaultPipeline(batch.batchOps)).pipe(Indexer.add()).on("data",function(){}).on("end",function(){return callback()}).on("error",function(err){return callback(err)})},1);return Indexer.add=function(){return pumpify.obj(new IndexBatch(Indexer),new DBWriteMergeStream(options))},Indexer.concurrentAdd=function(batchOps,batch,done){q.push({batch:batch,batchOps:batchOps},function(err){done(err)})},Indexer.close=function(callback){options.indexes.close(function(err){for(;!options.indexes.isClosed();)options.log.debug("closing...");options.indexes.isClosed()&&(options.log.debug("closed..."),callback(err))})},Indexer.dbWriteStream=function(streamOps){return streamOps=Object.assign({},{merge:!0},streamOps),streamOps.merge?new DBWriteMergeStream(options):new DBWriteCleanStream(options)},Indexer.defaultPipeline=function(batchOptions){return batchOptions=Object.assign({},options,batchOptions),docProc.pipeline(batchOptions)},Indexer.deleteStream=function(options){return pumpify.obj(new DocVector(options),new DBEntries(options),new RecalibrateDB(options))},Indexer.deleter=function(docIds,done){const s=new Readable;docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)})},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},callback(err,Indexer)})};const getOptions=function(options,done){options=Object.assign({},{deletable:!0,batchSize:1e5,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\\n|[|' ><.,\-|]+|\\u0003/,stopwords:[],weight:0},options),options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes?done(null,options):levelup(options.indexPath||"si",{valueEncoding:"json",db:leveldown},function(err,db){options.indexes=db,done(err,options)})}},{"./lib/add.js":102,"./lib/delete.js":103,"./lib/replicate.js":104,async:4,bunyan:10,docproc:19,leveldown:58,levelup:71,pumpify:88,stream:122}],102:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),emitIndexKeys=function(s){for(var key in s.deltaIndex)s.push({key:key,value:s.deltaIndex[key]});s.deltaIndex={}},IndexBatch=function(indexer){this.indexer=indexer,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.indexer.options.keySeparator;var that=this;this.indexer.deleter([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.indexer.options.log.info("processing doc "+ingestedDoc.id),that.deltaIndex["DOCUMENT"+sep+ingestedDoc.id+sep]=ingestedDoc.stored;for(var fieldName in ingestedDoc.vector){that.deltaIndex["FIELD"+sep+fieldName]=fieldName;for(var token in ingestedDoc.vector[fieldName]){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token,dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id]),that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.deltaIndex["DOCUMENT-VECTOR"+sep+ingestedDoc.id+sep+fieldName+sep]=ingestedDoc.vector[fieldName]}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.indexer.options.batchSize&&(that.push({totalKeys:totalKeys}),that.indexer.options.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:122,util:131}],103:[function(require,module,exports){const util=require("util"),Transform=require("stream").Transform;exports.flush=function(options,callback){const sep=options.keySeparator;var deleteOps=[];options.indexes.createKeyStream({gte:"0",lte:sep}).on("data",function(data){deleteOps.push({type:"del",key:data})}).on("error",function(err){return options.log.error(err," failed to empty index"),callback(err)}).on("end",function(){options.indexes.batch(deleteOps,callback)})};const DocVector=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DocVector=DocVector,util.inherits(DocVector,Transform),DocVector.prototype._transform=function(docId,encoding,end){docId=JSON.parse(docId);const sep=this.options.keySeparator;var that=this;this.options.indexes.createReadStream({gte:"DOCUMENT-VECTOR"+sep+docId+sep,lte:"DOCUMENT-VECTOR"+sep+docId+sep+sep}).on("data",function(data){that.push(data)}).on("close",function(){return end()})};const DBEntries=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBEntries=DBEntries,util.inherits(DBEntries,Transform),DBEntries.prototype._transform=function(vector,encoding,end){const sep=this.options.keySeparator;var docId;for(var k in vector.value){docId=vector.key.split(sep)[1];var field=vector.key.split(sep)[2];this.push({key:"TF"+sep+field+sep+k,value:docId}),this.push({key:"DF"+sep+field+sep+k,value:docId})}return this.push({key:vector.key}),this.push({key:"DOCUMENT"+sep+docId+sep}),end()};const RecalibrateDB=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.RecalibrateDB=RecalibrateDB,util.inherits(RecalibrateDB,Transform),RecalibrateDB.prototype._transform=function(dbEntry,encoding,end){const sep=this.options.keySeparator;var that=this;this.options.indexes.get(dbEntry.key,function(err,value){err&&that.options.log.info(err),value||(value=[]);var docId=dbEntry.value,dbInstruction={};dbInstruction.key=dbEntry.key,dbEntry.key.substring(0,3)==="TF"+sep?(dbInstruction.value=value.filter(function(item){return item[1]!==docId}),dbInstruction.type=0===dbInstruction.value.length?"del":"put"):dbEntry.key.substring(0,3)==="DF"+sep?(value.splice(value.indexOf(docId),1),dbInstruction.value=value,dbInstruction.type=0===dbInstruction.value.length?"del":"put"):dbEntry.key.substring(0,9)==="DOCUMENT"+sep?dbInstruction.type="del":dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep&&(dbInstruction.type="del"),that.options.indexes.batch([dbInstruction],function(err){return end()})})}},{stream:122,util:131}],104:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),DBWriteMergeStream=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBWriteMergeStream=DBWriteMergeStream,util.inherits(DBWriteMergeStream,Transform),DBWriteMergeStream.prototype._transform=function(data,encoding,end){if(data.totalKeys)return this.push(data),end();const sep=this.options.keySeparator;var that=this;this.options.indexes.get(data.key,function(err,val){var newVal;newVal=data.key.substring(0,3)==="TF"+sep?data.value.concat(val||[]).sort(function(a,b){return a[0]===b[0]?b[1]-a[1]:b[0]-a[0]}):data.key.substring(0,3)==="DF"+sep?data.value.concat(val||[]).sort():"DOCUMENT-COUNT"===data.key?+val+(+data.value||0):data.value,that.options.indexes.put(data.key,newVal,function(err){that.push(data),end()})})};const DBWriteCleanStream=function(options){this.currentBatch=[],this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(DBWriteCleanStream,Transform),DBWriteCleanStream.prototype._transform=function(data,encoding,end){var that=this;this.currentBatch.push(data),this.currentBatch.length%this.options.batchSize===0?this.options.indexes.batch(this.currentBatch,function(err){that.push("indexing batch"),that.currentBatch=[],end()}):end()},DBWriteCleanStream.prototype._flush=function(end){var that=this;this.options.indexes.batch(this.currentBatch,function(err){that.push("remaining data indexed"),end()})},exports.DBWriteCleanStream=DBWriteCleanStream},{stream:122,util:131}],105:[function(require,module){const AvailableFields=require("./lib/AvailableFields.js").AvailableFields,CalculateBuckets=require("./lib/CalculateBuckets.js").CalculateBuckets,CalculateCategories=require("./lib/CalculateCategories.js").CalculateCategories,CalculateEntireResultSet=require("./lib/CalculateEntireResultSet.js").CalculateEntireResultSet,CalculateResultSetPerClause=require("./lib/CalculateResultSetPerClause.js").CalculateResultSetPerClause,CalculateTopScoringDocs=require("./lib/CalculateTopScoringDocs.js").CalculateTopScoringDocs,CalculateTotalHits=require("./lib/CalculateTotalHits.js").CalculateTotalHits,FetchDocsFromDB=require("./lib/FetchDocsFromDB.js").FetchDocsFromDB,FetchStoredDoc=require("./lib/FetchStoredDoc.js").FetchStoredDoc,GetIntersectionStream=require("./lib/GetIntersectionStream.js").GetIntersectionStream,MergeOrConditions=require("./lib/MergeOrConditions.js").MergeOrConditions,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,SortTopScoringDocs=require("./lib/SortTopScoringDocs.js").SortTopScoringDocs,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),initModule=function(err,Searcher,moduleReady){return Searcher.bucketStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateBuckets(Searcher.options,q.filter||{},q.buckets))},Searcher.categoryStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateCategories(Searcher.options,q))},Searcher.close=function(callback){Searcher.options.indexes.close(function(err){for(;!Searcher.options.indexes.isClosed();)Searcher.options.log.debug("closing...");Searcher.options.indexes.isClosed()&&(Searcher.options.log.debug("closed..."),callback(err))})},Searcher.availableFields=function(){const sep=Searcher.options.keySeparator;return Searcher.options.indexes.createReadStream({gte:"FIELD"+sep,lte:"FIELD"+sep+sep}).pipe(new AvailableFields(Searcher.options))},Searcher.get=function(docIDs){var s=new Readable({objectMode:!0});return docIDs.forEach(function(id){s.push(id)}),s.push(null),s.pipe(new FetchDocsFromDB(Searcher.options))},Searcher.fieldNames=function(){return Searcher.options.indexes.createReadStream({gte:"FIELD",lte:"FIELD"})},Searcher.match=function(q){return matcher.match(q,Searcher.options)},Searcher.dbReadStream=function(){return Searcher.options.indexes.createReadStream()},Searcher.search=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),q.sort?s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options)):s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreTopScoringDocsTFIDF(Searcher.options)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options))},Searcher.scan=function(q){q=siUtil.getQueryDefaults(q);var s=new Readable({objectMode:!0});return s.push("init"),s.push(null),s.pipe(new GetIntersectionStream(Searcher.options,siUtil.getKeySet(q.query[0].AND,Searcher.options.keySeparator))).pipe(new FetchDocsFromDB(Searcher.options))},Searcher.totalHits=function(q,callback){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateTotalHits(Searcher.options)).on("data",function(totalHits){return callback(null,totalHits)})},moduleReady(err,Searcher)},getOptions=function(options,done){var Searcher={};return Searcher.options=Object.assign({},{deletable:!0,fieldedSearch:!0,store:!0,indexPath:"si",keySeparator:"○",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:[]},options),Searcher.options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes?done(null,Searcher):void levelup(Searcher.options.indexPath||"si",{valueEncoding:"json"},function(err,db){return Searcher.options.indexes=db,done(err,Searcher)})};module.exports=function(givenOptions,moduleReady){getOptions(givenOptions,function(err,Searcher){initModule(err,Searcher,moduleReady)})}},{"./lib/AvailableFields.js":106,"./lib/CalculateBuckets.js":107,"./lib/CalculateCategories.js":108,"./lib/CalculateEntireResultSet.js":109,"./lib/CalculateResultSetPerClause.js":110,"./lib/CalculateTopScoringDocs.js":111,"./lib/CalculateTotalHits.js":112,"./lib/FetchDocsFromDB.js":113,"./lib/FetchStoredDoc.js":114,"./lib/GetIntersectionStream.js":115,"./lib/MergeOrConditions.js":116,"./lib/ScoreDocsOnField.js":117,"./lib/ScoreTopScoringDocsTFIDF.js":118,"./lib/SortTopScoringDocs.js":119,"./lib/matcher.js":120,"./lib/siUtil.js":121,bunyan:10,levelup:71,stream:122}],106:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),AvailableFields=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.AvailableFields=AvailableFields,util.inherits(AvailableFields,Transform),AvailableFields.prototype._transform=function(field,encoding,end){return this.push(field.key.split(this.options.keySeparator)[1]),end()}},{stream:122,util:131}],107:[function(require,module,exports){const _intersection=require("lodash.intersection"),_uniq=require("lodash.uniq"),Transform=require("stream").Transform,util=require("util"),CalculateBuckets=function(options,filter,requestedBuckets){this.buckets=requestedBuckets||[],this.filter=filter,this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateBuckets=CalculateBuckets,util.inherits(CalculateBuckets,Transform),CalculateBuckets.prototype._transform=function(mergedQueryClauses,encoding,end){const that=this,sep=this.options.keySeparator;var bucketsProcessed=0;that.buckets.forEach(function(bucket){const gte="DF"+sep+bucket.field+sep+bucket.gte,lte="DF"+sep+bucket.field+sep+bucket.lte+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){var IDSet=_intersection(data.value,mergedQueryClauses.set);IDSet.length>0&&(bucket.value=bucket.value||[],bucket.value=_uniq(bucket.value.concat(IDSet).sort()))}).on("close",function(){return bucket.set||(bucket.value=bucket.value.length),that.push(bucket),++bucketsProcessed===that.buckets.length?end():void 0})})}},{"lodash.intersection":75,"lodash.uniq":80,stream:122,util:131}],108:[function(require,module,exports){const _intersection=require("lodash.intersection"),Transform=require("stream").Transform,util=require("util"),CalculateCategories=function(options,q){var category=q.category||[];category.values=[],this.offset=+q.offset,this.pageSize=+q.pageSize,this.category=category,this.options=options,this.query=q.query,Transform.call(this,{objectMode:!0})};exports.CalculateCategories=CalculateCategories,util.inherits(CalculateCategories,Transform),CalculateCategories.prototype._transform=function(mergedQueryClauses,encoding,end){if(!this.category.field)return end(new Error("you need to specify a category"));const sep=this.options.keySeparator,that=this,gte="DF"+sep+this.category.field+sep,lte="DF"+sep+this.category.field+sep+sep;this.category.values=this.category.values||[];var i=this.offset+this.pageSize,j=0;const rs=that.options.indexes.createReadStream({gte:gte,lte:lte});rs.on("data",function(data){if(!(that.offset>j++)){var IDSet=_intersection(data.value,mergedQueryClauses.set);if(IDSet.length>0){var key=data.key.split(sep)[2],value=IDSet.length;that.category.set&&(value=IDSet);var result={key:key,value:value};if(1===that.query.length)try{that.query[0].AND[that.category.field].indexOf(key)>-1&&(result.filter=!0)}catch(e){}i-->that.offset?that.push(result):rs.destroy()}}}).on("close",function(){return end()})}},{"lodash.intersection":75,stream:122,util:131}],109:[function(require,module,exports){const Transform=require("stream").Transform,_union=require("lodash.union"),util=require("util"),CalculateEntireResultSet=function(options){this.options=options,this.setSoFar=[],Transform.call(this,{objectMode:!0})};exports.CalculateEntireResultSet=CalculateEntireResultSet,util.inherits(CalculateEntireResultSet,Transform),CalculateEntireResultSet.prototype._transform=function(queryClause,encoding,end){return this.setSoFar=_union(queryClause.set,this.setSoFar),end()},CalculateEntireResultSet.prototype._flush=function(end){return this.push({set:this.setSoFar}),end()}},{"lodash.union":79,stream:122,util:131}],110:[function(require,module,exports){const Transform=require("stream").Transform,_difference=require("lodash.difference"),_intersection=require("lodash.intersection"),_spread=require("lodash.spread"),siUtil=require("./siUtil.js"),util=require("util"),CalculateResultSetPerClause=function(options){ -this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateResultSetPerClause=CalculateResultSetPerClause,util.inherits(CalculateResultSetPerClause,Transform),CalculateResultSetPerClause.prototype._transform=function(queryClause,encoding,end){const sep=this.options.keySeparator,that=this,frequencies=[];var NOT=function(includeResults){const bigIntersect=_spread(_intersection);var include=bigIntersect(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,termFrequencies:frequencies,BOOST:queryClause.BOOST||0}),end();var i=0,excludeResults=[];siUtil.getKeySet(queryClause.NOT,sep).forEach(function(item){var excludeSet={};that.options.indexes.createReadStream({gte:item[0],lte:item[1]+sep}).on("data",function(data){for(var i=0;ib.id?-1:0}).reduce(function(merged,cur){var lastDoc=merged[merged.length-1];return 0===merged.length||cur.id!==lastDoc.id?merged.push(cur):cur.id===lastDoc.id&&(lastDoc.scoringCriteria=lastDoc.scoringCriteria.concat(cur.scoringCriteria)),merged},[]);return mergedResultSet.map(function(item){return item.scoringCriteria&&(item.score=item.scoringCriteria.reduce(function(acc,val){return{score:+acc.score+ +val.score}},{score:0}).score,item.score=item.score/item.scoringCriteria.length),item}),mergedResultSet.forEach(function(item){that.push(item)}),end()}},{stream:122,util:131}],117:[function(require,module,exports){const Transform=require("stream").Transform,_sortedIndexOf=require("lodash.sortedindexof"),util=require("util"),ScoreDocsOnField=function(options,seekLimit,sort){this.options=options,this.seekLimit=seekLimit,this.sort=sort,Transform.call(this,{objectMode:!0})};exports.ScoreDocsOnField=ScoreDocsOnField,util.inherits(ScoreDocsOnField,Transform),ScoreDocsOnField.prototype._transform=function(clauseSet,encoding,end){const sep=this.options.keySeparator,that=this,gte="TF"+sep+this.sort.field+sep,lte="TF"+sep+this.sort.field+sep+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){for(var i=0;ib.score?-2:a.idb.id?-1:0}:function(a,b){return a.score>b.score?2:a.scoreb.id?-1:0}),this.resultSet=this.resultSet.slice(this.q.offset,this.q.offset+this.q.pageSize),this.resultSet.forEach(function(hit){that.push(hit)}),end()}},{stream:122,util:131}],120:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatcherStream=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatcherStream,Transform),MatcherStream.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var results=[];const formatMatches=function(item){that.push("ID"===q.type?[item.key.split(sep)[2],item.value]:"count"===q.type?[item.key.split(sep)[2],item.value.length]:item.key.split(sep)[2])},sortResults=function(err){err&&console.log(err),results.sort(function(a,b){return b.value.length-a.value.length}).slice(0,q.limit).forEach(formatMatches),end()};this.options.indexes.createReadStream({start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep}).on("data",function(data){results.push(data)}).on("error",function(err){that.options.log.error("Oh my!",err)}).on("end",sortResults)},exports.match=function(q,options){var s=new Readable({objectMode:!0});return q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple"},q),q.beginsWith.length=byte?0:byte>>5===6?2:byte>>4===14?3:byte>>3===30?4:-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(i>j)return 0;var nb=utf8CheckByte(buf[j]);return nb>=0?(nb>0&&(self.lastNeed=nb-1),nb):--j=0?(nb>0&&(self.lastNeed=nb-2),nb):--j=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0))}function utf8CheckExtraBytes(self,buf,p){if(128!==(192&buf[0]))return self.lastNeed=0,"�".repeat(p);if(self.lastNeed>1&&buf.length>1){if(128!==(192&buf[1]))return self.lastNeed=1,"�".repeat(p+1);if(self.lastNeed>2&&buf.length>2&&128!==(192&buf[2]))return self.lastNeed=2,"�".repeat(p+2)}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�".repeat(this.lastTotal-this.lastNeed):r}function utf16Text(buf,i){if((buf.length-i)%2===0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&56319>=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("buffer").Buffer,bufferShim=require("buffer-shims"),isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return itokens.length)return[];for(var ngrams=[],i=0;i<=tokens.length-nGramLength;i++)ngrams.push(tokens.slice(i,i+nGramLength));if(ngrams=ngrams.sort(),1===ngrams.length)return[[ngrams[0],1]];for(var counter=1,lastToken=ngrams[0],vector=[],j=1;j=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){return str}function arrayToHash(array){var hash={};return array.forEach(function(val){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)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}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(0>recurseTimes)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;l>i;++i)output.push(hasOwnProperty(value,String(i))?formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),!0):"");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if(desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]},desc.get?str=desc.set?ctx.stylize("[Getter/Setter]","special"):ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(ctx.seen.indexOf(desc.value)<0?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1),str.indexOf("\n")>-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,length=output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return length>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||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return 10>n?"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];len>i;x=args[++i])str+=isNull(x)||!isObject(x)?" "+x:" "+inspect(x);return str},exports.deprecate=function(fn,msg){function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);process.traceDeprecation?console.trace(msg):console.error(msg),warned=!0}return fn.apply(this,arguments)}if(isUndefined(global.process))return function(){return exports.deprecate(fn,msg).apply(this,arguments)};if(process.noDeprecation===!0)return fn;var warned=!1;return deprecated};var debugEnviron,debugs={};exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!debugs[set])if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":130,_process:85,inherits:129}],132:[function(require,module){function wrappy(fn,cb){function wrapper(){for(var args=new Array(arguments.length),i=0;i=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":134}],4:[function(require,module,exports){(function(process,global){!function(global,factory){"object"==typeof exports&&void 0!==module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory(global.async=global.async||{})}(this,function(exports){"use strict";function slice(arrayLike,start){start|=0;for(var newLen=Math.max(arrayLike.length-start,0),newArr=Array(newLen),idx=0;idx-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function noop(){}function once(fn){return function(){if(null!==fn){var callFn=fn;fn=null,callFn.apply(this,arguments)}}}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index-1&&value%1==0&&valuelength?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=length?array:baseSlice(array,start,end)}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function charsStartIndex(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index-1;);return index}function asciiToArray(string){return string.split("")}function hasUnicode(string){return reHasUnicode.test(string)}function unicodeToArray(string){return string.match(reUnicode)||[]}function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string)}function toString(value){return null==value?"":baseToString(value)}function trim(string,chars,guard){if((string=toString(string))&&(guard||void 0===chars))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars);return castSlice(strSymbols,charsStartIndex(strSymbols,chrSymbols),charsEndIndex(strSymbols,chrSymbols)+1).join("")}function parseParams(func){return func=func.toString().replace(STRIP_COMMENTS,""),func=func.match(FN_ARGS)[2].replace(" ",""),func=func?func.split(FN_ARG_SPLIT):[],func=func.map(function(arg){return trim(arg.replace(FN_ARG,""))})}function autoInject(tasks,callback){var newTasks={};baseForOwn(tasks,function(taskFn,key){function newTask(results,taskCb){var newArgs=arrayMap(params,function(name){return results[name]});newArgs.push(taskCb),wrapAsync(taskFn).apply(null,newArgs)}var params,fnIsAsync=isAsync(taskFn),hasNoDeps=!fnIsAsync&&1===taskFn.length||fnIsAsync&&0===taskFn.length;if(isArray(taskFn))params=taskFn.slice(0,-1),taskFn=taskFn[taskFn.length-1],newTasks[key]=params.concat(params.length>0?newTask:taskFn);else if(hasNoDeps)newTasks[key]=taskFn;else{if(params=parseParams(taskFn),0===taskFn.length&&!fnIsAsync&&0===params.length)throw new Error("autoInject task functions require explicit parameters.");fnIsAsync||params.pop(),newTasks[key]=params.concat(newTask)}}),auto(newTasks,callback)}function DLL(){this.head=this.tail=null,this.length=0}function setInitial(dll,node){dll.length=1,dll.head=dll.tail=node}function queue(worker,concurrency,payload){function _insert(data,insertAtFront,callback){if(null!=callback&&"function"!=typeof callback)throw new Error("task callback must be a function");if(q.started=!0,isArray(data)||(data=[data]),0===data.length&&q.idle())return setImmediate$1(function(){q.drain()});for(var i=0,l=data.length;i=0&&workersList.splice(index),task.callback.apply(task,arguments),null!=err&&q.error(err,task.data)}numRunning<=q.concurrency-q.buffer&&q.unsaturated(),q.idle()&&q.drain(),q.process()}}if(null==concurrency)concurrency=1;else if(0===concurrency)throw new Error("Concurrency must not be zero");var _worker=wrapAsync(worker),numRunning=0,workersList=[],isProcessing=!1,q={_tasks:new DLL,concurrency:concurrency,payload:payload,saturated:noop,unsaturated:noop,buffer:concurrency/4,empty:noop,drain:noop,error:noop,started:!1,paused:!1,push:function(data,callback){_insert(data,!1,callback)},kill:function(){q.drain=noop,q._tasks.empty()},unshift:function(data,callback){_insert(data,!0,callback)},remove:function(testFn){q._tasks.remove(testFn)},process:function(){if(!isProcessing){for(isProcessing=!0;!q.paused&&numRunning2&&(result=slice(arguments,1)),results[key]=result,callback(err)})},function(err){callback(err,results)})}function parallelLimit(tasks,callback){_parallel(eachOf,tasks,callback)}function parallelLimit$1(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)}function race(tasks,callback){if(callback=once(callback||noop),!isArray(tasks))return callback(new TypeError("First argument to race must be an array of functions"));if(!tasks.length)return callback();for(var i=0,l=tasks.length;ib?1:0}var _iteratee=wrapAsync(iteratee);map(coll,function(x,callback){_iteratee(x,function(err,criteria){ +if(err)return callback(err);callback(null,{value:x,criteria:criteria})})},function(err,results){if(err)return callback(err);callback(null,arrayMap(results.sort(comparator),baseProperty("value")))})}function timeout(asyncFn,milliseconds,info){var fn=wrapAsync(asyncFn);return initialParams(function(args,callback){function timeoutCallback(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)}var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(timeoutCallback,milliseconds),fn.apply(null,args)})}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function timeLimit(count,limit,iteratee,callback){var _iteratee=wrapAsync(iteratee);mapLimit(baseRange(0,count,1),limit,_iteratee,callback)}function transform(coll,accumulator,iteratee,callback){arguments.length<=3&&(callback=iteratee,iteratee=accumulator,accumulator=isArray(coll)?[]:{}),callback=once(callback||noop);var _iteratee=wrapAsync(iteratee);eachOf(coll,function(v,k,cb){_iteratee(accumulator,v,k,cb)},function(err){callback(err,accumulator)})}function tryEach(tasks,callback){var result,error=null;callback=callback||noop,eachSeries(tasks,function(task,callback){wrapAsync(task)(function(err,res){result=arguments.length>2?slice(arguments,1):res,error=err,callback(!err)})},function(){callback(error,result)})}function unmemoize(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}}function whilst(test,iteratee,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync(iteratee);if(!test())return callback(null);var next=function(err){if(err)return callback(err);if(test())return _iteratee(next);var args=slice(arguments,1);callback.apply(null,[null].concat(args))};_iteratee(next)}function until(test,iteratee,callback){whilst(function(){return!test.apply(this,arguments)},iteratee,callback)}var _defer,initialParams=function(fn){return function(){var args=slice(arguments),callback=args.pop();fn.call(this,args,callback)}},hasSetImmediate="function"==typeof setImmediate&&setImmediate,hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback;var setImmediate$1=wrap(_defer),supportsSymbol="function"==typeof Symbol,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol$1=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag$1=Symbol$1?Symbol$1.toStringTag:void 0,objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString,nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$1?Symbol$1.toStringTag:void 0,asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]",MAX_SAFE_INTEGER=9007199254740991,breakLoop={},iteratorSymbol="function"==typeof Symbol&&Symbol.iterator,getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()},argsTag="[object Arguments]",objectProto$3=Object.prototype,hasOwnProperty$2=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$2.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,MAX_SAFE_INTEGER$1=9007199254740991,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["[object Arguments]"]=typedArrayTags["[object Array]"]=typedArrayTags["[object ArrayBuffer]"]=typedArrayTags["[object Boolean]"]=typedArrayTags["[object DataView]"]=typedArrayTags["[object Date]"]=typedArrayTags["[object Error]"]=typedArrayTags["[object Function]"]=typedArrayTags["[object Map]"]=typedArrayTags["[object Number]"]=typedArrayTags["[object Object]"]=typedArrayTags["[object RegExp]"]=typedArrayTags["[object Set]"]=typedArrayTags["[object String]"]=typedArrayTags["[object WeakMap]"]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray,objectProto$2=Object.prototype,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty,eachOfGeneric=doLimit(eachOfLimit,1/0),eachOf=function(coll,iteratee,callback){(isArrayLike(coll)?eachOfArrayLike:eachOfGeneric)(coll,wrapAsync(iteratee),callback)},map=doParallel(_asyncMap),applyEach=applyEach$1(map),mapLimit=doParallelLimit(_asyncMap),mapSeries=doLimit(mapLimit,1),applyEachSeries=applyEach$1(mapSeries),apply=function(fn){var args=slice(arguments,1);return function(){var callArgs=slice(arguments);return fn.apply(null,args.concat(callArgs))}},baseFor=function(fromRight){return function(object,iteratee,keysFunc){for(var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;length--;){var key=props[fromRight?length:++index];if(!1===iteratee(iterable[key],key,iterable))break}return object}}(),auto=function(tasks,concurrency,callback){function enqueueTask(key,task){readyTasks.push(function(){runTask(key,task)})}function processQueue(){if(0===readyTasks.length&&0===runningTasks)return callback(null,results);for(;readyTasks.length&&runningTasks2&&(result=slice(arguments,1)),err){var safeResults={};baseForOwn(results,function(val,rkey){safeResults[rkey]=val}),safeResults[key]=result,hasError=!0,listeners=Object.create(null),callback(err,safeResults)}else results[key]=result,taskComplete(key)});runningTasks++;var taskFn=wrapAsync(task[task.length-1]);task.length>1?taskFn(results,taskCallback):taskFn(taskCallback)}}function getDependents(taskName){var result=[];return baseForOwn(tasks,function(task,key){isArray(task)&&baseIndexOf(task,taskName,0)>=0&&result.push(key)}),result}"function"==typeof concurrency&&(callback=concurrency,concurrency=null),callback=once(callback||noop);var keys$$1=keys(tasks),numTasks=keys$$1.length;if(!numTasks)return callback(null);concurrency||(concurrency=numTasks);var results={},runningTasks=0,hasError=!1,listeners=Object.create(null),readyTasks=[],readyToCheck=[],uncheckedDependencies={};baseForOwn(tasks,function(task,key){if(!isArray(task))return enqueueTask(key,[task]),void readyToCheck.push(key);var dependencies=task.slice(0,task.length-1),remainingDependencies=dependencies.length;if(0===remainingDependencies)return enqueueTask(key,task),void readyToCheck.push(key);uncheckedDependencies[key]=remainingDependencies,arrayEach(dependencies,function(dependencyName){if(!tasks[dependencyName])throw new Error("async.auto task `"+key+"` has a non-existent dependency `"+dependencyName+"` in "+dependencies.join(", "));addListener(dependencyName,function(){0===--remainingDependencies&&enqueueTask(key,task)})})}),function(){for(var currentTask,counter=0;readyToCheck.length;)currentTask=readyToCheck.pop(),counter++,arrayEach(getDependents(currentTask),function(dependent){0==--uncheckedDependencies[dependent]&&readyToCheck.push(dependent)});if(counter!==numTasks)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),processQueue()},symbolTag="[object Symbol]",INFINITY=1/0,symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0,reHasUnicode=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),rsCombo="[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",reOptMod="(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?",rsOptJoin="(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+rsOptJoin,rsSymbol="(?:"+["[^\\ud800-\\udfff]"+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,"[\\ud800-\\udfff]"].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reTrim=/^\s+|\s+$/g,FN_ARGS=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,FN_ARG_SPLIT=/,/,FN_ARG=/(=.+)?(\s*)$/,STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;DLL.prototype.removeLink=function(node){return node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev,node.prev=node.next=null,this.length-=1,node},DLL.prototype.empty=function(){for(;this.head;)this.shift();return this},DLL.prototype.insertAfter=function(node,newNode){newNode.prev=node,newNode.next=node.next,node.next?node.next.prev=newNode:this.tail=newNode,node.next=newNode,this.length+=1},DLL.prototype.insertBefore=function(node,newNode){newNode.prev=node.prev,newNode.next=node,node.prev?node.prev.next=newNode:this.head=newNode,node.prev=newNode,this.length+=1},DLL.prototype.unshift=function(node){this.head?this.insertBefore(this.head,node):setInitial(this,node)},DLL.prototype.push=function(node){this.tail?this.insertAfter(this.tail,node):setInitial(this,node)},DLL.prototype.shift=function(){return this.head&&this.removeLink(this.head)},DLL.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},DLL.prototype.toArray=function(){for(var arr=Array(this.length),curr=this.head,idx=0;idx=nextNode.priority;)nextNode=nextNode.next;for(var i=0,l=data.length;i0)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,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;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+16383));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;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&&("ucs2"===(encoding=String(encoding).toLowerCase())||"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)>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)>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)>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=65536+(leadSurrogate-55296<<10|codePoint-56320)}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 base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");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:function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}(),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)<0&&(start=0):start>len&&(start=len),end<0?(end+=len)<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]?-1*(255-this[offset]+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;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":return fastAndSafeJsonStringify(args[i++]);case"%%":return"%";default:return x}}),x=args[i];i=0,format('rotating-file stream "count" is not >= 0: %j in %j',this.count,this)),options.period){var period={hourly:"1h",daily:"1d",weekly:"1w",monthly:"1m",yearly:"1y"}[options.period]||options.period,m=/^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);if(!m)throw new Error(format('invalid period: "%s"',options.period));this.periodNum=Number(m[1]),this.periodScope=m[2]}else this.periodNum=1,this.periodScope="d";var lastModified=null;try{lastModified=fs.statSync(this.path).mtime.getTime()}catch(err){}var rotateAfterOpen=!1;if(lastModified){lastModified call rotate()"),this.rotate()):this._setupNextRot()},util.inherits(RotatingFileStream,EventEmitter),RotatingFileStream.prototype._debug=function(){return!1},RotatingFileStream.prototype._setupNextRot=function(){this.rotAt=this._calcRotTime(1),this._setRotationTimer()},RotatingFileStream.prototype._setRotationTimer=function(){var self=this,delay=this.rotAt-Date.now();delay>2147483647&&(delay=2147483647),this.timeout=setTimeout(function(){self._debug("_setRotationTimer timeout -> call rotate()"),self.rotate()},delay),"function"==typeof this.timeout.unref&&this.timeout.unref()},RotatingFileStream.prototype._calcRotTime=function(periodOffset){this._debug("_calcRotTime: %s%s",this.periodNum,this.periodScope);var d=new Date;this._debug(" now local: %s",d),this._debug(" now utc: %s",d.toISOString());var rotAt;switch(this.periodScope){case"ms":rotAt=this.rotAt?this.rotAt+this.periodNum*periodOffset:Date.now()+this.periodNum*periodOffset;break;case"h":rotAt=this.rotAt?this.rotAt+60*this.periodNum*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours()+periodOffset);break;case"d":rotAt=this.rotAt?this.rotAt+24*this.periodNum*60*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+periodOffset);break;case"w":if(this.rotAt)rotAt=this.rotAt+7*this.periodNum*24*60*60*1e3*periodOffset;else{var dayOffset=7-d.getUTCDay();periodOffset<1&&(dayOffset=-d.getUTCDay()),(periodOffset>1||periodOffset<-1)&&(dayOffset+=7*periodOffset),rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+dayOffset)}break;case"m":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+this.periodNum*periodOffset,1):Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+periodOffset,1);break;case"y":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear()+this.periodNum*periodOffset,0,1):Date.UTC(d.getUTCFullYear()+periodOffset,0,1);break;default:assert.fail(format('invalid period scope: "%s"',this.periodScope))}if(this._debug()){this._debug(" **rotAt**: %s (utc: %s)",rotAt,new Date(rotAt).toUTCString());var now=Date.now();this._debug(" now: %s (%sms == %smin == %sh to go)",now,rotAt-now,(rotAt-now)/1e3/60,(rotAt-now)/1e3/60/60)}return rotAt},RotatingFileStream.prototype.rotate=function(){function moves(){if(0===self.count||n<0)return finish();var before=self.path,after=self.path+"."+String(n);n>0&&(before+="."+String(n-1)),n-=1,fs.exists(before,function(exists){exists?(self._debug(" mv %s %s",before,after),mv(before,after,function(mvErr){mvErr?(self.emit("error",mvErr),finish()):moves()})):moves()})}function finish(){self._debug(" open %s",self.path),self.stream=fs.createWriteStream(self.path,{flags:"a",encoding:"utf8"});for(var q=self.rotQueue,len=q.length,i=0;iDate.now())return self._setRotationTimer();if(this._debug("rotate"),self.rotating)throw new TypeError("cannot start a rotation when already rotating");self.rotating=!0,self.stream.end();var n=this.count;!function(){var toDel=self.path+"."+String(n-1);0===n&&(toDel=self.path),n-=1,self._debug(" rm %s",toDel),fs.unlink(toDel,function(delErr){moves()})}()},RotatingFileStream.prototype.write=function(s){return this.rotating?(this.rotQueue.push(s),!1):this.stream.write(s)},RotatingFileStream.prototype.end=function(s){this.stream.end()},RotatingFileStream.prototype.destroy=function(s){this.stream.destroy()},RotatingFileStream.prototype.destroySoon=function(s){this.stream.destroySoon()}),util.inherits(RingBuffer,EventEmitter),RingBuffer.prototype.write=function(record){if(!this.writable)throw new Error("RingBuffer has been ended already");return this.records.push(record),this.records.length>this.limit&&this.records.shift(),!0},RingBuffer.prototype.end=function(){arguments.length>0&&this.write.apply(this,Array.prototype.slice.call(arguments)),this.writable=!1},RingBuffer.prototype.destroy=function(){this.writable=!1,this.emit("close")},RingBuffer.prototype.destroySoon=function(){this.destroy()},module.exports=Logger,module.exports.TRACE=10,module.exports.DEBUG=20,module.exports.INFO=INFO,module.exports.WARN=WARN,module.exports.ERROR=ERROR,module.exports.FATAL=60,module.exports.resolveLevel=resolveLevel,module.exports.levelFromName=levelFromName,module.exports.nameFromLevel=nameFromLevel,module.exports.VERSION="1.8.10",module.exports.LOG_VERSION=LOG_VERSION,module.exports.createLogger=function(options){return new Logger(options)},module.exports.RingBuffer=RingBuffer,module.exports.RotatingFileStream=RotatingFileStream,module.exports.safeCycles=safeCycles}).call(this,{isBuffer:require("../../is-buffer/index.js")},require("_process"))},{"../../is-buffer/index.js":42,_process:84,assert:3,events:37,fs:7,os:82,"safe-json-stringify":102,stream:125,util:134}],10:[function(require,module,exports){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}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"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)}function isError(e){return"[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)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":42}],11:[function(require,module,exports){function DeferredIterator(options){AbstractIterator.call(this,options),this._options=options,this._iterator=null,this._operations=[]}var util=require("util"),AbstractIterator=require("abstract-leveldown").AbstractIterator;util.inherits(DeferredIterator,AbstractIterator),DeferredIterator.prototype.setDb=function(db){var it=this._iterator=db.iterator(this._options);this._operations.forEach(function(op){it[op.method].apply(it,op.args)})},DeferredIterator.prototype._operation=function(method,args){if(this._iterator)return this._iterator[method].apply(this._iterator,args);this._operations.push({method:method,args:args})},"next end".split(" ").forEach(function(m){DeferredIterator.prototype["_"+m]=function(){this._operation(m,arguments)}}),module.exports=DeferredIterator},{"abstract-leveldown":16,util:134}],12:[function(require,module,exports){(function(Buffer,process){function DeferredLevelDOWN(location){AbstractLevelDOWN.call(this,"string"==typeof location?location:""),this._db=void 0,this._operations=[],this._iterators=[]}var util=require("util"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,DeferredIterator=require("./deferred-iterator");util.inherits(DeferredLevelDOWN,AbstractLevelDOWN),DeferredLevelDOWN.prototype.setDb=function(db){this._db=db,this._operations.forEach(function(op){db[op.method].apply(db,op.args)}),this._iterators.forEach(function(it){it.setDb(db)})},DeferredLevelDOWN.prototype._open=function(options,callback){return process.nextTick(callback)},DeferredLevelDOWN.prototype._operation=function(method,args){if(this._db)return this._db[method].apply(this._db,args);this._operations.push({method:method,args:args})},"put get del batch approximateSize".split(" ").forEach(function(m){DeferredLevelDOWN.prototype["_"+m]=function(){this._operation(m,arguments)}}),DeferredLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},DeferredLevelDOWN.prototype._iterator=function(options){if(this._db)return this._db.iterator.apply(this._db,arguments);var it=new DeferredIterator(options);return this._iterators.push(it),it},module.exports=DeferredLevelDOWN,module.exports.DeferredIterator=DeferredIterator}).call(this,{isBuffer:require("../is-buffer/index.js")},require("_process"))},{"../is-buffer/index.js":42,"./deferred-iterator":11,_process:84,"abstract-leveldown":16,util:134}],13:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:84}],14:[function(require,module,exports){(function(process){function AbstractIterator(db){this.db=db,this._ended=!1,this._nexting=!1}AbstractIterator.prototype.next=function(callback){var self=this;if("function"!=typeof callback)throw new Error("next() requires a callback argument");return self._ended?callback(new Error("cannot call next() after end()")):self._nexting?callback(new Error("cannot call next() before previous next() has completed")):(self._nexting=!0,"function"==typeof self._next?self._next(function(){self._nexting=!1,callback.apply(null,arguments)}):void process.nextTick(function(){self._nexting=!1,callback()}))},AbstractIterator.prototype.end=function(callback){if("function"!=typeof callback)throw new Error("end() requires a callback argument");return this._ended?callback(new Error("end() already called on iterator")):(this._ended=!0,"function"==typeof this._end?this._end(callback):void process.nextTick(callback))},module.exports=AbstractIterator}).call(this,require("_process"))},{_process:84}],15:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location,this.status="new"}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){var self=this,oldStatus=this.status;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");"object"!=typeof options&&(options={}),options.createIfMissing=0!=options.createIfMissing,options.errorIfExists=!!options.errorIfExists,"function"==typeof this._open?(this.status="opening",this._open(options,function(err){if(err)return self.status=oldStatus,callback(err);self.status="open",callback()})):(this.status="open",process.nextTick(callback))},AbstractLevelDOWN.prototype.close=function(callback){var self=this,oldStatus=this.status;if("function"!=typeof callback)throw new Error("close() requires a callback argument");"function"==typeof this._close?(this.status="closing",this._close(function(err){if(err)return self.status=oldStatus,callback(err);self.status="closed",callback()})):(this.status="closed",process.nextTick(callback))},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),options.asBuffer=0!=options.asBuffer,"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),null==value||this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"==typeof array&&(callback=array),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));options&&"object"==typeof options||(options={});for(var e,err,i=0,l=array.length;i<.,\-|]+|\\u0003/},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{separator:options.separator},options.fieldOptions[fieldName]);"[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.tokenised[fieldName]=doc.normalised[fieldName]:doc.tokenised[fieldName]=doc.normalised[fieldName].split(fieldOptions.separator)}return this.push(doc),end()}},{stream:125,util:134}],30:[function(require,module,exports){(function(process,Buffer){var stream=require("readable-stream"),eos=require("end-of-stream"),inherits=require("inherits"),shift=require("stream-shift"),SIGNAL_FLUSH=new Buffer([0]),onuncork=function(self,fn){self._corked?self.once("uncork",fn):fn() +},destroyer=function(self,end){return function(err){err?self.destroy("premature close"===err.message?null:err):end&&!self._ended&&self.end()}},end=function(ws,fn){return ws?ws._writableState&&ws._writableState.finished?fn():ws._writableState?ws.end(fn):(ws.end(),void fn()):fn()},toStreams2=function(rs){return new stream.Readable({objectMode:!0,highWaterMark:16}).wrap(rs)},Duplexify=function(writable,readable,opts){if(!(this instanceof Duplexify))return new Duplexify(writable,readable,opts);stream.Duplex.call(this,opts),this._writable=null,this._readable=null,this._readable2=null,this._forwardDestroy=!opts||!1!==opts.destroy,this._forwardEnd=!opts||!1!==opts.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,writable&&this.setWritable(writable),readable&&this.setReadable(readable)};inherits(Duplexify,stream.Duplex),Duplexify.obj=function(writable,readable,opts){return opts||(opts={}),opts.objectMode=!0,opts.highWaterMark=16,new Duplexify(writable,readable,opts)},Duplexify.prototype.cork=function(){1==++this._corked&&this.emit("cork")},Duplexify.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},Duplexify.prototype.setWritable=function(writable){if(this._unwrite&&this._unwrite(),this.destroyed)return void(writable&&writable.destroy&&writable.destroy());if(null===writable||!1===writable)return void this.end();var self=this,unend=eos(writable,{writable:!0,readable:!1},destroyer(this,this._forwardEnd)),ondrain=function(){var ondrain=self._ondrain;self._ondrain=null,ondrain&&ondrain()},clear=function(){self._writable.removeListener("drain",ondrain),unend()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=clear,this.uncork()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)return void(readable&&readable.destroy&&readable.destroy());if(null===readable||!1===readable)return this.push(null),void this.resume();var self=this,unend=eos(readable,{writable:!1,readable:!0},destroyer(this)),onreadable=function(){self._forward()},onend=function(){self.push(null)},clear=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()};this._drained=!0,this._readable=readable,this._readable2=readable._readableState?readable:toStreams2(readable),this._readable2.on("readable",onreadable),this._readable2.on("end",onend),this._unread=clear,this._forward()},Duplexify.prototype._read=function(){this._drained=!0,this._forward()},Duplexify.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){this._forwarding=!0;for(var data;this._drained&&null!==(data=shift(this._readable2));)this.destroyed||(this._drained=this.push(data));this._forwarding=!1}},Duplexify.prototype.destroy=function(err){if(!this.destroyed){this.destroyed=!0;var self=this;process.nextTick(function(){self._destroy(err)})}},Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null,ondrain?ondrain(err):this.emit("error",err)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},Duplexify.prototype._write=function(data,enc,cb){return this.destroyed?cb():this._corked?onuncork(this,this._write.bind(this,data,enc,cb)):data===SIGNAL_FLUSH?this._finish(cb):this._writable?void(!1===this._writable.write(data)?this._ondrain=cb:cb()):cb()},Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend"),onuncork(this,function(){end(self._forwardEnd&&self._writable,function(){!1===self._writableState.prefinished&&(self._writableState.prefinished=!0),self.emit("prefinish"),onuncork(self,cb)})})},Duplexify.prototype.end=function(data,enc,cb){return"function"==typeof data?this.end(null,null,data):"function"==typeof enc?this.end(data,null,enc):(this._ended=!0,data&&this.write(data),this._writableState.ending||this.write(SIGNAL_FLUSH),stream.Writable.prototype.end.call(this,cb))},module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:84,buffer:8,"end-of-stream":31,inherits:40,"readable-stream":98,"stream-shift":126}],31:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback()},onend=function(){readable=!1,writable||callback()},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback(new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:32}],32:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0})})},{wrappy:135}],33:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback.call(stream)},onend=function(){readable=!1,writable||callback.call(stream)},onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback.call(stream,new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:81}],34:[function(require,module,exports){function init(type,message,cause){prr(this,{type:type,name:type,cause:"string"!=typeof message?message:cause,message:message&&"string"!=typeof message?message.message:message},"ewr")}function CustomError(message,cause){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),init.call(this,"CustomError",message,cause)}function createError(errno,type,proto){var err=function(message,cause){init.call(this,type,message,cause),"FilesystemError"==type&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(errno.errno[this.cause.errno]?errno.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return err.prototype=proto?new proto:new CustomError,err}var prr=require("prr");CustomError.prototype=new Error,module.exports=function(errno){var ce=function(type,proto){return createError(errno,type,proto)};return{CustomError:CustomError,FilesystemError:ce("FilesystemError"),createError:ce}}},{prr:36}],35:[function(require,module,exports){var all=module.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];module.exports.errno={},module.exports.code={},all.forEach(function(error){module.exports.errno[error.errno]=error,module.exports.code[error.code]=error}),module.exports.custom=require("./custom")(module.exports),module.exports.create=module.exports.custom.createError},{"./custom":34}],36:[function(require,module,exports){!function(name,context,definition){void 0!==module&&module.exports?module.exports=definition():context.prr=definition()}(0,this,function(){var setProperty="function"==typeof Object.defineProperty?function(obj,key,options){return Object.defineProperty(obj,key,options),obj}:function(obj,key,options){return obj[key]=options.value,obj},makeOptions=function(value,options){var oo="object"==typeof options,os=!oo&&"string"==typeof options,op=function(p){return oo?!!options[p]:!!os&&options.indexOf(p[0])>-1};return{enumerable:op("enumerable"),configurable:op("configurable"),writable:op("writable"),value:value}};return function(obj,key,value,options){var k;if(options=makeOptions(value,options),"object"==typeof key){for(k in key)Object.hasOwnProperty.call(key,k)&&(options.value=key[k],setProperty(obj,k,options));return obj}return setProperty(obj,key,options)}})},{}],37:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if((er=arguments[1])instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;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)}},{}],38:[function(require,module,exports){!function(name,definition,global){"use strict";"function"==typeof define?define(definition):void 0!==module&&module.exports?module.exports=definition():global.IDBStore=definition()}(0,function(){"use strict";function mixin(target,source){var name,s;for(name in source)(s=source[name])!==empty[name]&&s!==target[name]&&(target[name]=s);return target}function hasVersionError(errorEvent){return"error"in errorEvent.target?"VersionError"==errorEvent.target.error.name:"errorCode"in errorEvent.target&&12==errorEvent.target.errorCode}var defaultErrorHandler=function(error){throw error},defaultSuccessHandler=function(){},defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:!0,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]},IDBStore=function(kwArgs,onStoreReady){void 0===onStoreReady&&"function"==typeof kwArgs&&(onStoreReady=kwArgs),"[object Object]"!=Object.prototype.toString.call(kwArgs)&&(kwArgs={});for(var key in defaults)this[key]=void 0!==kwArgs[key]?kwArgs[key]:defaults[key];this.dbName=this.storePrefix+this.storeName,this.dbVersion=parseInt(this.dbVersion,10)||1,onStoreReady&&(this.onStoreReady=onStoreReady);var env="object"==typeof window?window:self,availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0],this.idb=env[this.implementation],this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange,this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"},this.openDB()},proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion),preventSuccessCallback=!1;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent))this.onError(new Error("The version number provided is lower than the existing one."));else{var error;if(errorEvent.target.error)error=errorEvent.target.error;else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;"errorCode"in errorEvent.target&&(errorMessage+=" with error code "+errorEvent.target.errorCode),error=new Error(errorMessage)}this.onError(error)}}.bind(this),openRequest.onsuccess=function(event){if(!preventSuccessCallback){if(this.db)return void this.onStoreReady();if(this.db=event.target.result,"string"==typeof this.db.version)return void this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));if(!this.db.objectStoreNames.contains(this.storeName))return void this.onError(new Error("Object store couldn't be created."));var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName)return preventSuccessCallback=!0,void this.onError(new Error("Cannot create index: No index name given."));if(this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(preventSuccessCallback=!0,this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else preventSuccessCallback=!0,this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))},this),existingIndexes.length&&(preventSuccessCallback=!0,this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),preventSuccessCallback||this.onStoreReady()}}.bind(this),openRequest.onupgradeneeded=function(event){if(this.db=event.target.result,this.db.objectStoreNames.contains(this.storeName))this.store=event.target.transaction.objectStore(this.storeName);else{var optionalParameters={autoIncrement:this.autoIncrement};null!==this.keyPath&&(optionalParameters.keyPath=this.keyPath),this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(indexName||(preventSuccessCallback=!0,this.onError(new Error("Cannot create index: No index name given."))),this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(this.store.deleteIndex(indexName),this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})},this),existingIndexes.length&&existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess,deleteRequest.onerror=onError}else onError(new Error("Browser does not support IndexedDB deleteDatabase!"))},put:function(key,value,onSuccess,onError){null!==this.keyPath&&(onError=onSuccess,onSuccess=value,value=key),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var putRequest,hasSuccess=!1,result=null,putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);return putTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},putTransaction.onabort=onError,putTransaction.onerror=onError,null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=putTransaction.objectStore(this.storeName).put(value)):putRequest=putTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},putRequest.onerror=onError,putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getTransaction.onabort=onError,getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);return getRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getRequest.onerror=onError,getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},removeTransaction.onabort=onError,removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName).delete(key);return deleteRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},deleteRequest.onerror=onError,removeTransaction},batch:function(dataArray,onSuccess,onError){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),"[object Array]"!=Object.prototype.toString.call(dataArray))onError(new Error("dataArray argument must be of type Array."));else if(0===dataArray.length)return onSuccess(!0);var count=dataArray.length,called=!1,hasSuccess=!1,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(hasSuccess)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(){0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(operation){var type=operation.type,key=operation.key,value=operation.value,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err,type,key))};if("remove"==type){var deleteRequest=batchTransaction.objectStore(this.storeName).delete(key);deleteRequest.onsuccess=onItemSuccess,deleteRequest.onerror=onItemError}else if("put"==type){var putRequest;null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=batchTransaction.objectStore(this.storeName).put(value)):putRequest=batchTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError}},this),batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}});return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){"function"==typeof options&&(onSuccess=options,onError=onSuccess,options={}),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),options||(options={}),"[object Array]"!=Object.prototype.toString.call(dataArray)&&onError(new Error("dataArray argument must be of type Array."));var keyField=options.keyField||this.keyPath,count=dataArray.length,called=!1,hasSuccess=!1,index=0,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){hasSuccess?onSuccess(dataArray):onError(!1)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){dataArray[index++][keyField]=event.target.result,0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(record){var putRequest,key=record.key,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err))};null!==this.keyPath?(this._addIdPropertyIfNeeded(record),putRequest=batchTransaction.objectStore(this.storeName).put(record)):putRequest=batchTransaction.objectStore(this.storeName).put(record,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError},this),batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),arrayType||(arrayType="sparse"),"[object Array]"!=Object.prototype.toString.call(keyArray))onError(new Error("keyArray argument must be of type Array."));else if(0===keyArray.length)return onSuccess([]);var data=[],count=keyArray.length,called=!1,hasSuccess=!1,result=null,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){event.target.result||"dense"==arrayType?data.push(event.target.result):"sparse"==arrayType&&data.length++,0===--count&&(called=!0,hasSuccess=!0,result=data)};return keyArray.forEach(function(key){var onItemError=function(err){called=!0,result=err,onError(err),batchTransaction.abort()},getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=onItemError},this),batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY),store=getAllTransaction.objectStore(this.storeName);return store.getAll?this._getAllNative(getAllTransaction,store,onSuccess,onError):this._getAllCursor(getAllTransaction,store,onSuccess,onError),getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)}, +getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;cursor?(all.push(cursor.value),cursor.continue()):(hasSuccess=!0,result=all)},cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},clearTransaction.onabort=onError,clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();return clearRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},clearRequest.onerror=onError,clearTransaction},_addIdPropertyIfNeeded:function(dataObj){void 0===dataObj[this.keyPath]&&(dataObj[this.keyPath]=this._insertIdCount+++Date.now())},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name,indexData.unique=!!indexData.unique,indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){return["keyPath","unique","multiEntry"].every(function(key){if("multiEntry"==key&&void 0===actual[key]&&!1===expected[key])return!0;if("keyPath"==key&&"[object Array]"==Object.prototype.toString.call(expected[key])){var exp=expected.keyPath,act=actual.keyPath;if("string"==typeof act)return exp.toString()==act;if("function"!=typeof act.contains&&"function"!=typeof act.indexOf)return!1;if(act.length!==exp.length)return!1;for(var i=0,m=exp.length;i>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:1/0*(s?-1:1);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}},{}],40:[function(require,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}},{}],41:[function(require,module,exports){var Readable=require("stream").Readable;exports.getIntersectionStream=function(sortedSets){for(var s=new Readable,i=0,ii=[],k=0;ksortedSets[i+1][ii[i+1]])ii[i+1]++;else if(i+2=sortedSets[k].length&&(finished=!0);i=0}return s.push(null),s}},{stream:125}],42:[function(require,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],43:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],44:[function(require,module,exports){function isBuffer(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}var Buffer=require("buffer").Buffer;module.exports=isBuffer},{buffer:8}],45:[function(require,module,exports){function Codec(opts){this.opts=opts||{},this.encodings=encodings}var encodings=require("./lib/encodings");module.exports=Codec,Codec.prototype._encoding=function(encoding){return"string"==typeof encoding&&(encoding=encodings[encoding]),encoding||(encoding=encodings.id),encoding},Codec.prototype._keyEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&batchOpts.keyEncoding||opts&&opts.keyEncoding||this.opts.keyEncoding)},Codec.prototype._valueEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&(batchOpts.valueEncoding||batchOpts.encoding)||opts&&(opts.valueEncoding||opts.encoding)||this.opts.valueEncoding||this.opts.encoding)},Codec.prototype.encodeKey=function(key,opts,batchOpts){return this._keyEncoding(opts,batchOpts).encode(key)},Codec.prototype.encodeValue=function(value,opts,batchOpts){return this._valueEncoding(opts,batchOpts).encode(value)},Codec.prototype.decodeKey=function(key,opts){return this._keyEncoding(opts).decode(key)},Codec.prototype.decodeValue=function(value,opts){return this._valueEncoding(opts).decode(value)},Codec.prototype.encodeBatch=function(ops,opts){var self=this;return ops.map(function(_op){var op={type:_op.type,key:self.encodeKey(_op.key,opts,_op)};return self.keyAsBuffer(opts,_op)&&(op.keyEncoding="binary"),_op.prefix&&(op.prefix=_op.prefix),"value"in _op&&(op.value=self.encodeValue(_op.value,opts,_op),self.valueAsBuffer(opts,_op)&&(op.valueEncoding="binary")),op})};var ltgtKeys=["lt","gt","lte","gte","start","end"];Codec.prototype.encodeLtgt=function(ltgt){var self=this,ret={};return Object.keys(ltgt).forEach(function(key){ret[key]=ltgtKeys.indexOf(key)>-1?self.encodeKey(ltgt[key],ltgt):ltgt[key]}),ret},Codec.prototype.createStreamDecoder=function(opts){var self=this;return opts.keys&&opts.values?function(key,value){return{key:self.decodeKey(key,opts),value:self.decodeValue(value,opts)}}:opts.keys?function(key){return self.decodeKey(key,opts)}:opts.values?function(_,value){return self.decodeValue(value,opts)}:function(){}},Codec.prototype.keyAsBuffer=function(opts){return this._keyEncoding(opts).buffer},Codec.prototype.valueAsBuffer=function(opts){return this._valueEncoding(opts).buffer}},{"./lib/encodings":46}],46:[function(require,module,exports){(function(Buffer){function identity(value){return value}function isBinary(data){return void 0===data||null===data||Buffer.isBuffer(data)}exports.utf8=exports["utf-8"]={encode:function(data){return isBinary(data)?data:String(data)},decode:identity,buffer:!1,type:"utf8"},exports.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},exports.binary={encode:function(data){return isBinary(data)?data:new Buffer(data)},decode:identity,buffer:!0,type:"binary"},exports.id={encode:function(data){return data},decode:function(data){return data},buffer:!1,type:"id"},["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"].forEach(function(type){exports[type]={encode:function(data){return isBinary(data)?data:new Buffer(data,type)},decode:function(buffer){return buffer.toString(type)},buffer:!0,type:type}})}).call(this,require("buffer").Buffer)},{buffer:8}],47:[function(require,module,exports){var createError=require("errno").create,LevelUPError=createError("LevelUPError"),NotFoundError=createError("NotFoundError",LevelUPError);NotFoundError.prototype.notFound=!0,NotFoundError.prototype.status=404,module.exports={LevelUPError:LevelUPError,InitializationError:createError("InitializationError",LevelUPError),OpenError:createError("OpenError",LevelUPError),ReadError:createError("ReadError",LevelUPError),WriteError:createError("WriteError",LevelUPError),NotFoundError:NotFoundError,EncodingError:createError("EncodingError",LevelUPError)}},{errno:35}],48:[function(require,module,exports){function ReadStream(iterator,options){if(!(this instanceof ReadStream))return new ReadStream(iterator,options);Readable.call(this,extend(options,{objectMode:!0})),this._iterator=iterator,this._destroyed=!1,this._decoder=null,options&&options.decoder&&(this._decoder=options.decoder),this.on("end",this._cleanup.bind(this))}var inherits=require("inherits"),Readable=require("readable-stream").Readable,extend=require("xtend"),EncodingError=require("level-errors").EncodingError;module.exports=ReadStream,inherits(ReadStream,Readable),ReadStream.prototype._read=function(){var self=this;this._destroyed||this._iterator.next(function(err,key,value){if(!self._destroyed){if(err)return self.emit("error",err);if(void 0===key&&void 0===value)self.push(null);else{if(!self._decoder)return self.push({key:key,value:value});try{var value=self._decoder(key,value)}catch(err){return self.emit("error",new EncodingError(err)),void self.push(null)}self.push(value)}}})},ReadStream.prototype.destroy=ReadStream.prototype._cleanup=function(){var self=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(err){if(err)return self.emit("error",err);self.emit("close")}))}},{inherits:40,"level-errors":47,"readable-stream":55,xtend:136}],49:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],50:[function(require,module,exports){(function(process){function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys},util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable),function(xs,f){for(var i=0,l=xs.length;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:isNaN(n)||util.isNull(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return util.isBuffer(chunk)||util.isString(chunk)||util.isNullOrUndefined(chunk)||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,util.isNull(ret)&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),util.isNull(ret)||this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),!1===dest.write(chunk)&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i1){for(var cbs=[],c=0;c=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:8}],57:[function(require,module,exports){(function(Buffer){function Level(location){if(!(this instanceof Level))return new Level(location);if(!location)throw new Error("constructor requires at least a location argument");this.IDBOptions={},this.location=location}module.exports=Level;var IDB=require("idb-wrapper"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,util=require("util"),Iterator=require("./iterator"),isBuffer=require("isbuffer"),xtend=require("xtend"),toBuffer=require("typedarray-to-buffer");util.inherits(Level,AbstractLevelDOWN),Level.prototype._open=function(options,callback){var self=this,idbOpts={storeName:this.location,autoIncrement:!1,keyPath:null,onStoreReady:function(){callback&&callback(null,self.idb)},onError:function(err){callback&&callback(err)}};xtend(idbOpts,options),this.IDBOptions=idbOpts,this.idb=new IDB(idbOpts)},Level.prototype._get=function(key,options,callback){this.idb.get(key,function(value){if(void 0===value)return callback(new Error("NotFound"));var asBuffer=!0;return!1===options.asBuffer&&(asBuffer=!1),options.raw&&(asBuffer=!1),asBuffer&&(value=value instanceof Uint8Array?toBuffer(value):new Buffer(String(value))),callback(null,value,key)},callback)},Level.prototype._del=function(id,options,callback){this.idb.remove(id,callback,callback)},Level.prototype._put=function(key,value,options,callback){value instanceof ArrayBuffer&&(value=toBuffer(new Uint8Array(value)));var obj=this.convertEncoding(key,value,options);Buffer.isBuffer(obj.value)&&("function"==typeof value.toArrayBuffer?obj.value=new Uint8Array(value.toArrayBuffer()):obj.value=new Uint8Array(value)),this.idb.put(obj.key,obj.value,function(){callback()},callback)},Level.prototype.convertEncoding=function(key,value,options){if(options.raw)return{key:key,value:value};if(value){var stringed=value.toString();"NaN"===stringed&&(value="NaN")}var valEnc=options.valueEncoding,obj={key:key,value:value};return!value||valEnc&&"binary"===valEnc||"object"!=typeof obj.value&&(obj.value=stringed),obj},Level.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),new Iterator(this.idb,options)},Level.prototype._batch=function(array,options,callback){var i,k,copiedOp,currentOp,modified=[];if(0===array.length)return setTimeout(callback,0);for(i=0;i0&&this._count++>=this._limit&&(shouldCall=!1),shouldCall&&this.callback(!1,cursor.key,cursor.value),cursor&&cursor.continue()},Iterator.prototype._next=function(callback){return callback?this._keyRangeError?callback():(this._started||(this.createIterator(),this._started=!0),void(this.callback=callback)):new Error("next() requires a callback argument")}},{"abstract-leveldown":61,ltgt:79,util:134}],59:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;if(err=this._db._checkKeyValue(value,"value",this._db._isBuffer))throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:84}],60:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{_process:84,dup:14}],61:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");if("object"!=typeof options&&(options={}),"function"==typeof this._open)return this._open(options,callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.close=function(callback){if("function"!=typeof callback)throw new Error("close() requires a callback argument");if("function"==typeof this._close)return this._close(callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(err=this._checkKeyValue(value,"value",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));"object"!=typeof options&&(options={});for(var e,err,i=0,l=array.length;i2?arguments[2]:null;if(l===+l)for(i=0;i=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],66:[function(require,module,exports){!function(){"use strict";var keysShim,has=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,forEach=require("./foreach"),isArgs=require("./isArguments"),hasDontEnumBug=!{toString:null}.propertyIsEnumerable("toString"),hasProtoEnumBug=function(){}.propertyIsEnumerable("prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];keysShim=function(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toString.call(object),isArguments=isArgs(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");if(isArguments)forEach(object,function(value){theKeys.push(value)});else{var name,skipProto=hasProtoEnumBug&&isFunction;for(name in object)skipProto&&"prototype"===name||!has.call(object,name)||theKeys.push(name)}if(hasDontEnumBug){var ctor=object.constructor,skipConstructor=ctor&&ctor.prototype===object;forEach(dontEnums,function(dontEnum){skipConstructor&&"constructor"===dontEnum||!has.call(object,dontEnum)||theKeys.push(dontEnum)})}return theKeys},module.exports=keysShim}()},{"./foreach":63,"./isArguments":65}],67:[function(require,module,exports){function hasKeys(source){return null!==source&&("object"==typeof source||"function"==typeof source)}module.exports=hasKeys},{}],68:[function(require,module,exports){function extend(){for(var target={},i=0;i-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 getMapData(map,key){var data=map.__data__;return isKeyable(key)?data["string"==typeof key?"string":"hash"]:data.map}function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function toSource(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+""}catch(e){}}return""}function eq(value,other){return value===other||value!==value&&other!==other}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 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 difference=function(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}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=120&&array.length>=120)?new SetCache(othIndex&&array):void 0}array=arrays[0];var index=-1,seen=caches[0];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}var HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,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.*?")+"$"),splice=arrayProto.splice,nativeMax=Math.max,nativeMin=Math.min,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 intersection=function(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}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;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&COMPARE_UNORDERED_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 null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function stubArray(){return[]}function stubFalse(){return!1}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",asyncTag="[object AsyncFunction]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",nullTag="[object Null]",objectTag="[object Object]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",undefinedTag="[object Undefined]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,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["[object WeakMap]"]=!1;var 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&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),nativeObjectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Buffer=moduleExports?root.Buffer:void 0,Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),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;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 getSymbols=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray,getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&"[object Promise]"!=getTag(Promise.resolve())||Set&&getTag(new Set)!=setTag||WeakMap&&"[object WeakMap]"!=getTag(new WeakMap))&&(getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return"[object Promise]";case setCtorString:return setTag;case weakMapCtorString:return"[object WeakMap]"}return result});var isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isBuffer=nativeIsBuffer||stubFalse,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray;module.exports=isEqual}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],75:[function(require,module,exports){function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if("number"==typeof value&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){for(;low>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?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=length?array:baseSlice(array,start,end)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=void 0===start?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}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))===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 FUNC_ERROR_TEXT="Expected a function",INFINITY=1/0,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString,nativeMax=Math.max;module.exports=spread},{}],77:[function(require,module,exports){(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 baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=!0,result=[],seen=result;if(comparator)isCommon=!1,includes=arrayIncludesWith;else if(length>=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__",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]==1/0?function(values){return new Set(values)}:noop,union=function(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}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){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexb?1:0};var lowerBoundKey=exports.lowerBoundKey=function(range){return hasKey(range,"gt")||hasKey(range,"gte")||hasKey(range,"min")||(range.reverse?hasKey(range,"end"):hasKey(range,"start"))||void 0},lowerBound=exports.lowerBound=function(range,def){var k=lowerBoundKey(range);return k?range[k]:def},lowerBoundInclusive=exports.lowerBoundInclusive=function(range){return!has(range,"gt")},upperBoundInclusive=exports.upperBoundInclusive=function(range){return!has(range,"lt")},lowerBoundExclusive=exports.lowerBoundExclusive=function(range){return!lowerBoundInclusive(range)},upperBoundExclusive=exports.upperBoundExclusive=function(range){return!upperBoundInclusive(range)},upperBoundKey=exports.upperBoundKey=function(range){return hasKey(range,"lt")||hasKey(range,"lte")||hasKey(range,"max")||(range.reverse?hasKey(range,"start"):hasKey(range,"end"))||void 0},upperBound=exports.upperBound=function(range,def){var k=upperBoundKey(range);return k?range[k]:def};exports.start=function(range,def){return range.reverse?upperBound(range,def):lowerBound(range,def)},exports.end=function(range,def){return range.reverse?lowerBound(range,def):upperBound(range,def)},exports.startInclusive=function(range){return range.reverse?upperBoundInclusive(range):lowerBoundInclusive(range)},exports.endInclusive=function(range){return range.reverse?lowerBoundInclusive(range):upperBoundInclusive(range)},exports.toLtgt=function(range,_range,map,lower,upper){_range=_range||{},map=map||id;var defaults=arguments.length>3,lb=exports.lowerBoundKey(range),ub=exports.upperBoundKey(range);return lb?"gt"===lb?_range.gt=map(range.gt,!1):_range.gte=map(range[lb],!1):defaults&&(_range.gte=map(lower,!1)),ub?"lt"===ub?_range.lt=map(range.lt,!0):_range.lte=map(range[ub],!0):defaults&&(_range.lte=map(upper,!0)),null!=range.reverse&&(_range.reverse=!!range.reverse),has(_range,"max")&&delete _range.max,has(_range,"min")&&delete _range.min,has(_range,"start")&&delete _range.start,has(_range,"end")&&delete _range.end,_range},exports.contains=function(range,key,compare){compare=compare||exports.compare;var lb=lowerBound(range);if(isDef(lb)){var cmp=compare(key,lb);if(cmp<0||0===cmp&&lowerBoundExclusive(range))return!1}var ub=upperBound(range);if(isDef(ub)){var cmp=compare(key,ub);if(cmp>0||0===cmp&&upperBoundExclusive(range))return!1}return!0},exports.filter=function(range,compare){return function(key){return exports.contains(range,key,compare)}}}).call(this,{isBuffer:require("../is-buffer/index.js")})},{"../is-buffer/index.js":42}],80:[function(require,module,exports){const getNGramsOfMultipleLengths=function(inputArray,nGramLengths){var outputArray=[];return nGramLengths.forEach(function(len){outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,len))}),outputArray},getNGramsOfRangeOfLengths=function(inputArray,nGramLengths){for(var outputArray=[],i=nGramLengths.gte;i<=nGramLengths.lte;i++)outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,i));return outputArray},getNGramsOfSingleLength=function(inputArray,nGramLength){return inputArray.slice(nGramLength-1).map(function(item,i){return inputArray.slice(i,i+nGramLength)})};exports.ngram=function(inputArray,nGramLength){switch(nGramLength.constructor){case Array: +return getNGramsOfMultipleLengths(inputArray,nGramLength);case Number:return getNGramsOfSingleLength(inputArray,nGramLength);case Object:return getNGramsOfRangeOfLengths(inputArray,nGramLength)}}},{}],81:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:135}],82:[function(require,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],83:[function(require,module,exports){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i1)for(var i=1;i0,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)};module.exports=pump},{"end-of-stream":33,fs:6,once:81}],87:[function(require,module,exports){var pump=require("pump"),inherits=require("inherits"),Duplexify=require("duplexify"),toArray=function(args){return args.length?Array.isArray(args[0])?args[0]:Array.prototype.slice.call(args):[]},define=function(opts){var Pumpify=function(){var streams=toArray(arguments);if(!(this instanceof Pumpify))return new Pumpify(streams);Duplexify.call(this,null,null,opts),streams.length&&this.setPipeline(streams)};return inherits(Pumpify,Duplexify),Pumpify.prototype.setPipeline=function(){var streams=toArray(arguments),self=this,ended=!1,w=streams[0],r=streams[streams.length-1];r=r.readable?r:null,w=w.writable?w:null;var onclose=function(){streams[0].emit("error",new Error("stream was destroyed"))};if(this.on("close",onclose),this.on("prefinish",function(){ended||self.cork()}),pump(streams,function(err){if(self.removeListener("close",onclose),err)return self.destroy(err);ended=!0,self.uncork()}),this.destroyed)return onclose();this.setWritable(w),this.setReadable(r)},Pumpify};module.exports=define({destroy:!1}),module.exports.obj=define({destroy:!1,objectMode:!0,highWaterMark:16})},{duplexify:30,inherits:40,pump:86}],88:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":89}],89:[function(require,module,exports){"use strict";function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var processNextTick=require("process-nextick-args"),objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v0?("string"==typeof chunk||Object.getPrototypeOf(chunk)===Buffer.prototype||state.objectMode||(chunk=_uint8ArrayToBuffer(chunk)),addToFront?state.endEmitted?stream.emit("error",new Error("stream.unshift() after end event")):addChunk(stream,state,chunk,!0):state.ended?stream.emit("error",new Error("stream.push() after EOF")):(state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1))):addToFront||(state.reading=!1)}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0===(n-=nb)){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0===(n-=nb)){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1,!1!==dest.write(chunk)||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=_isUint8Array(chunk)&&!state.objectMode;return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){this.end(),cb(err)}}).call(this,require("_process"))},{"./_stream_duplex":89,"./internal/streams/destroy":95,"./internal/streams/stream":96,_process:84,"core-util-is":10,inherits:40,"process-nextick-args":83,"safe-buffer":101,"util-deprecate":131}],94:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function copyBuffer(src,target,offset){src.copy(target,offset)}var Buffer=require("safe-buffer").Buffer;module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return Buffer.alloc(0);if(1===this.length)return this.head.data;for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret},BufferList}()},{"safe-buffer":101}],95:[function(require,module,exports){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed)return void(cb?cb(err):!err||this._writableState&&this._writableState.errorEmitted||processNextTick(emitErrorNT,this,err));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?(processNextTick(emitErrorNT,_this,err),_this._writableState&&(_this._writableState.errorEmitted=!0)):cb&&cb(err)})}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":83}],96:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:37}],97:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":98}],98:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":89,"./lib/_stream_passthrough.js":90,"./lib/_stream_readable.js":91,"./lib/_stream_transform.js":92,"./lib/_stream_writable.js":93}],99:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":98}],100:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":93}],101:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:8}],102:[function(require,module,exports){function throwsMessage(err){return"[Throws: "+(err?err.message:"?")+"]"}function safeGetValueFromPropertyOnObject(obj,property){if(hasProp.call(obj,property))try{return obj[property]}catch(err){return throwsMessage(err)}return obj[property]}function ensureProperties(obj){function visit(obj){if(null===obj||"object"!=typeof obj)return obj;if(-1!==seen.indexOf(obj))return"[Circular]";if(seen.push(obj),"function"==typeof obj.toJSON)try{return visit(obj.toJSON())}catch(err){return throwsMessage(err)}return Array.isArray(obj)?obj.map(visit):Object.keys(obj).reduce(function(result,prop){return result[prop]=visit(safeGetValueFromPropertyOnObject(obj,prop)),result},{})}var seen=[];return visit(obj)}var hasProp=Object.prototype.hasOwnProperty;module.exports=function(data){return JSON.stringify(ensureProperties(data))},module.exports.ensureProperties=ensureProperties},{}],103:[function(require,module,exports){const DBEntries=require("./lib/delete.js").DBEntries,DBWriteCleanStream=require("./lib/replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./lib/replicate.js").DBWriteMergeStream,DocVector=require("./lib/delete.js").DocVector,IndexBatch=require("./lib/add.js").IndexBatch,Readable=require("stream").Readable,RecalibrateDB=require("./lib/delete.js").RecalibrateDB,bunyan=require("bunyan"),del=require("./lib/delete.js"),docProc=require("docproc"),levelup=require("levelup"),pumpify=require("pumpify"),async=require("async");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){var Indexer={};Indexer.options=options;var q=async.queue(function(batch,done){var s;"add"===batch.operation?(s=new Readable({objectMode:!0}),batch.batch.forEach(function(doc){s.push(doc)}),s.push(null),s.pipe(Indexer.defaultPipeline(batch.batchOps)).pipe(Indexer.add()).on("finish",function(){return done()}).on("error",function(err){return done(err)})):"delete"===batch.operation&&(s=new Readable,batch.docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)}))},1);return Indexer.add=function(){return pumpify.obj(new IndexBatch(Indexer),new DBWriteMergeStream(options))},Indexer.concurrentAdd=function(batchOps,batch,done){q.push({batch:batch,batchOps:batchOps,operation:"add"},function(err){done(err)})},Indexer.concurrentDel=function(docIds,done){q.push({docIds:docIds,operation:"delete"},function(err){done(err)})},Indexer.close=function(callback){options.indexes.close(function(err){for(;!options.indexes.isClosed();)options.log.debug("closing...");options.indexes.isClosed()&&(options.log.debug("closed..."),callback(err))})},Indexer.dbWriteStream=function(streamOps){return streamOps=Object.assign({},{merge:!0},streamOps),streamOps.merge?new DBWriteMergeStream(options):new DBWriteCleanStream(options)},Indexer.defaultPipeline=function(batchOptions){return batchOptions=Object.assign({},options,batchOptions),docProc.pipeline(batchOptions)},Indexer.deleteStream=function(options){return pumpify.obj(new DocVector(options),new DBEntries(options),new RecalibrateDB(options))},Indexer.deleter=function(docIds,done){const s=new Readable;docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)})},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{deletable:!0,batchSize:1e3,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0},options),options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)done(null,options);else{const leveldown=require("leveldown");levelup(options.indexPath||"si",{valueEncoding:"json",db:leveldown},function(err,db){options.indexes=db,done(err,options)})}}},{"./lib/add.js":104,"./lib/delete.js":105,"./lib/replicate.js":106,async:4,bunyan:9,docproc:18,leveldown:57,levelup:70,pumpify:87,stream:125}],104:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),emitIndexKeys=function(s){for(var key in s.deltaIndex)s.push({key:key,value:s.deltaIndex[key]});s.deltaIndex={}},IndexBatch=function(indexer){this.indexer=indexer,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.indexer.options.keySeparator;var that=this;this.indexer.deleter([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.indexer.options.log.info("processing doc "+ingestedDoc.id),that.deltaIndex["DOCUMENT"+sep+ingestedDoc.id+sep]=ingestedDoc.stored;for(var fieldName in ingestedDoc.vector){that.deltaIndex["FIELD"+sep+fieldName]=fieldName;for(var token in ingestedDoc.vector[fieldName]){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token,dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id]),that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.deltaIndex["DOCUMENT-VECTOR"+sep+ingestedDoc.id+sep+fieldName+sep]=ingestedDoc.vector[fieldName]}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.indexer.options.batchSize&&(that.push({totalKeys:totalKeys}),that.indexer.options.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:125,util:134}],105:[function(require,module,exports){const util=require("util"),Transform=require("stream").Transform;exports.flush=function(options,callback){const sep=options.keySeparator;var deleteOps=[];options.indexes.createKeyStream({gte:"0",lte:sep}).on("data",function(data){deleteOps.push({type:"del",key:data})}).on("error",function(err){return options.log.error(err," failed to empty index"),callback(err)}).on("end",function(){options.indexes.batch(deleteOps,callback)})};const DocVector=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DocVector=DocVector,util.inherits(DocVector,Transform),DocVector.prototype._transform=function(docId,encoding,end){docId=JSON.parse(docId);const sep=this.options.keySeparator;var that=this;this.options.indexes.createReadStream({gte:"DOCUMENT-VECTOR"+sep+docId+sep,lte:"DOCUMENT-VECTOR"+sep+docId+sep+sep}).on("data",function(data){that.push(data)}).on("close",function(){return end()})};const DBEntries=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBEntries=DBEntries,util.inherits(DBEntries,Transform),DBEntries.prototype._transform=function(vector,encoding,end){const sep=this.options.keySeparator;var docId;for(var k in vector.value){docId=vector.key.split(sep)[1];var field=vector.key.split(sep)[2];this.push({key:"TF"+sep+field+sep+k,value:docId}),this.push({key:"DF"+sep+field+sep+k,value:docId})}return this.push({key:vector.key}),this.push({key:"DOCUMENT"+sep+docId+sep}),end()};const RecalibrateDB=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.RecalibrateDB=RecalibrateDB,util.inherits(RecalibrateDB,Transform),RecalibrateDB.prototype._transform=function(dbEntry,encoding,end){const sep=this.options.keySeparator;var that=this;this.options.indexes.get(dbEntry.key,function(err,value){err&&that.options.log.info(err),value||(value=[]);var docId=dbEntry.value,dbInstruction={};dbInstruction.key=dbEntry.key,dbEntry.key.substring(0,3)==="TF"+sep?(dbInstruction.value=value.filter(function(item){return item[1]!==docId}),0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,3)==="DF"+sep?(value.splice(value.indexOf(docId),1),dbInstruction.value=value,0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,9)==="DOCUMENT"+sep?dbInstruction.type="del":dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep&&(dbInstruction.type="del"),that.options.indexes.batch([dbInstruction],function(err){return end()})})}},{stream:125,util:134}],106:[function(require,module,exports){const Transform=require("stream").Transform,Writable=require("stream").Writable,util=require("util"),DBWriteMergeStream=function(options){this.options=options,Writable.call(this,{objectMode:!0})};exports.DBWriteMergeStream=DBWriteMergeStream,util.inherits(DBWriteMergeStream,Writable),DBWriteMergeStream.prototype._write=function(data,encoding,end){if(data.totalKeys)return end();const sep=this.options.keySeparator;var that=this;this.options.indexes.get(data.key,function(err,val){var newVal;newVal=data.key.substring(0,3)==="TF"+sep?data.value.concat(val||[]).sort(function(a,b){return a[0]b[0]?-1:a[1]b[1]?-1:0}):data.key.substring(0,3)==="DF"+sep?data.value.concat(val||[]).sort():"DOCUMENT-COUNT"===data.key?+val+(+data.value||0):data.value,that.options.indexes.put(data.key,newVal,function(err){end()})})};const DBWriteCleanStream=function(options){this.currentBatch=[],this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(DBWriteCleanStream,Transform),DBWriteCleanStream.prototype._transform=function(data,encoding,end){var that=this;this.currentBatch.push(data),this.currentBatch.length%this.options.batchSize==0?this.options.indexes.batch(this.currentBatch,function(err){that.push("indexing batch"),that.currentBatch=[],end()}):end()},DBWriteCleanStream.prototype._flush=function(end){var that=this;this.options.indexes.batch(this.currentBatch,function(err){that.push("remaining data indexed"),end()})},exports.DBWriteCleanStream=DBWriteCleanStream},{stream:125,util:134}],107:[function(require,module,exports){const AvailableFields=require("./lib/AvailableFields.js").AvailableFields,CalculateBuckets=require("./lib/CalculateBuckets.js").CalculateBuckets,CalculateCategories=require("./lib/CalculateCategories.js").CalculateCategories,CalculateEntireResultSet=require("./lib/CalculateEntireResultSet.js").CalculateEntireResultSet,CalculateResultSetPerClause=require("./lib/CalculateResultSetPerClause.js").CalculateResultSetPerClause,CalculateTopScoringDocs=require("./lib/CalculateTopScoringDocs.js").CalculateTopScoringDocs,CalculateTotalHits=require("./lib/CalculateTotalHits.js").CalculateTotalHits,Classify=require("./lib/Classify.js").Classify,FetchDocsFromDB=require("./lib/FetchDocsFromDB.js").FetchDocsFromDB,FetchStoredDoc=require("./lib/FetchStoredDoc.js").FetchStoredDoc,GetIntersectionStream=require("./lib/GetIntersectionStream.js").GetIntersectionStream,MergeOrConditions=require("./lib/MergeOrConditions.js").MergeOrConditions,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,SortTopScoringDocs=require("./lib/SortTopScoringDocs.js").SortTopScoringDocs,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),initModule=function(err,Searcher,moduleReady){return Searcher.bucketStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateBuckets(Searcher.options,q.filter||{},q.buckets))},Searcher.categoryStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateCategories(Searcher.options,q))},Searcher.classify=function(ops){return new Classify(Searcher,ops)},Searcher.close=function(callback){Searcher.options.indexes.close(function(err){for(;!Searcher.options.indexes.isClosed();)Searcher.options.log.debug("closing...");Searcher.options.indexes.isClosed()&&(Searcher.options.log.debug("closed..."),callback(err))})},Searcher.availableFields=function(){const sep=Searcher.options.keySeparator;return Searcher.options.indexes.createReadStream({gte:"FIELD"+sep,lte:"FIELD"+sep+sep}).pipe(new AvailableFields(Searcher.options))},Searcher.get=function(docIDs){var s=new Readable({objectMode:!0});return docIDs.forEach(function(id){s.push(id)}),s.push(null),s.pipe(new FetchDocsFromDB(Searcher.options))},Searcher.fieldNames=function(){return Searcher.options.indexes.createReadStream({gte:"FIELD",lte:"FIELD"})},Searcher.match=function(q){return matcher.match(q,Searcher.options)},Searcher.dbReadStream=function(){return Searcher.options.indexes.createReadStream()},Searcher.search=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),q.sort?s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options)):s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreTopScoringDocsTFIDF(Searcher.options)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options))},Searcher.scan=function(q){q=siUtil.getQueryDefaults(q);var s=new Readable({objectMode:!0});return s.push("init"),s.push(null),s.pipe(new GetIntersectionStream(Searcher.options,siUtil.getKeySet(q.query[0].AND,Searcher.options.keySeparator))).pipe(new FetchDocsFromDB(Searcher.options))},Searcher.totalHits=function(q,callback){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateTotalHits(Searcher.options)).on("data",function(totalHits){return callback(null,totalHits)})},moduleReady(err,Searcher)},getOptions=function(options,done){var Searcher={};if(Searcher.options=Object.assign({},{deletable:!0,fieldedSearch:!0,store:!0,indexPath:"si",keySeparator:"○",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:[]},options),Searcher.options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)return done(null,Searcher);levelup(Searcher.options.indexPath||"si",{valueEncoding:"json"},function(err,db){return Searcher.options.indexes=db,done(err,Searcher)})};module.exports=function(givenOptions,moduleReady){getOptions(givenOptions,function(err,Searcher){initModule(err,Searcher,moduleReady)})}},{"./lib/AvailableFields.js":108,"./lib/CalculateBuckets.js":109,"./lib/CalculateCategories.js":110,"./lib/CalculateEntireResultSet.js":111,"./lib/CalculateResultSetPerClause.js":112,"./lib/CalculateTopScoringDocs.js":113,"./lib/CalculateTotalHits.js":114,"./lib/Classify.js":115,"./lib/FetchDocsFromDB.js":116,"./lib/FetchStoredDoc.js":117,"./lib/GetIntersectionStream.js":118,"./lib/MergeOrConditions.js":119,"./lib/ScoreDocsOnField.js":120,"./lib/ScoreTopScoringDocsTFIDF.js":121,"./lib/SortTopScoringDocs.js":122,"./lib/matcher.js":123,"./lib/siUtil.js":124,bunyan:9,levelup:70,stream:125}],108:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),AvailableFields=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.AvailableFields=AvailableFields,util.inherits(AvailableFields,Transform),AvailableFields.prototype._transform=function(field,encoding,end){return this.push(field.key.split(this.options.keySeparator)[1]),end()}},{stream:125,util:134}],109:[function(require,module,exports){const _intersection=require("lodash.intersection"),_uniq=require("lodash.uniq"),Transform=require("stream").Transform,util=require("util"),CalculateBuckets=function(options,filter,requestedBuckets){this.buckets=requestedBuckets||[],this.filter=filter,this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateBuckets=CalculateBuckets,util.inherits(CalculateBuckets,Transform),CalculateBuckets.prototype._transform=function(mergedQueryClauses,encoding,end){const that=this,sep=this.options.keySeparator;var bucketsProcessed=0;that.buckets.forEach(function(bucket){const gte="DF"+sep+bucket.field+sep+bucket.gte,lte="DF"+sep+bucket.field+sep+bucket.lte+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){var IDSet=_intersection(data.value,mergedQueryClauses.set);IDSet.length>0&&(bucket.value=bucket.value||[],bucket.value=_uniq(bucket.value.concat(IDSet).sort()))}).on("close",function(){if(bucket.set||(bucket.value=bucket.value.length),that.push(bucket),++bucketsProcessed===that.buckets.length)return end()})})}},{"lodash.intersection":73,"lodash.uniq":78,stream:125,util:134}],110:[function(require,module,exports){const _intersection=require("lodash.intersection"),Transform=require("stream").Transform,util=require("util"),CalculateCategories=function(options,q){var category=q.category||[];category.values=[],this.offset=+q.offset,this.pageSize=+q.pageSize,this.category=category,this.options=options,this.query=q.query,Transform.call(this,{objectMode:!0})};exports.CalculateCategories=CalculateCategories,util.inherits(CalculateCategories,Transform),CalculateCategories.prototype._transform=function(mergedQueryClauses,encoding,end){if(!this.category.field)return end(new Error("you need to specify a category"));const sep=this.options.keySeparator,that=this,gte="DF"+sep+this.category.field+sep,lte="DF"+sep+this.category.field+sep+sep;this.category.values=this.category.values||[];var i=this.offset+this.pageSize,j=0;const rs=that.options.indexes.createReadStream({gte:gte,lte:lte});rs.on("data",function(data){if(!(that.offset>j++)){var IDSet=_intersection(data.value,mergedQueryClauses.set);if(IDSet.length>0){var key=data.key.split(sep)[2],value=IDSet.length;that.category.set&&(value=IDSet);var result={key:key,value:value};if(1===that.query.length)try{that.query[0].AND[that.category.field].indexOf(key)>-1&&(result.filter=!0)}catch(e){}i-- >that.offset?that.push(result):rs.destroy()}}}).on("close",function(){return end()})}},{"lodash.intersection":73,stream:125,util:134}],111:[function(require,module,exports){const Transform=require("stream").Transform,_union=require("lodash.union"),util=require("util"),CalculateEntireResultSet=function(options){this.options=options,this.setSoFar=[],Transform.call(this,{objectMode:!0})};exports.CalculateEntireResultSet=CalculateEntireResultSet,util.inherits(CalculateEntireResultSet,Transform),CalculateEntireResultSet.prototype._transform=function(queryClause,encoding,end){return this.setSoFar=_union(queryClause.set,this.setSoFar),end()},CalculateEntireResultSet.prototype._flush=function(end){return this.push({set:this.setSoFar}),end()}},{"lodash.union":77,stream:125,util:134}],112:[function(require,module,exports){const Transform=require("stream").Transform,_difference=require("lodash.difference"),_intersection=require("lodash.intersection"),_spread=require("lodash.spread"),siUtil=require("./siUtil.js"),util=require("util"),CalculateResultSetPerClause=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateResultSetPerClause=CalculateResultSetPerClause,util.inherits(CalculateResultSetPerClause,Transform),CalculateResultSetPerClause.prototype._transform=function(queryClause,encoding,end){const sep=this.options.keySeparator,that=this,frequencies=[];var NOT=function(includeResults){const bigIntersect=_spread(_intersection);var include=bigIntersect(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,termFrequencies:frequencies,BOOST:queryClause.BOOST||0}),end();var i=0,excludeResults=[];siUtil.getKeySet(queryClause.NOT,sep).forEach(function(item){var excludeSet={};that.options.indexes.createReadStream({gte:item[0],lte:item[1]+sep}).on("data",function(data){for(var i=0;ib.id?-1:0}).reduce(function(merged,cur){var lastDoc=merged[merged.length-1];return 0===merged.length||cur.id!==lastDoc.id?merged.push(cur):cur.id===lastDoc.id&&(lastDoc.scoringCriteria=lastDoc.scoringCriteria.concat(cur.scoringCriteria)),merged},[]);return mergedResultSet.map(function(item){return item.scoringCriteria&&(item.score=item.scoringCriteria.reduce(function(acc,val){return{score:+acc.score+ +val.score}},{score:0}).score,item.score=item.score/item.scoringCriteria.length),item}),mergedResultSet.forEach(function(item){that.push(item)}),end()}},{stream:125,util:134}],120:[function(require,module,exports){const Transform=require("stream").Transform,_sortedIndexOf=require("lodash.sortedindexof"),util=require("util"),ScoreDocsOnField=function(options,seekLimit,sort){this.options=options,this.seekLimit=seekLimit,this.sort=sort,Transform.call(this,{objectMode:!0})};exports.ScoreDocsOnField=ScoreDocsOnField,util.inherits(ScoreDocsOnField,Transform),ScoreDocsOnField.prototype._transform=function(clauseSet,encoding,end){const sep=this.options.keySeparator,that=this,gte="TF"+sep+this.sort.field+sep,lte="TF"+sep+this.sort.field+sep+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){for(var i=0;ib.score?-2:a.idb.id?-1:0}):this.resultSet=this.resultSet.sort(function(a,b){return a.score>b.score?2:a.scoreb.id?-1:0}),this.resultSet=this.resultSet.slice(this.q.offset,this.q.offset+this.q.pageSize),this.resultSet.forEach(function(hit){that.push(hit)}),end()}},{stream:125,util:134}],123:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatcherStream=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatcherStream,Transform),MatcherStream.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var results=[];this.options.indexes.createReadStream({start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep}).on("data",function(data){results.push(data)}).on("error",function(err){that.options.log.error("Oh my!",err)}).on("end",function(){return results.sort(function(a,b){return b.value.length-a.value.length}).slice(0,q.limit).forEach(function(item){var m={};switch(q.type){case"ID":m={token:item.key.split(sep)[2],documents:item.value};break;case"count":m={token:item.key.split(sep)[2],documentCount:item.value.length};break;default:m=item.key.split(sep)[2]}that.push(m)}),end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple"},q),q.beginsWith.length>5==6?2:byte>>4==14?3:byte>>3==30?4:-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=0?(nb>0&&(self.lastNeed=nb-1),nb):--j=0?(nb>0&&(self.lastNeed=nb-2),nb):--j=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"�".repeat(p);if(self.lastNeed>1&&buf.length>1){if(128!=(192&buf[1]))return self.lastNeed=1,"�".repeat(p+1);if(self.lastNeed>2&&buf.length>2&&128!=(192&buf[2]))return self.lastNeed=2,"�".repeat(p+2)}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�".repeat(this.lastTotal-this.lastNeed):r}function utf16Text(buf,i){if((buf.length-i)%2==0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch((encoding=""+encoding)&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(void 0===(r=this.fillLast(buf)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return itokens.length)return[];for(var ngrams=[],i=0;i<=tokens.length-nGramLength;i++)ngrams.push(tokens.slice(i,i+nGramLength));if(ngrams=ngrams.sort(),1===ngrams.length)return[[ngrams[0],1]];for(var counter=1,lastToken=ngrams[0],vector=[],j=1;j=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];i=4" @@ -10,7 +10,7 @@ "dependencies": { "bunyan": "^1.8.10", "levelup": "^1.3.8", - "search-index-adder": "^0.2.5", + "search-index-adder": "^0.3.0", "search-index-searcher": "^0.2.3" }, "devDependencies": { diff --git a/test/node/mocha-tests/328-test.js b/test/node/mocha-tests/328-test.js index 5e1a3488..b7dff9e7 100644 --- a/test/node/mocha-tests/328-test.js +++ b/test/node/mocha-tests/328-test.js @@ -48,7 +48,7 @@ describe('bug 328', function() { .on('data', function (data) { // nowt }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/boost-test.js b/test/node/mocha-tests/boost-test.js index c02e6ecf..1fdd0713 100644 --- a/test/node/mocha-tests/boost-test.js +++ b/test/node/mocha-tests/boost-test.js @@ -98,10 +98,7 @@ describe('boosting', function () { si = thisSI s.pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) { - // nowt - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/bucket-test.js b/test/node/mocha-tests/bucket-test.js index e76b68d9..d43d0543 100644 --- a/test/node/mocha-tests/bucket-test.js +++ b/test/node/mocha-tests/bucket-test.js @@ -56,8 +56,7 @@ describe('init the search index', function() { getStream() .pipe(index.defaultPipeline()) .pipe(index.add()) - .on('data', function (data) {}) - .on('end', function () { + .on('finish', function () { return done() }) }) diff --git a/test/node/mocha-tests/delete-test.js b/test/node/mocha-tests/delete-test.js index 6f494854..df01fd6e 100644 --- a/test/node/mocha-tests/delete-test.js +++ b/test/node/mocha-tests/delete-test.js @@ -51,7 +51,7 @@ describe('deleting: ', function () { s.push(null) s.pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) {}).on('end', function () { + .on('finish', function () { done() }) }) @@ -102,10 +102,7 @@ describe('deleting: ', function () { s.push(null) s.pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { done() }) }) diff --git a/test/node/mocha-tests/facet-test.js b/test/node/mocha-tests/facet-test.js index e062e9e3..2cef5870 100644 --- a/test/node/mocha-tests/facet-test.js +++ b/test/node/mocha-tests/facet-test.js @@ -116,8 +116,7 @@ describe('categories: ', function () { s.pipe(JSONStream.parse()) .pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) {}) - .on('end', function () { + .on('finish', function () { return done() }) }) diff --git a/test/node/mocha-tests/fieldsToStore-test.js b/test/node/mocha-tests/fieldsToStore-test.js index c5600eb8..850d0a6a 100644 --- a/test/node/mocha-tests/fieldsToStore-test.js +++ b/test/node/mocha-tests/fieldsToStore-test.js @@ -106,10 +106,7 @@ describe('storing fields: ', function () { } })) .pipe(si.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) @@ -161,7 +158,7 @@ describe('storing fields: ', function () { .pipe(si2.add()) .on('data', function (data) { }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/flush-test.js b/test/node/mocha-tests/flush-test.js index 4769ab84..3731ebd1 100644 --- a/test/node/mocha-tests/flush-test.js +++ b/test/node/mocha-tests/flush-test.js @@ -96,10 +96,7 @@ describe('boosting', function () { si = thisSI s.pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) { - // nowt - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/get-test.js b/test/node/mocha-tests/get-test.js index ba65fe3e..14624bb0 100644 --- a/test/node/mocha-tests/get-test.js +++ b/test/node/mocha-tests/get-test.js @@ -48,8 +48,7 @@ describe('.get-ting: ', function () { }) s.push(null) s.pipe(si.defaultPipeline()) - .pipe(si.add()) - .on('data', function (data) {}).on('end', function () { + .pipe(si.add()).on('finish', function () { done() }) }) diff --git a/test/node/mocha-tests/indexing-test-2.js b/test/node/mocha-tests/indexing-test-2.js index ea0e9f76..aeaac481 100644 --- a/test/node/mocha-tests/indexing-test-2.js +++ b/test/node/mocha-tests/indexing-test-2.js @@ -42,8 +42,7 @@ describe('Indexing API', function () { // jshint ignore:line var i = 0 s.pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) {}) - .on('end', function () { + .on('finish', function () { si.dbReadStream() .on('data', function (data) { i++ diff --git a/test/node/mocha-tests/indexing-test.js b/test/node/mocha-tests/indexing-test.js index 6637ec66..2a63f848 100644 --- a/test/node/mocha-tests/indexing-test.js +++ b/test/node/mocha-tests/indexing-test.js @@ -31,15 +31,16 @@ describe('Indexing API', function () { } s.push(doc) s.push(null) - s.pipe(si.defaultPipeline()).pipe(si.add()) - .on('data', function (data) {}) - .on('end', function () { - si.get(['1']).on('data', function (data) { - data.should.eql(doc) - }) - .on('end', function () { - return done() - }) + s.pipe(si.defaultPipeline()) + .pipe(si.add()) + .on('finish', function () { + si.get(['1']) + .on('data', function (data) { + data.should.eql(doc) + }) + .on('end', function () { + return done() + }) }) }) @@ -54,8 +55,7 @@ describe('Indexing API', function () { s.push(null) s.pipe(si.defaultPipeline()) .pipe(si.add(undefined)) - .on('data', function (data) {}) - .on('end', function () { + .on('finish', function () { si.get(['2']).on('data', function (data) { data.should.eql(doc) }) @@ -77,8 +77,7 @@ describe('Indexing API', function () { s.pipe(si.defaultPipeline({ separator: /\s+/ })).pipe(si.add()) - .on('data', function (data) {}) - .on('end', function () { + .on('finish', function () { si.search({ query: [{ AND: {'*': ['14.2.1.0']} @@ -105,8 +104,7 @@ describe('Indexing API', function () { s.pipe(si.defaultPipeline({ separator: /\s+/ })).pipe(si.add()) - .on('data', function (data) {}) - .on('end', function () { + .on('finish', function () { si.search({ query: [{ AND: {'*': ['14.2.1.0']} diff --git a/test/node/mocha-tests/instantiation-test.js b/test/node/mocha-tests/instantiation-test.js index 7018f2ce..e56751b3 100644 --- a/test/node/mocha-tests/instantiation-test.js +++ b/test/node/mocha-tests/instantiation-test.js @@ -62,8 +62,7 @@ describe('Instantiation: ', function () { it('should index test data into the first index', function (done) { sOne.pipe(siOne.defaultPipeline()) .pipe(siOne.add()) - .on('data', function (data) {}) - .on('end', function () { + .on('finish', function () { return done() }) }) @@ -71,8 +70,7 @@ describe('Instantiation: ', function () { it('should index test data into the second index', function (done) { sTwo.pipe(siTwo.defaultPipeline()) .pipe(siTwo.add()) - .on('data', function (data) {}) - .on('end', function () { + .on('finish', function () { return done() }) }) diff --git a/test/node/mocha-tests/matching-test.js b/test/node/mocha-tests/matching-test.js index 94756100..bca4902a 100644 --- a/test/node/mocha-tests/matching-test.js +++ b/test/node/mocha-tests/matching-test.js @@ -66,10 +66,7 @@ describe('Matching epub: ', function () { } })) .pipe(index.add()) - .on('data', function (data) { - // nowt - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/or-test.js b/test/node/mocha-tests/or-test.js index 2b06246c..bbd96f67 100644 --- a/test/node/mocha-tests/or-test.js +++ b/test/node/mocha-tests/or-test.js @@ -95,10 +95,7 @@ describe('OR-ing: ', function () { si = thisSI s.pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/phrase-search-test.js b/test/node/mocha-tests/phrase-search-test.js index 4bcbf3b0..077fc7e9 100644 --- a/test/node/mocha-tests/phrase-search-test.js +++ b/test/node/mocha-tests/phrase-search-test.js @@ -47,10 +47,7 @@ describe('ngrams (phrase search): ', function () { nGramLength: {gte: 1, lte: 3} })) .pipe(si.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) @@ -70,10 +67,7 @@ describe('ngrams (phrase search): ', function () { nGramLength: [1, 5] })) .pipe(si2.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) @@ -100,10 +94,7 @@ describe('ngrams (phrase search): ', function () { } })) .pipe(si3.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) @@ -127,10 +118,7 @@ describe('ngrams (phrase search): ', function () { } })) .pipe(si4.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/preserve-case-test.js b/test/node/mocha-tests/preserve-case-test.js index 0ef45817..dd4d0486 100644 --- a/test/node/mocha-tests/preserve-case-test.js +++ b/test/node/mocha-tests/preserve-case-test.js @@ -56,7 +56,7 @@ describe('testing case: ', function () { preserveCase: true })) .pipe(si.add()) - .on('data', function (data) {}).on('end', function () { + .on('finish', function () { done() }) }) @@ -106,7 +106,7 @@ describe('testing case: ', function () { preserveCase: false })) .pipe(si2.add()) - .on('data', function (data) {}).on('end', function () { + .on('finish', function () { done() }) }) diff --git a/test/node/mocha-tests/relevancy-test.js b/test/node/mocha-tests/relevancy-test.js index d2549e56..a2e1d9f6 100644 --- a/test/node/mocha-tests/relevancy-test.js +++ b/test/node/mocha-tests/relevancy-test.js @@ -42,10 +42,7 @@ describe('some simple relevancy tests: ', function () { si = thisSI s.pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/scan-test.js b/test/node/mocha-tests/scan-test.js index e1f484c9..554ccfa8 100644 --- a/test/node/mocha-tests/scan-test.js +++ b/test/node/mocha-tests/scan-test.js @@ -99,10 +99,7 @@ describe('scanning: ', function () { si = thisSi s.pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/search-test.js b/test/node/mocha-tests/search-test.js index 5c425b02..f10c8f05 100644 --- a/test/node/mocha-tests/search-test.js +++ b/test/node/mocha-tests/search-test.js @@ -31,9 +31,7 @@ describe('simple search test', function() { }) .pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (d) { - }) - .on('end', function () { + .on('finish', function () { i.should.be.exactly(10) return done() }) diff --git a/test/node/mocha-tests/sorting-test.js b/test/node/mocha-tests/sorting-test.js index ba59fcb4..1fc538de 100644 --- a/test/node/mocha-tests/sorting-test.js +++ b/test/node/mocha-tests/sorting-test.js @@ -110,10 +110,7 @@ describe('sorting: ', function () { } })) .pipe(si.add()) - .on('data', function (data) { - - }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/sqlite-test.js b/test/node/mocha-tests/sqlite-test.js index 285c8431..4d118fb3 100644 --- a/test/node/mocha-tests/sqlite-test.js +++ b/test/node/mocha-tests/sqlite-test.js @@ -49,9 +49,7 @@ describe('sqllite compatability: ', function () { s.push(null) s.pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) { - }) - .on('end', function () { + .on('finish', function () { si.search({ query: [{ AND: {'*': ['cool']} diff --git a/test/node/mocha-tests/stopword-test.js b/test/node/mocha-tests/stopword-test.js index 14e5b3c0..52e6daa8 100644 --- a/test/node/mocha-tests/stopword-test.js +++ b/test/node/mocha-tests/stopword-test.js @@ -76,7 +76,7 @@ describe('stopwords: ', function () { .pipe(si.add()) .on('data', function (data) { }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) @@ -113,7 +113,7 @@ describe('stopwords: ', function () { .pipe(siNO.add()) .on('data', function (data) { }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) @@ -164,7 +164,7 @@ describe('stopwords: ', function () { .pipe(siFood.add()) .on('data', function (data) { }) - .on('end', function () { + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/stream-test.js b/test/node/mocha-tests/stream-test.js index 2cdfedcb..190732f8 100644 --- a/test/node/mocha-tests/stream-test.js +++ b/test/node/mocha-tests/stream-test.js @@ -44,7 +44,7 @@ describe('stopwords: ', function () { .pipe(JSONStream.parse()) .pipe(si.defaultPipeline()) .pipe(si.add()) - .on('data', function (data) {}).on('end', function () { + .on('data', function (data) {}).on('finish', function () { done() }) }) diff --git a/test/node/tape-tests/classifier-test.js b/test/node/tape-tests/classifier-test.js index 68fd0d3c..d98f42f2 100644 --- a/test/node/tape-tests/classifier-test.js +++ b/test/node/tape-tests/classifier-test.js @@ -99,7 +99,7 @@ test('initialize a search index', function (t) { .on('data', function (data) { // tum te tum... }) - .on('end', function () { + .on('finish', function () { indexer.close(function (err) { t.error(err) }) diff --git a/test/node/tape-tests/stream-test.js b/test/node/tape-tests/stream-test.js index f87a8d43..ee953dc9 100644 --- a/test/node/tape-tests/stream-test.js +++ b/test/node/tape-tests/stream-test.js @@ -30,19 +30,11 @@ test('add docs using a stream', function (t) { s.push(null) s.pipe(index.defaultPipeline()) .pipe(index.add()) - .on('end', function () { + .on('finish', function () { t.pass('ended ok') }) }) -test('breather', function(t) { - t.plan(1) - console.log('waiting...') - setTimeout(function () { - t.pass('timeout over') - }, 1000) -}) - test('verify that large values are sorted', function (t) { t.plan(3) index.options.indexes.get('TF○text○number', function (err, val) {